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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
💬 style: Unify Message Row Layout and Edit Surfaces (#14770)
Marco Berettad920328bfa53
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.jsindex 19d4619bad..58d111a32a 100644--- a/api/app/clients/BaseClient.js+++ b/api/app/clients/BaseClient.js@@ -591,7 +591,8 @@ class BaseClient {} else if (editedContent != null) {// Handle editedContent for content partsif (editedContent && latestMessage.content && Array.isArray(latestMessage.content)) {- const { index, text, type } = editedContent;+ const { index, type } = editedContent;+ const text = editedContent[type];if (index >= 0 && index < latestMessage.content.length) {const contentPart = latestMessage.content[index];if (type === ContentTypes.THINK && contentPart.type === ContentTypes.THINK) {diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.jsindex 77848851a2..70f0a91c17 100644--- a/api/app/clients/specs/BaseClient.test.js+++ b/api/app/clients/specs/BaseClient.test.js@@ -691,6 +691,43 @@ describe('BaseClient', () => {);});+ it('applies edited reasoning content from its typed payload before regeneration', async () => {+ const responseMessageId = 'response-with-reasoning';+ const newHistory = [+ ...messageHistory,+ {+ role: 'assistant',+ isCreatedByUser: false,+ messageId: responseMessageId,+ parentMessageId: '3',+ content: [+ { type: ContentTypes.THINK, think: 'Original reasoning', phase: 'analysis' },+ { type: ContentTypes.TEXT, text: 'Original response' },+ ],+ },+ ];++ TestClient = initializeFakeClient(apiKey, options, newHistory);+ await TestClient.sendMessage('test message', {+ isEdited: true,+ overrideParentMessageId: 'user-message-id',+ parentMessageId: '3',+ responseMessageId,+ editedContent: {+ index: 0,+ type: ContentTypes.THINK,+ [ContentTypes.THINK]: 'Updated reasoning',+ },+ });++ const editedResponse = TestClient.currentMessages[TestClient.currentMessages.length - 1];+ expect(editedResponse.content[0]).toEqual({+ type: ContentTypes.THINK,+ think: 'Updated reasoning',+ phase: 'analysis',+ });+ });+test('setOptions is called with the correct arguments only when replaceOptions is set to true', async () => {TestClient.setOptions = jest.fn();const opts = { conversationId: '123', parentMessageId: '456', replaceOptions: true };diff --git a/api/server/routes/__tests__/messages-content-edit.spec.js b/api/server/routes/__tests__/messages-content-edit.spec.jsnew file mode 100644index 0000000000..5851c2a781--- /dev/null+++ b/api/server/routes/__tests__/messages-content-edit.spec.js@@ -0,0 +1,144 @@+const express = require('express');+const request = require('supertest');+const { ContentTypes } = require('librechat-data-provider');++jest.mock('@librechat/agents', () => ({+ sleep: jest.fn(),+}));++jest.mock('@librechat/api', () => ({+ unescapeLaTeX: jest.fn((value) => value),+ countTokens: jest.fn().mockResolvedValue(2),+ sendFeedbackScore: jest.fn().mockResolvedValue(undefined),+ traceIdForMessage: jest.fn((messageId) => `trace-${messageId}`),+ mergeQuotedTextForCount: jest.fn((text) => text),+}));++jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),+ logger: {+ debug: jest.fn(),+ info: jest.fn(),+ warn: jest.fn(),+ error: jest.fn(),+ },+}));++jest.mock('~/models', () => ({+ getMessages: jest.fn(),+ updateMessage: jest.fn(),+}));++jest.mock('~/server/services/Artifacts/update', () => ({+ findAllArtifacts: jest.fn(),+ replaceArtifactContent: jest.fn(),+}));++jest.mock('~/server/middleware', () => ({+ requireJwtAuth: (req, res, next) => next(),+ validateMessageReq: (req, res, next) => next(),+ configMiddleware: (req, res, next) => next(),+ sendValidationResponse: jest.fn(),+ prepareMessageRequestValidation: jest.fn(),+}));++describe('PUT /:conversationId/:messageId content edit', () => {+ let app;+ const { getMessages, updateMessage } = require('~/models');++ beforeAll(() => {+ const messagesRouter = require('../messages');+ app = express();+ app.use(express.json());+ app.use((req, res, next) => {+ req.user = { id: 'user-1' };+ next();+ });+ app.use('/api/messages', messagesRouter);+ });++ beforeEach(() => {+ jest.clearAllMocks();+ updateMessage.mockResolvedValue({ messageId: 'message-1' });+ });++ it('preserves content-part metadata when editing its text', async () => {+ getMessages.mockResolvedValue([+ {+ tokenCount: 10,+ content: [+ {+ type: ContentTypes.TEXT,+ text: 'Original response',+ phase: 'commentary',+ agentId: 'agent-1',+ tool_call_ids: ['tool-1'],+ },+ ],+ },+ ]);++ const response = await request(app)+ .put('/api/messages/conversation-1/message-1')+ .send({ index: 0, text: 'Edited response', model: 'gpt-5' });++ expect(response.status).toBe(200);+ expect(updateMessage).toHaveBeenCalledWith('user-1', {+ messageId: 'message-1',+ tokenCount: 10,+ content: [+ {+ type: ContentTypes.TEXT,+ text: 'Edited response',+ phase: 'commentary',+ agentId: 'agent-1',+ tool_call_ids: ['tool-1'],+ },+ ],+ });+ });++ /**+ * A text part is `string | { value, annotations }`. The Assistants thread sync+ * persists the structured form with its file citations intact and the editor reads+ * it through the same union, so writing the edit straight over the object dropped+ * every citation. Counting the object rather than its value is the same mistake+ * read back: the tokenizer measures `text.length`, which an object does not have,+ * so the stored count became NaN.+ */+ it('edits inside a structured text part instead of flattening it', async () => {+ const { countTokens } = require('@librechat/api');+ const annotations = [+ { type: 'file_citation', text: 'source', file_citation: { file_id: 'file-1' } },+ ];++ getMessages.mockResolvedValue([+ {+ tokenCount: 10,+ content: [+ {+ type: ContentTypes.TEXT,+ text: { value: 'Original response', annotations },+ },+ ],+ },+ ]);++ const response = await request(app)+ .put('/api/messages/conversation-1/message-1')+ .send({ index: 0, text: 'Edited response', model: 'gpt-5' });++ expect(response.status).toBe(200);+ expect(updateMessage).toHaveBeenCalledWith('user-1', {+ messageId: 'message-1',+ tokenCount: 10,+ content: [+ {+ type: ContentTypes.TEXT,+ text: { value: 'Edited response', annotations },+ },+ ],+ });+ expect(countTokens).toHaveBeenCalledWith('Original response', 'gpt-5');+ });+});diff --git a/api/server/routes/messages.js b/api/server/routes/messages.jsindex 0425b40eaa..0894e9bd1d 100644--- a/api/server/routes/messages.js+++ b/api/server/routes/messages.js@@ -409,8 +409,19 @@ router.put('/:conversationId/:messageId', validateMessageReq, async (req, res) =return res.status(400).json({ error: 'Cannot update non-text content' });}- const oldText = updatedContent[index][currentPartType];- updatedContent[index] = { type: currentPartType, [currentPartType]: text };+ /** A text part is `string | { value, annotations }`. The Assistants thread sync+ * persists the structured form with its file citations intact, and the editor+ * reads it through the same union, so an edit has to be written into `value`+ * rather than over the whole part. The same object is what gets counted below,+ * and the tokenizer measures `length`, which an object does not have. */+ const currentPart = updatedContent[index];+ const currentValue = currentPart[currentPartType];+ const isStructuredValue = currentValue != null && typeof currentValue === 'object';+ const oldText = isStructuredValue ? (currentValue.value ?? '') : currentValue;+ updatedContent[index] = {+ ...currentPart,+ [currentPartType]: isStructuredValue ? { ...currentValue, value: text } : text,+ };let tokenCount = message.tokenCount;if (tokenCount !== undefined) {diff --git a/client/src/common/types.ts b/client/src/common/types.tsindex 07d7544de9..5fae782858 100644--- a/client/src/common/types.ts+++ b/client/src/common/types.ts@@ -352,7 +352,7 @@ export type TOptions = {isContinued?: boolean;isEdited?: boolean;overrideMessages?: t.TMessage[];- /** This value is only true when the user submits a message with "Save & Submit" for a user-created message */+ /** This value is only true when the user submits a message with "Update & rerun" for a user-created message */isResubmission?: boolean;/** Currently only utilized when `isResubmission === true`, uses that message's currently attached files */overrideFiles?: t.TMessage['files'];diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsxindex 870e6d6cd2..7656949a65 100644--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx@@ -11,10 +11,11 @@ import type { ToolCallGroupExpansionState } from './ToolCallGroup';import { mapAttachments, filterAttachmentsForPart, groupSequentialToolCalls } from '~/utils';import { groupActivityPhases, lastVisibleContentIdx } from '~/utils/activityLabels';import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent';-import { EditTextPart, EmptyText, AgentUpdate } from './Parts';import { MessageContext, SearchContext } from '~/Providers';import PendingSkillCall from './Parts/PendingSkillCall';import ActivityPhaseGroup from './ActivityPhaseGroup';+import EditContentParts from './EditContentParts';+import { EmptyText, AgentUpdate } from './Parts';import ApprovalProvider from './ApprovalContext';import MemoryArtifacts from './MemoryArtifacts';import Sources from '~/components/Web/Sources';@@ -430,45 +431,24 @@ const ContentParts = memo(function ContentParts({return null;}- // Edit mode: render editable text parts. Interim skill cards are a- // mid-stream concern, not relevant in edit mode.+ // Interim skill cards are a mid-stream concern, not relevant in edit mode.if (edit === true && enterEdit && setSiblingIdx) {return (- <>- {(content ?? []).map((part, localIdx) => {- if (!part) {- return null;- }- const idx = absoluteIndexAt(localIdx);- const isTextPart =- part?.type === ContentTypes.TEXT ||- typeof (part as unknown as Agents.MessageContentText)?.text === 'string';- const isThinkPart =- part?.type === ContentTypes.THINK ||- typeof (part as unknown as Agents.ReasoningDeltaUpdate)?.think === 'string';- if (!isTextPart && !isThinkPart) {- return null;- }-- const isToolCall = part.type === ContentTypes.TOOL_CALL || part['tool_call_ids'] != null;- if (isToolCall) {- return null;- }-- return (- <EditTextPart- index={idx}- part={part as Agents.MessageContentText | Agents.ReasoningDeltaUpdate}- messageId={messageId}- isSubmitting={isSubmitting}- enterEdit={enterEdit}- siblingIdx={siblingIdx ?? null}- setSiblingIdx={setSiblingIdx}- key={`edit-${messageId}-${idx}`}- />- );- })}- </>+ <ApprovalProvider>+ <SearchContext.Provider value={{ searchResults }}>+ <MemoryArtifacts attachments={attachments} />+ <EditContentParts+ content={content ?? []}+ contentIndexOffset={contentIndexOffset}+ messageId={messageId}+ isSubmitting={isSubmitting}+ enterEdit={enterEdit}+ siblingIdx={siblingIdx ?? null}+ setSiblingIdx={setSiblingIdx}+ renderReadOnlyPart={(part, idx, isLastPart) => renderPart(part, idx, isLastPart)}+ />+ </SearchContext.Provider>+ </ApprovalProvider>);}diff --git a/client/src/components/Chat/Messages/Content/EditContentParts.tsx b/client/src/components/Chat/Messages/Content/EditContentParts.tsxnew file mode 100644index 0000000000..fd2129aae6--- /dev/null+++ b/client/src/components/Chat/Messages/Content/EditContentParts.tsx@@ -0,0 +1,444 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useRecoilValue } from 'recoil';+import { ContentTypes } from 'librechat-data-provider';+import { Alert, Button, TextareaAutosize } from '@librechat/client';+import { useUpdateMessageContentMutation } from 'librechat-data-provider/react-query';+import type { TMessageContentParts, TextData } from 'librechat-data-provider';+import type { ReactNode } from 'react';+import { useMessagesConversation, useMessagesOperations } from '~/Providers';+import { splitMarkdownIntoBlocks } from './splitMarkdown';+import { useGetAddedConvo } from '~/hooks/Chat';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';+import store from '~/store';++type EditableType = ContentTypes.TEXT | ContentTypes.THINK;++type EditablePart = {+ index: number;+ localIndex: number;+ type: EditableType;+ original: string;+};++type EditContentPartsProps = {+ content: Array<TMessageContentParts | undefined>;+ contentIndexOffset?: number;+ messageId: string;+ isSubmitting: boolean;+ enterEdit: (cancel?: boolean) => void | null | undefined;+ siblingIdx: number | null;+ setSiblingIdx: (value: number) => void;+ 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,+ messageId,+ isSubmitting,+ enterEdit,+ siblingIdx,+ setSiblingIdx,+ renderReadOnlyPart,+}: EditContentPartsProps) {+ const localize = useLocalize();+ const isRTL = useRecoilValue(store.chatDirection).toLowerCase() === 'rtl';+ const { conversation } = useMessagesConversation();+ const { ask, getMessages, setMessages } = useMessagesOperations();+ const getAddedConvo = useGetAddedConvo();+ const firstEditorRef = useRef<HTMLTextAreaElement | null>(null);+ const [saveError, setSaveError] = useState(false);+ const [isSaving, setIsSaving] = useState(false);+ const updateMessageContentMutation = useUpdateMessageContentMutation(+ conversation?.conversationId ?? '',+ );++ 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) {+ return;+ }+ const original = getPartText(part);+ if (original == null || containsArtifact(original)) {+ return;+ }+ result.push({+ index: localIndex + contentIndexOffset,+ localIndex,+ type: part.type,+ original,+ });+ });+ return result;+ }, [content, contentIndexOffset]);++ const [drafts, setDrafts] = useState<Record<number, string>>(() =>+ Object.fromEntries(editableParts.map((part) => [part.index, part.original])),+ );++ const editableByLocalIndex = useMemo(+ () => new Map(editableParts.map((part) => [part.localIndex, part])),+ [editableParts],+ );+ const changedParts = useMemo(+ () => editableParts.filter((part) => drafts[part.index] !== part.original),+ [drafts, editableParts],+ );+ /** Emptying a part would persist a blank one, and nothing in the editor offers a+ * way back: there is no delete-part affordance, so the only reading of a cleared+ * box is an accident. The sibling `EditMessage` refuses the same edit through its+ * form's `required` rule, so both editors hold the same line. */+ const hasBlankEdit = useMemo(+ () => 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 isBusy = isSubmitting || isSaving;++ useEffect(() => {+ const editor = firstEditorRef.current;+ if (!editor) {+ return;+ }+ editor.focus();+ editor.setSelectionRange(editor.value.length, editor.value.length);+ }, []);++ const applySavedParts = useCallback(+ (savedParts: EditablePart[]) => {+ const messages = getMessages();+ if (!messages || savedParts.length === 0) {+ return;+ }+ const changedByLocalIndex = new Map(+ savedParts.map((part) => [part.localIndex, { type: part.type, text: drafts[part.index] }]),+ );+ setMessages(+ messages.map((currentMessage) => {+ if (currentMessage.messageId !== messageId || !Array.isArray(currentMessage.content)) {+ return currentMessage;+ }+ return {+ ...currentMessage,+ content: currentMessage.content.map((part, localIndex) => {+ const change = changedByLocalIndex.get(localIndex);+ if (!part || !change || part.type !== change.type) {+ return part;+ }+ return {+ ...part,+ [change.type]: withPartText(part, change.text),+ } as TMessageContentParts;+ }),+ };+ }),+ );+ },+ [drafts, getMessages, messageId, setMessages],+ );++ const saveChanges = useCallback(async () => {+ if (changedParts.length === 0 || hasBlankEdit || isBusy) {+ return;+ }+ setIsSaving(true);+ setSaveError(false);+ /** The endpoint takes one part per call and nothing rolls a write back, so a+ * refused part leaves the earlier ones on the server. Recording what actually+ * landed lets the failure reconcile the transcript with the server instead of+ * claiming nothing was saved, and leaves only the refused parts still edited. */+ const savedParts: EditablePart[] = [];+ try {+ /** Each endpoint call replaces the full content array. Keep writes ordered so a+ * later edit reads the content produced by the previous one instead of racing it. */+ for (const part of changedParts) {+ await updateMessageContentMutation.mutateAsync({+ index: part.index,+ conversationId: conversation?.conversationId ?? '',+ text: drafts[part.index],+ messageId,+ });+ savedParts.push(part);+ }+ } catch {+ setSaveError(true);+ } finally {+ applySavedParts(savedParts);+ setIsSaving(false);+ }++ if (savedParts.length === changedParts.length) {+ enterEdit(true);+ }+ }, [+ applySavedParts,+ changedParts,+ conversation?.conversationId,+ drafts,+ enterEdit,+ hasBlankEdit,+ isBusy,+ messageId,+ updateMessageContentMutation,+ ]);++ const updateAndRerun = useCallback(() => {+ const firstChange = changedParts[0];+ if (!firstChange || !editedMessage || rerunRequiresSave || hasBlankEdit || isBusy) {+ return;+ }+ const messages = getMessages();++ /** `ask` refuses to send while another response is streaming and reports it by+ * returning false. Closing the editor regardless would throw the drafts away for+ * a rerun that never started, so a refused send leaves the editor as it was. */+ let refused = false;++ if (editedMessage.isCreatedByUser === true) {+ const userText = editableParts+ .filter((part) => part.type === ContentTypes.TEXT)+ .map((part) => drafts[part.index])+ .join('\n');+ refused =+ ask(+ {+ text: userText,+ parentMessageId: editedMessage.parentMessageId,+ conversationId: editedMessage.conversationId,+ },+ {+ overrideFiles: editedMessage.files,+ overrideManualSkills: editedMessage.manualSkills,+ overrideQuotes: editedMessage.quotes,+ addedConvo: getAddedConvo() || undefined,+ },+ ) === false;+ } else {+ const parentMessage = messages?.find(+ (item) => item.messageId === editedMessage.parentMessageId,+ );+ if (!parentMessage) {+ return;+ }+ const editedContent =+ firstChange.type === ContentTypes.THINK+ ? {+ index: firstChange.index,+ type: ContentTypes.THINK as const,+ [ContentTypes.THINK]: drafts[firstChange.index],+ }+ : {+ index: firstChange.index,+ type: ContentTypes.TEXT as const,+ [ContentTypes.TEXT]: drafts[firstChange.index],+ };+ refused =+ ask(+ { ...parentMessage },+ {+ editedContent,+ editedMessageId: messageId,+ isRegenerate: true,+ isEdited: true,+ overrideManualSkills: parentMessage.manualSkills,+ overrideQuotes: parentMessage.quotes,+ addedConvo: getAddedConvo() || undefined,+ },+ ) === false;+ }++ if (refused) {+ return;+ }++ setSiblingIdx((siblingIdx ?? 0) - 1);+ enterEdit(true);+ }, [+ ask,+ changedParts,+ drafts,+ editedMessage,+ editableParts,+ enterEdit,+ getAddedConvo,+ getMessages,+ hasBlankEdit,+ isBusy,+ messageId,+ rerunRequiresSave,+ setSiblingIdx,+ siblingIdx,+ ]);++ const handleKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ enterEdit(true);+ return;+ }+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {+ event.preventDefault();+ updateAndRerun();+ return;+ }+ if (event.key.toLowerCase() === 's' && (event.ctrlKey || event.metaKey)) {+ event.preventDefault();+ void saveChanges();+ }+ },+ [enterEdit, saveChanges, updateAndRerun],+ );++ /** Both states share the footer's status slot so neither can add a row and+ * shift the message below it. */+ const getStatusMessage = () => {+ if (hasBlankEdit) {+ return localize('com_ui_message_part_empty');+ }+ if (rerunRequiresSave) {+ return localize('com_ui_save_before_rerun');+ }+ if (changedParts.length > 0) {+ return localize('com_ui_unsaved_changes');+ }+ return '';+ };++ return (+ <section+ aria-label={localize('com_ui_edit_message')}+ className="flex w-full min-w-0 flex-col gap-2"+ >+ {saveError && <Alert variant="error">{localize('com_ui_save_message_error')}</Alert>}++ <div className="flex min-w-0 flex-col gap-3">+ {content.map((part, localIndex) => {+ if (!part) {+ return null;+ }+ const editablePart = editableByLocalIndex.get(localIndex);+ const absoluteIndex = localIndex + contentIndexOffset;+ if (!editablePart) {+ return (+ <div key={`read-only-${messageId}-${absoluteIndex}`} className="min-w-0">+ {renderReadOnlyPart(part, absoluteIndex, localIndex === content.length - 1)}+ </div>+ );+ }+ const label =+ editablePart.type === ContentTypes.THINK+ ? localize('com_ui_thoughts')+ : localize('com_ui_response');+ return (+ <label+ key={`editor-${messageId}-${absoluteIndex}`}+ dir={isRTL ? 'rtl' : 'ltr'}+ className="flex min-w-0 flex-col gap-1.5 text-xs font-medium text-text-secondary"+ >+ {label}+ <TextareaAutosize+ ref={editablePart === editableParts[0] ? firstEditorRef : undefined}+ value={drafts[absoluteIndex]}+ onChange={(event) =>+ setDrafts((current) => ({+ ...current,+ [absoluteIndex]: event.target.value,+ }))+ }+ onKeyDown={handleKeyDown}+ aria-label={`${localize('com_ui_editable_message')}: ${label}`}+ aria-keyshortcuts="Control+Enter Meta+Enter Control+S Meta+S Escape"+ disabled={isBusy}+ minRows={3}+ dir={isRTL ? 'rtl' : 'ltr'}+ className={cn(+ 'message-editor-text max-h-[65vh] min-h-24 w-full resize-y rounded-lg',+ 'border border-border-medium bg-surface-tertiary-alt px-3 py-2',+ 'font-normal text-text-primary',+ 'focus-visible:outline-none',+ isRTL ? 'text-right' : 'text-left',+ 'disabled:opacity-50 md:max-h-[75vh]',+ )}+ />+ </label>+ );+ })}+ </div>++ {/* The actions wrap rather than hold one unbreakable row: on a 320px assistant+ turn the identity column and page padding leave less width than the three+ English labels need, and a translated label needs more still. */}+ <footer className="flex flex-wrap items-center justify-between gap-2">+ <span+ className="line-clamp-2 min-w-0 flex-1 text-xs text-text-secondary"+ aria-live="polite"+ >+ {getStatusMessage()}+ </span>+ <div className="flex flex-wrap items-center justify-end gap-2">+ <Button size="sm" variant="outline" onClick={() => enterEdit(true)} disabled={isSaving}>+ {localize('com_ui_cancel')}+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() => void saveChanges()}+ disabled={changedParts.length === 0 || hasBlankEdit || isBusy}+ >+ {isSaving ? localize('com_ui_saving') : localize('com_ui_save')}+ </Button>+ <Button+ size="sm"+ variant="submit"+ onClick={updateAndRerun}+ disabled={changedParts.length === 0 || rerunRequiresSave || hasBlankEdit || isBusy}+ >+ {localize('com_ui_update_rerun')}+ </Button>+ </div>+ </footer>+ </section>+ );+}diff --git a/client/src/components/Chat/Messages/Content/EditMessage.tsx b/client/src/components/Chat/Messages/Content/EditMessage.tsxindex 2030c5ffc9..1fbd4d4efc 100644--- a/client/src/components/Chat/Messages/Content/EditMessage.tsx+++ b/client/src/components/Chat/Messages/Content/EditMessage.tsx@@ -1,14 +1,14 @@-import { useRef, useEffect, useCallback } from 'react';+import { useRef, useEffect, useCallback, useState } from 'react';import { useRecoilValue } from 'recoil';import { useForm } from 'react-hook-form';-import { TextareaAutosize, TooltipAnchor } from '@librechat/client';+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 { useGetAddedConvo } from '~/hooks/Chat';-import { cn, removeFocusRings } from '~/utils';import { useLocalize } from '~/hooks';import Container from './Container';+import { cn } from '~/utils';import store from '~/store';const EditMessage = ({@@ -22,6 +22,7 @@ const EditMessage = ({}: TEditProps) => {const saveButtonRef = useRef<HTMLButtonElement | null>(null);const submitButtonRef = useRef<HTMLButtonElement | null>(null);+ const [saveError, setSaveError] = useState(false);const { conversation } = useMessagesConversation();const { getMessages, setMessages } = useMessagesOperations();@@ -36,7 +37,13 @@ const EditMessage = ({const getAddedConvo = useGetAddedConvo();- const { register, handleSubmit, setValue } = useForm({+ const {+ register,+ handleSubmit,+ setValue,+ formState: { isDirty, isValid },+ } = useForm({+ mode: 'onChange',defaultValues: {text: text ?? '',},@@ -51,9 +58,12 @@ const EditMessage = ({}}, []);+ /** `ask` refuses to send while another response is streaming and reports it by+ * returning false. Closing the editor regardless would throw the draft away for+ * a rerun that never started, so a refused send leaves the editor as it was. */const resubmitMessage = (data: { text: string }) => {if (message.isCreatedByUser) {- ask(+ const submitted = ask({text: data.text,parentMessageId,@@ -72,6 +82,10 @@ const EditMessage = ({},);+ if (submitted === false) {+ return;+ }+setSiblingIdx((siblingIdx ?? 0) - 1);} else {const messages = getMessages();@@ -80,7 +94,7 @@ const EditMessage = ({if (!parentMessage) {return;}- ask(+ const submitted = ask({ ...parentMessage },{editedText: data.text,@@ -98,41 +112,58 @@ const EditMessage = ({},);+ if (submitted === false) {+ return;+ }+setSiblingIdx((siblingIdx ?? 0) - 1);}enterEdit(true);};- const updateMessage = (data: { text: string }) => {- const messages = getMessages();- if (!messages) {- return;- }- updateMessageMutation.mutate({- conversationId: conversationId ?? '',- model: conversation?.model ?? 'gpt-3.5-turbo',- text: data.text,- messageId,- });-- const isInMessages = messages.some((message) => message.messageId === messageId);- if (!isInMessages) {- message.text = data.text;- } else {- setMessages(- messages.map((msg) =>- msg.messageId === messageId- ? {- ...msg,- text: data.text,- }- : msg,- ),+ const updateMessage = async (data: { text: string }) => {+ setSaveError(false);+ try {+ await updateMessageMutation.mutateAsync({+ conversationId: conversationId ?? '',+ model: conversation?.model ?? 'gpt-3.5-turbo',+ text: data.text,+ messageId,+ });++ /** Read the thread after the request, not before it. An earlier turn stays+ * editable while the newest answer streams, so a snapshot taken before the+ * round trip is already behind by the time it would be written back, and+ * writing it wholesale would drop every delta that landed in between. */+ const messages = getMessages();+ if (!messages) {+ enterEdit(true);+ return;+ }++ const isInMessages = messages.some(+ (currentMessage) => currentMessage.messageId === messageId,);- }+ if (!isInMessages) {+ message.text = data.text;+ } else {+ setMessages(+ messages.map((msg) =>+ msg.messageId === messageId+ ? {+ ...msg,+ text: data.text,+ }+ : msg,+ ),+ );+ }- enterEdit(true);+ enterEdit(true);+ } catch {+ setSaveError(true);+ }};const handleKeyDown = useCallback(@@ -156,13 +187,17 @@ const EditMessage = ({const { ref, ...registerProps } = register('text', {required: true,onChange: (e) => {- setValue('text', e.target.value, { shouldValidate: true });+ setValue('text', e.target.value, { shouldDirty: true, shouldValidate: true });},});return (<Container message={message}>- <div className="bg-token-main-surface-primary relative mt-2 flex w-full flex-grow flex-col overflow-hidden rounded-2xl border border-border-medium text-text-primary [&:has(textarea:focus)]:border-border-heavy [&:has(textarea:focus)]:shadow-[0_2px_6px_rgba(0,0,0,.05)]">+ <section+ aria-label={localize('com_ui_edit_message')}+ className="mt-2 flex w-full flex-col gap-2"+ >+ {saveError && <Alert variant="error">{localize('com_ui_save_message_error')}</Alert>}<TextareaAutosize{...registerProps}ref={(e) => {@@ -172,53 +207,60 @@ const EditMessage = ({onKeyDown={handleKeyDown}data-testid="message-text-editor"className={cn(- 'markdown prose dark:prose-invert light whitespace-pre-wrap break-words pl-3 md:pl-4',- 'm-0 w-full resize-none border-0 bg-transparent py-[10px]',- 'placeholder-text-secondary focus:ring-0 focus-visible:ring-0 md:py-3.5',+ 'message-editor-text max-h-[65vh] min-h-24 w-full resize-y whitespace-pre-wrap',+ 'break-words rounded-lg border border-border-medium bg-surface-tertiary-alt',+ 'px-3 py-2 text-text-primary',+ 'focus-visible:outline-none',isRTL ? 'text-right' : 'text-left',- 'max-h-[65vh] pr-3 md:max-h-[75vh] md:pr-4',- removeFocusRings,+ '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"+ disabled={isSubmitting || updateMessageMutation.isLoading}dir={isRTL ? 'rtl' : 'ltr'}/>- </div>- <div className="mt-2 flex w-full justify-center text-center">- <TooltipAnchor- description="Ctrl + Enter / ⌘ + Enter"- render={- <button- ref={submitButtonRef}- className="btn btn-primary relative mr-2"- disabled={isSubmitting}- onClick={handleSubmit(resubmitMessage)}+ {/* The actions wrap rather than hold one unbreakable row: on a 320px assistant+ turn the identity column and page padding leave less width than the three+ English labels need, and a translated label needs more still. */}+ <footer className="flex flex-wrap items-center justify-between gap-2">+ <span+ className="line-clamp-2 min-w-0 flex-1 text-xs text-text-secondary"+ aria-live="polite"+ >+ {isDirty ? localize('com_ui_unsaved_changes') : ''}+ </span>+ <div className="flex flex-wrap items-center justify-end gap-2">+ <Button+ size="sm"+ variant="outline"+ onClick={() => enterEdit(true)}+ disabled={updateMessageMutation.isLoading}>- {localize('com_ui_save_submit')}- </button>- }- />- <TooltipAnchor- description="Shift + Enter"- render={- <button+ {localize('com_ui_cancel')}+ </Button>+ <Buttonref={saveButtonRef}- className="btn btn-secondary relative mr-2"- disabled={isSubmitting}+ size="sm"+ variant="outline"+ disabled={isSubmitting || updateMessageMutation.isLoading || !isDirty || !isValid}onClick={handleSubmit(updateMessage)}>- {localize('com_ui_save')}- </button>- }- />- <TooltipAnchor- description="Esc"- render={- <button className="btn btn-neutral relative" onClick={() => enterEdit(true)}>- {localize('com_ui_cancel')}- </button>- }- />- </div>+ {updateMessageMutation.isLoading+ ? localize('com_ui_saving')+ : localize('com_ui_save')}+ </Button>+ <Button+ ref={submitButtonRef}+ size="sm"+ variant="submit"+ disabled={isSubmitting || updateMessageMutation.isLoading || !isDirty || !isValid}+ onClick={handleSubmit(resubmitMessage)}+ >+ {localize('com_ui_update_rerun')}+ </Button>+ </div>+ </footer>+ </section></Container>);};diff --git a/client/src/components/Chat/Messages/Content/Parts/AuthorHeader.tsx b/client/src/components/Chat/Messages/Content/Parts/AuthorHeader.tsxindex 189c9a9268..d0deeb1fcc 100644--- a/client/src/components/Chat/Messages/Content/Parts/AuthorHeader.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/AuthorHeader.tsx@@ -1,8 +1,5 @@import { memo } from 'react';-import { useAtomValue } from 'jotai';import type { ReactNode } from 'react';-import { fontSizeAtom } from '~/store/fontSize';-import { cn } from '~/utils';/*** Re-attributes response content to its author mid-message. A `SteerPart`@@ -18,15 +15,14 @@ const AuthorHeader = memo(function AuthorHeader({icon: ReactNode;label: string;}) {- const fontSize = useAtomValue(fontSizeAtom);return (<div className="relative -ml-9 flex w-[calc(100%+2.25rem)] gap-3" data-testid="author-header">- <div className="relative flex flex-shrink-0 flex-col items-center">+ <div className="relative flex flex-shrink-0 flex-col items-center" aria-hidden="true"><div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">{icon}</div></div>- <h2 className={cn('select-none font-semibold text-text-primary', fontSize)}>{label}</h2>+ <h2 className="select-none text-sm font-semibold text-text-primary">{label}</h2></div>);});diff --git a/client/src/components/Chat/Messages/Content/Parts/EditTextPart.tsx b/client/src/components/Chat/Messages/Content/Parts/EditTextPart.tsxdeleted file mode 100644index 6575ad327b..0000000000--- a/client/src/components/Chat/Messages/Content/Parts/EditTextPart.tsx+++ /dev/null@@ -1,213 +0,0 @@-import { useRef, useEffect, useCallback, useMemo } from 'react';-import { useRecoilValue } from 'recoil';-import { useForm } from 'react-hook-form';-import { TextareaAutosize } from '@librechat/client';-import { ContentTypes } from 'librechat-data-provider';-import { Lightbulb, MessageSquare } from 'lucide-react';-import { useUpdateMessageContentMutation } from 'librechat-data-provider/react-query';-import type { Agents } from 'librechat-data-provider';-import type { TEditProps } from '~/common';-import { useMessagesOperations, useMessagesConversation } from '~/Providers';-import Container from '~/components/Chat/Messages/Content/Container';-import { useGetAddedConvo } from '~/hooks/Chat';-import { cn, removeFocusRings } from '~/utils';-import { useLocalize } from '~/hooks';-import store from '~/store';--const EditTextPart = ({- part,- index,- messageId,- isSubmitting,- enterEdit,-}: Omit<TEditProps, 'message' | 'ask' | 'text'> & {- index: number;- messageId: string;- part: Agents.MessageContentText | Agents.ReasoningDeltaUpdate;-}) => {- const localize = useLocalize();- const { conversation } = useMessagesConversation();- const { ask, getMessages, setMessages } = useMessagesOperations();-- const { conversationId = '' } = conversation ?? {};- const message = useMemo(- () => getMessages()?.find((msg) => msg.messageId === messageId),- [getMessages, messageId],- );-- const chatDirection = useRecoilValue(store.chatDirection);-- const getAddedConvo = useGetAddedConvo();-- const textAreaRef = useRef<HTMLTextAreaElement | null>(null);- const updateMessageContentMutation = useUpdateMessageContentMutation(conversationId ?? '');-- const isRTL = chatDirection?.toLowerCase() === 'rtl';-- const { register, handleSubmit, setValue } = useForm({- defaultValues: {- text: (ContentTypes.THINK in part ? part.think : part.text) || '',- },- });-- useEffect(() => {- const textArea = textAreaRef.current;- if (textArea) {- const length = textArea.value.length;- textArea.focus();- textArea.setSelectionRange(length, length);- }- }, []);-- const resubmitMessage = (data: { text: string }) => {- const messages = getMessages();- const parentMessage = messages?.find((msg) => msg.messageId === message?.parentMessageId);-- const editedContent =- part.type === ContentTypes.THINK- ? {- index,- type: ContentTypes.THINK as const,- [ContentTypes.THINK]: data.text,- }- : {- index,- type: ContentTypes.TEXT as const,- [ContentTypes.TEXT]: data.text,- };-- if (!parentMessage) {- return;- }- ask(- { ...parentMessage },- {- editedContent,- editedMessageId: messageId,- isRegenerate: true,- isEdited: true,- addedConvo: getAddedConvo() || undefined,- },- );-- enterEdit(true);- };-- const updateMessage = (data: { text: string }) => {- const messages = getMessages();- if (!messages) {- return;- }- updateMessageContentMutation.mutate({- index,- conversationId: conversationId ?? '',- text: data.text,- messageId,- });-- const isInMessages = messages.some((msg) => msg.messageId === messageId);- if (!isInMessages) {- return enterEdit(true);- }-- const updatedContent = message?.content?.map((part, idx) => {- if (part.type === ContentTypes.TEXT && idx === index) {- return { ...part, text: data.text };- }- return part;- });-- setMessages(- messages.map((msg) =>- msg.messageId === messageId- ? {- ...msg,- content: updatedContent,- }- : msg,- ),- );-- enterEdit(true);- };-- const handleKeyDown = useCallback(- (e: React.KeyboardEvent<HTMLTextAreaElement>) => {- if (e.key === 'Escape') {- e.preventDefault();- enterEdit(true);- }- },- [enterEdit],- );-- const { ref, ...registerProps } = register('text', {- required: true,- onChange: (e) => {- setValue('text', e.target.value, { shouldValidate: true });- },- });-- return (- <Container message={message}>- {part.type === ContentTypes.THINK && (- <div className="mt-2 flex items-center gap-1.5 text-xs text-text-secondary">- <span className="flex gap-2 rounded-lg bg-surface-tertiary px-1.5 py-1 font-medium">- <Lightbulb className="size-3.5" aria-hidden="true" />- {localize('com_ui_thoughts')}- </span>- </div>- )}- {part.type !== ContentTypes.THINK && (- <div className="mt-2 flex items-center gap-1.5 text-xs text-text-secondary">- <span className="flex gap-2 rounded-lg bg-surface-tertiary px-1.5 py-1 font-medium">- <MessageSquare className="size-3.5" aria-hidden="true" />- {localize('com_ui_response')}- </span>- </div>- )}- <div className="bg-token-main-surface-primary relative flex w-full flex-grow flex-col overflow-hidden rounded-2xl border border-border-medium text-text-primary [&:has(textarea:focus)]:border-border-heavy [&:has(textarea:focus)]:shadow-[0_2px_6px_rgba(0,0,0,.05)]">- <TextareaAutosize- {...registerProps}- ref={(e) => {- ref(e);- textAreaRef.current = e;- }}- onKeyDown={handleKeyDown}- data-testid="message-text-editor"- className={cn(- 'markdown prose dark:prose-invert light whitespace-pre-wrap break-words pl-3 md:pl-4',- 'm-0 w-full resize-none border-0 bg-transparent py-[10px]',- 'placeholder-text-secondary focus:ring-0 focus-visible:ring-0 md:py-3.5',- isRTL ? 'text-right' : 'text-left',- 'max-h-[65vh] pr-3 md:max-h-[75vh] md:pr-4',- removeFocusRings,- )}- aria-label={localize('com_ui_editable_message')}- dir={isRTL ? 'rtl' : 'ltr'}- />- </div>- <div className="mt-2 flex w-full justify-center text-center">- <button- className="btn btn-primary relative mr-2"- disabled={isSubmitting}- onClick={handleSubmit(resubmitMessage)}- >- {localize('com_ui_save_submit')}- </button>- <button- className="btn btn-secondary relative mr-2"- disabled={isSubmitting}- onClick={handleSubmit(updateMessage)}- >- {localize('com_ui_save')}- </button>- <button className="btn btn-neutral relative" onClick={() => enterEdit(true)}>- {localize('com_ui_cancel')}- </button>- </div>- </Container>- );-};--export default EditTextPart;diff --git a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsxindex 4361481d54..00c50f8e0a 100644--- a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx@@ -1,26 +1,20 @@import { memo, useMemo, useState, useCallback } from 'react';-import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';-import { InfoHoverCard, ESide, UserIcon } from '@librechat/client';+import { InfoHoverCard, ESide } from '@librechat/client';import type { TFile, TMessage } from 'librechat-data-provider';-import type { TMessageIcon } from '~/common';import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDialog';import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';import FileContainer from '~/components/Chat/Input/Files/FileContainer';-import MessageIcon from '~/components/Chat/Messages/MessageIcon';import Image from '~/components/Chat/Messages/Content/Image';-import { fontSizeAtom } from '~/store/fontSize';import { useShareContext } from '~/Providers';import { useLocalize } from '~/hooks';import { cn } from '~/utils';import store from '~/store';-const USER_ICON: TMessageIcon = { isCreatedByUser: true };-/*** A mid-run steering message rendered as a standard user message inside the- * assistant response — same icon, author header, and text presentation as any+ * assistant response, with the same compact surface and text presentation as any* user turn, placed where the words enter the run so the visible order equals* what the next turn replays (`ContentTypes.STEER` splits back into a* HumanMessage server-side). Only the server-applied part renders here, at its@@ -43,7 +37,6 @@ const SteerPart = memo(function SteerPart({/** Read the atom rather than the auth context: AuthContextProvider mirrors the* user into it, and the public share route mounts outside that provider. */const user = useRecoilValue(store.user);- const fontSize = useAtomValue(fontSizeAtom);const { isSharedConvo } = useShareContext();const usernameDisplay = useRecoilValue<boolean>(store.UsernameDisplay);const enableUserMsgMarkdown = useRecoilValue<boolean>(store.enableUserMsgMarkdown);@@ -82,51 +75,12 @@ const SteerPart = memo(function SteerPart({return (<divid={steerId ? `steer-${steerId}` : undefined}- className={cn(- /* Outdented past the response's icon column so the steer sits flush- * with top-level message rows — it reads as a regular user message. */- 'steer-render group relative my-4 -ml-9 flex w-[calc(100%+2.25rem)] gap-3',- )}+ className="steer-render group relative my-5 -ml-9 flex w-[calc(100%+2.25rem)] justify-end"data-testid="steer-part">- <div className="relative flex flex-shrink-0 flex-col items-center">- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">- {isSharedConvo === true ? (- /** The atom still holds the viewer's identity when a signed-in user opens- * a share link, so rendering the identity-bearing avatar here would put- * the viewer's face on the sharer's steer. Mirrors Share/MessageIcon. */- <div- style={{- backgroundColor: 'rgb(121, 137, 255)',- width: '20px',- height: '20px',- boxShadow: 'rgba(240, 246, 252, 0.1) 0px 0px 0px 1px',- }}- className="relative flex h-9 w-9 items-center justify-center rounded-sm p-1 text-white"- >- <UserIcon />- </div>- ) : (- <MessageIcon iconData={USER_ICON} />- )}- </div>- </div>- <div className="user-turn relative flex w-11/12 flex-col">- <h2 className={cn('flex select-none items-center gap-1.5 font-semibold', fontSize)}>- {label}- {/* Subtle "?" explaining why a user message appears inside the- * response. Like the message hover buttons, it's revealed on- * hover/focus on hover-capable pointers, but stays visible on- * touch (no hover to reveal it) via [@media(hover:hover)]:opacity-0. */}- <span- data-testid="steer-info-affordance"- className="transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100 [@media(hover:hover)]:opacity-0"- >- <InfoHoverCard side={ESide.Top} text={localize('com_ui_steered_info')} />- </span>- <MessageTimestamp value={timestamp} />- </h2>- <div className="flex flex-col items-start gap-2">+ <div className="user-turn relative flex w-fit max-w-[90%] flex-col items-end sm:max-w-[85%]">+ <h2 className="sr-only">{label}</h2>+ <div className="flex max-w-full flex-col items-start gap-2 rounded-theme-surface rounded-br-theme-control bg-surface-tertiary px-theme-normal py-2.5">{(imageFiles.length > 0 || otherFiles.length > 0) && (<div className="flex flex-wrap gap-2">{otherFiles.map((file) => (@@ -151,12 +105,21 @@ const SteerPart = memo(function SteerPart({className={cn('markdown prose message-content dark:prose-invert light w-full break-words',!enableUserMsgMarkdown && 'whitespace-pre-wrap',- 'dark:text-gray-20',+ 'text-text-primary',)}>{enableUserMsgMarkdown ? <MarkdownLite content={steer} /> : steer}</div></div>+ <div className="mt-1 flex min-h-8 items-center justify-end text-text-secondary">+ <span+ data-testid="steer-info-affordance"+ className="transition-opacity duration-theme-normal focus-within:opacity-100 group-hover:opacity-100 motion-reduce:transition-none [@media(hover:hover)]:opacity-0"+ >+ <InfoHoverCard side={ESide.Top} text={localize('com_ui_steered_info')} />+ </span>+ <MessageTimestamp value={timestamp} />+ </div></div>{otherFiles.length > 0 && (<FilePreviewDialogdiff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsxindex 8f586c18e0..94d16b098e 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx@@ -1,7 +1,6 @@import React from 'react';import { RecoilRoot } from 'recoil';import { render, screen, fireEvent } from '@testing-library/react';-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { TMessage } from 'librechat-data-provider';import SteerPart from '../SteerPart';import store from '~/store';@@ -46,9 +45,8 @@ jest.mock('~/components/Chat/Messages/Content/Image', () => ({default: ({ altText }: { altText: string }) => <img alt={altText} data-testid="steer-image" />,}));-/** Seeds the user atom rather than mocking `useAuthContext`, and renders the real- * MessageIcon tree — mocking either one hid a crash on the share route, where- * neither an auth context nor a user exists. */+/** Seeds the user atom rather than mocking `useAuthContext`, matching the share+ * route where neither an auth context nor a user exists. */const SEEDED_USER = { name: 'Danny', username: 'danny' };function renderPart(@@ -58,11 +56,9 @@ function renderPart(user: { name: string; username: string } | null = SEEDED_USER,) {return render(- <QueryClientProvider client={new QueryClient()}>- <RecoilRoot initializeState={({ set }) => user && set(store.user, user as never)}>- <SteerPart steer="steered words" steerId="s1" createdAt={1} files={files} />- </RecoilRoot>- </QueryClientProvider>,+ <RecoilRoot initializeState={({ set }) => user && set(store.user, user as never)}>+ <SteerPart steer="steered words" steerId="s1" createdAt={1} files={files} />+ </RecoilRoot>,);}@@ -89,10 +85,10 @@ describe('SteerPart author label', () => {expect(screen.getByText('com_user_message')).toBeInTheDocument();});- it('never renders the viewer identity on a shared steer avatar', () => {+ it('never renders the viewer identity on a shared steer bubble', () => {/** The user atom is app-wide and survives navigation, so a signed-in viewer* opening a share link still has an identity in state. The shared steer must- * show the generic avatar regardless. */+ * keep generic attribution regardless. */mockShareContext = { isSharedConvo: true, shareId: 'share-1' };renderPart(undefined, SEEDED_USER);@@ -130,12 +126,13 @@ describe('SteerPart presentation', () => {mockShareContext = {};});- it('presents the steer as a user message with an icon', () => {+ it('presents the steer as a compact user bubble with accessible attribution', () => {renderPart();- /** Asserts the real avatar rather than a stubbed one — the previous mock was- * what hid the auth-context crash inside this icon tree. */- expect(screen.getByTitle('Danny')).toBeInTheDocument();- expect(screen.getByText('steered words')).toBeInTheDocument();+ const message = screen.getByText('steered words');++ expect(message.closest('.bg-surface-tertiary')).toHaveClass('rounded-theme-surface');+ expect(screen.getByRole('heading', { name: 'Danny' })).toHaveClass('sr-only');+ expect(screen.queryByTitle('Danny')).not.toBeInTheDocument();});it('anchors the steer for the message-nav rail', () => {diff --git a/client/src/components/Chat/Messages/Content/Parts/index.ts b/client/src/components/Chat/Messages/Content/Parts/index.tsindex 68da02ac1b..527654a442 100644--- a/client/src/components/Chat/Messages/Content/Parts/index.ts+++ b/client/src/components/Chat/Messages/Content/Parts/index.ts@@ -8,7 +8,6 @@ export { default as LogContent } from './LogContent';export { default as ExecuteCode } from './ExecuteCode';export { default as Summary } from './Summary';export { default as AgentUpdate } from './AgentUpdate';-export { default as EditTextPart } from './EditTextPart';export { default as SkillCall } from './SkillCall';export { default as ReadFileCall } from './ReadFileCall';export { default as FileAuthoringCall } from './FileAuthoringCall';diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsxindex fa47cd8f78..9d9d1a5830 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx@@ -78,7 +78,6 @@ jest.mock('../Parts', () => ({Reasoning: () => <div data-testid="reasoning" />,Summary: () => <div data-testid="summary" />,Text: ({ text }: { text?: string }) => <div data-testid="text">{text}</div>,- EditTextPart: () => <div data-testid="edit-text" />,}));jest.mock('../MemoryArtifacts', () => ({diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsxindex e0a5951a71..df52bb72d7 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx@@ -30,7 +30,6 @@ jest.mock('~/Providers', () => {});jest.mock('../Parts', () => ({- EditTextPart: () => <div data-testid="edit-text-part" />,EmptyText: () => <div data-testid="empty-text" />,AgentUpdate: ({ currentAgentId }: { currentAgentId: string }) => (<div data-testid="post-steer-agent-update" data-agent-id={currentAgentId} />diff --git a/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsxnew file mode 100644index 0000000000..b72f353174--- /dev/null+++ b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx@@ -0,0 +1,439 @@+import React from 'react';+import { 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';++const mockMutateAsync = jest.fn();+const mockSetMessages = jest.fn();+const mockAsk = jest.fn();+let mockChatDirection = 'LTR';++jest.mock('recoil', () => ({+ useRecoilValue: () => mockChatDirection,+}));++jest.mock('~/store', () => ({+ __esModule: true,+ default: { chatDirection: {} },+}));++const message = {+ messageId: 'assistant-1',+ parentMessageId: 'user-1',+ conversationId: 'conversation-1',+ isCreatedByUser: false,+} as TMessage;++const parentMessage = {+ messageId: 'user-1',+ conversationId: 'conversation-1',+ isCreatedByUser: true,+ text: 'Check the service',+} as TMessage;++jest.mock('librechat-data-provider/react-query', () => ({+ useUpdateMessageContentMutation: () => ({+ mutateAsync: mockMutateAsync,+ isLoading: false,+ }),+}));++jest.mock('~/Providers', () => ({+ useMessagesConversation: () => ({+ conversation: { conversationId: 'conversation-1' },+ }),+ useMessagesOperations: () => ({+ ask: mockAsk,+ getMessages: () => [parentMessage, message],+ setMessages: mockSetMessages,+ }),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++jest.mock('~/hooks/Chat', () => ({+ useGetAddedConvo: () => () => null,+}));++const content = [+ { type: ContentTypes.TEXT, text: 'Current response' },+ {+ type: ContentTypes.TOOL_CALL,+ tool_call: { type: 'tool_call', name: 'status', args: '{}', output: 'ok' },+ },+ { type: ContentTypes.ERROR, error: 'A visible tool error' },+] as TMessageContentParts[];++describe('EditContentParts', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockMutateAsync.mockReset();+ mockMutateAsync.mockResolvedValue({});+ mockChatDirection = 'LTR';+ message.content = undefined;+ });++ it('uses one editor footer and keeps non-editable parts visible', () => {+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={jest.fn()}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={(part) => <div data-testid={`read-only-${part.type}`}>{part.type}</div>}+ />,+ );++ expect(screen.getAllByRole('textbox')).toHaveLength(1);+ expect(screen.getByTestId(`read-only-${ContentTypes.TOOL_CALL}`)).toBeInTheDocument();+ expect(screen.getByTestId(`read-only-${ContentTypes.ERROR}`)).toBeInTheDocument();+ expect(screen.getAllByRole('button')).toHaveLength(3);+ });++ it('saves changed text parts before closing the editor', async () => {+ const enterEdit = jest.fn();+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={enterEdit}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={() => null}+ />,+ );++ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Updated response' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));++ await waitFor(() =>+ expect(mockMutateAsync).toHaveBeenCalledWith({+ index: 0,+ conversationId: 'conversation-1',+ text: 'Updated response',+ messageId: message.messageId,+ }),+ );+ expect(mockSetMessages).toHaveBeenCalledTimes(1);+ expect(enterEdit).toHaveBeenCalledWith(true);+ });++ it('reruns an assistant response with the edited content value', () => {+ const enterEdit = jest.fn();+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={enterEdit}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={() => null}+ />,+ );++ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Rerun response' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_update_rerun' }));++ expect(mockAsk).toHaveBeenCalledWith(+ parentMessage,+ expect.objectContaining({+ editedContent: {+ index: 0,+ type: ContentTypes.TEXT,+ [ContentTypes.TEXT]: 'Rerun response',+ },+ }),+ );+ expect(enterEdit).toHaveBeenCalledWith(true);+ });++ it('keeps the editor open with the drafts when a rerun is refused mid-stream', () => {+ const enterEdit = jest.fn();+ const setSiblingIdx = jest.fn();+ mockAsk.mockReturnValue(false);+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={enterEdit}+ siblingIdx={0}+ setSiblingIdx={setSiblingIdx}+ renderReadOnlyPart={() => null}+ />,+ );++ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Refused rerun' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_update_rerun' }));++ expect(mockAsk).toHaveBeenCalled();+ expect(screen.getByRole('textbox')).toHaveValue('Refused rerun');+ expect(setSiblingIdx).not.toHaveBeenCalled();+ expect(enterEdit).not.toHaveBeenCalled();+ });++ it('requires multi-part assistant edits to be saved before rerunning', () => {+ const multiPartContent = [+ { type: ContentTypes.TEXT, text: 'First response' },+ { type: ContentTypes.TEXT, text: 'Second response' },+ ] as TMessageContentParts[];++ render(+ <EditContentParts+ content={multiPartContent}+ messageId={message.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.getByRole('button', { name: 'com_ui_update_rerun' })).toBeDisabled();+ expect(screen.getByText('com_ui_save_before_rerun')).toBeInTheDocument();+ });++ it('reconciles the parts that were persisted when a later part is refused', async () => {+ const enterEdit = jest.fn();+ const multiPartContent = [+ { type: ContentTypes.TEXT, text: 'First response' },+ { type: ContentTypes.TEXT, text: 'Second response' },+ ] as TMessageContentParts[];+ message.content = multiPartContent;+ mockMutateAsync+ .mockResolvedValueOnce({})+ .mockRejectedValueOnce(new Error('the second write was refused'));++ render(+ <EditContentParts+ content={multiPartContent}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={enterEdit}+ 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' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));++ expect(await screen.findByText('com_ui_save_message_error')).toBeInTheDocument();+ expect(mockMutateAsync).toHaveBeenCalledTimes(2);++ /** The first write is on the server whatever the second one did, so the transcript+ * has to show it rather than report that the whole save was lost. */+ expect(mockSetMessages).toHaveBeenCalledTimes(1);+ const reconciled = mockSetMessages.mock.calls[0][0] as TMessage[];+ const edited = reconciled.find((item) => item.messageId === message.messageId);+ expect(edited?.content).toEqual([+ { type: ContentTypes.TEXT, text: 'Updated first response' },+ { type: ContentTypes.TEXT, text: 'Second response' },+ ]);++ /** The refused part is the only one still holding an unsaved draft, so the editor+ * stays open on it and a retry does not rewrite what already landed. */+ expect(enterEdit).not.toHaveBeenCalled();+ expect(screen.getAllByRole('textbox')[1]).toHaveValue('Updated second response');+ });++ /**+ * The Assistants thread sync stores a response carrying file citations as+ * `{ value, annotations }`, and the editor reads that through the same union it+ * reads a bare string with. Writing the draft over the whole value dropped the+ * citations from the transcript, and they stayed dropped until a refetch.+ */+ it('edits inside a structured text part rather than flattening the cached one', async () => {+ const annotations: FileCitation[] = [+ {+ type: 'file_citation',+ text: 'source',+ start_index: 0,+ end_index: 6,+ file_citation: { file_id: 'file-1', quote: 'the cited passage' },+ },+ ];+ const structuredContent = [+ { type: ContentTypes.TEXT, text: { value: 'Cited response', annotations } },+ ] as TMessageContentParts[];+ message.content = structuredContent;++ render(+ <EditContentParts+ content={structuredContent}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={jest.fn()}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={() => null}+ />,+ );++ /** Read back through the union, so the editor opens on the text and not on the wrapper. */+ const editor = screen.getByRole('textbox');+ expect(editor).toHaveValue('Cited response');++ fireEvent.change(editor, { target: { value: 'Edited cited response' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));++ await waitFor(() => expect(mockSetMessages).toHaveBeenCalledTimes(1));+ const reconciled = mockSetMessages.mock.calls[0][0] as TMessage[];+ const edited = reconciled.find((item) => item.messageId === message.messageId);+ expect(edited?.content).toEqual([+ { type: ContentTypes.TEXT, text: { value: 'Edited cited response', annotations } },+ ]);+ });++ it('keeps artifact-bearing text in the specialized read-only renderer', () => {+ const artifactContent = [+ {+ type: ContentTypes.TEXT,+ text: ':::artifact{identifier="demo" type="text/html" title="Demo"}\n<div />\n:::',+ },+ ] as TMessageContentParts[];++ render(+ <EditContentParts+ content={artifactContent}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={jest.fn()}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={(part) => <div data-testid="artifact-part">{part.type}</div>}+ />,+ );++ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.getByTestId('artifact-part')).toBeInTheDocument();+ });++ it('refuses to persist a part the editor has been emptied of', async () => {+ const enterEdit = jest.fn();+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={enterEdit}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={() => null}+ />,+ );++ const editor = screen.getByRole('textbox');+ fireEvent.change(editor, { target: { value: ' ' } });++ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'com_ui_update_rerun' })).toBeDisabled();+ expect(screen.getByText('com_ui_message_part_empty')).toBeInTheDocument();++ /** The shortcuts reach the save paths directly, so a disabled button is not+ * enough on its own. */+ fireEvent.keyDown(editor, { key: 's', ctrlKey: true });+ fireEvent.keyDown(editor, { key: 'Enter', ctrlKey: true });++ await waitFor(() => expect(mockMutateAsync).not.toHaveBeenCalled());+ expect(mockAsk).not.toHaveBeenCalled();+ expect(enterEdit).not.toHaveBeenCalled();+ });++ it('lets a restored part save again after being emptied', async () => {+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={jest.fn()}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={() => null}+ />,+ );++ const editor = screen.getByRole('textbox');+ fireEvent.change(editor, { target: { value: '' } });+ fireEvent.change(editor, { target: { value: 'Restored response' } });++ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeEnabled();+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));++ await waitFor(() =>+ expect(mockMutateAsync).toHaveBeenCalledWith(+ expect.objectContaining({ text: 'Restored response' }),+ ),+ );+ });++ it('turns the editor around for a right-to-left chat direction', () => {+ mockChatDirection = 'RTL';+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={jest.fn()}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={() => null}+ />,+ );++ const editor = screen.getByRole('textbox');+ expect(editor).toHaveAttribute('dir', 'rtl');+ expect(editor).toHaveClass('text-right');+ });++ it('leaves the editor left-to-right by default', () => {+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={jest.fn()}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={() => null}+ />,+ );++ const editor = screen.getByRole('textbox');+ expect(editor).toHaveAttribute('dir', 'ltr');+ expect(editor).toHaveClass('text-left');+ });++ it('sizes the editor from the configured message font rather than pinning it', () => {+ render(+ <EditContentParts+ content={content}+ messageId={message.messageId}+ isSubmitting={false}+ enterEdit={jest.fn()}+ siblingIdx={0}+ setSiblingIdx={jest.fn()}+ renderReadOnlyPart={() => null}+ />,+ );++ const editor = screen.getByRole('textbox');+ expect(editor).toHaveClass('message-editor-text');+ expect(editor).not.toHaveClass('text-sm');+ });+});diff --git a/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsx b/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsxnew file mode 100644index 0000000000..f0db525695--- /dev/null+++ b/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsx@@ -0,0 +1,222 @@+import React from 'react';+import userEvent from '@testing-library/user-event';+import { render, screen, waitFor } from '@testing-library/react';+import type { TMessage } from 'librechat-data-provider';+import EditMessage from '../EditMessage';++const mockMutateAsync = jest.fn();+const mockSetMessages = jest.fn();+const mockGetMessages = jest.fn();++jest.mock('recoil', () => ({+ useRecoilValue: () => 'ltr',+}));++jest.mock('~/store', () => ({+ __esModule: true,+ default: { chatDirection: {} },+}));++jest.mock('librechat-data-provider/react-query', () => ({+ useUpdateMessageMutation: () => ({+ mutateAsync: mockMutateAsync,+ isLoading: false,+ }),+}));++jest.mock('~/Providers', () => ({+ useMessagesConversation: () => ({+ conversation: { conversationId: 'conversation-1', model: 'test-model' },+ }),+ useMessagesOperations: () => ({+ getMessages: mockGetMessages,+ setMessages: mockSetMessages,+ }),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++jest.mock('~/hooks/Chat', () => ({+ useGetAddedConvo: () => () => null,+}));++jest.mock('../Container', () => ({+ __esModule: true,+ default: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++const message = {+ messageId: 'user-1',+ parentMessageId: 'root',+ conversationId: 'conversation-1',+ isCreatedByUser: true,+ text: 'Original message',+} as TMessage;++const assistantMessage = {+ messageId: 'assistant-1',+ parentMessageId: 'user-1',+ conversationId: 'conversation-1',+ isCreatedByUser: false,+ text: 'Original answer',+} as TMessage;++function renderEditor({+ enterEdit = jest.fn(),+ ask = jest.fn(),+ setSiblingIdx = jest.fn(),+ editedMessage = message,+} = {}) {+ render(+ <EditMessage+ text={editedMessage.text}+ message={editedMessage}+ isSubmitting={false}+ ask={ask}+ enterEdit={enterEdit}+ siblingIdx={0}+ setSiblingIdx={setSiblingIdx}+ />,+ );+ return { ask, enterEdit, setSiblingIdx };+}++describe('EditMessage', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockGetMessages.mockReturnValue([message]);+ mockMutateAsync.mockResolvedValue({});+ });++ it('sizes the editor from the configured message font rather than pinning it', () => {+ renderEditor();++ const editor = screen.getByTestId('message-text-editor');+ expect(editor).toHaveClass('message-editor-text');+ expect(editor).not.toHaveClass('text-sm');+ });++ it('waits for a successful save before updating local state and closing', async () => {+ const user = userEvent.setup();+ const { enterEdit } = renderEditor();++ await user.clear(screen.getByTestId('message-text-editor'));+ await user.type(screen.getByTestId('message-text-editor'), 'Updated message');+ await user.click(screen.getByRole('button', { name: 'com_ui_save' }));++ await waitFor(() =>+ expect(mockMutateAsync).toHaveBeenCalledWith({+ conversationId: message.conversationId,+ model: 'test-model',+ text: 'Updated message',+ messageId: message.messageId,+ }),+ );+ expect(mockSetMessages).toHaveBeenCalledWith([+ expect.objectContaining({ messageId: message.messageId, text: 'Updated message' }),+ ]);+ expect(enterEdit).toHaveBeenCalledWith(true);+ });++ it('writes the save onto the thread as it stands when the request resolves', async () => {+ const user = userEvent.setup();+ const streamedAnswer = {+ messageId: 'assistant-streaming',+ parentMessageId: message.messageId,+ conversationId: 'conversation-1',+ isCreatedByUser: false,+ text: 'Half an answer',+ } as TMessage;++ /** The answer keeps streaming into the cache while the request is in flight. */+ mockMutateAsync.mockImplementation(async () => {+ mockGetMessages.mockReturnValue([message, streamedAnswer]);+ return {};+ });++ renderEditor();++ await user.clear(screen.getByTestId('message-text-editor'));+ await user.type(screen.getByTestId('message-text-editor'), 'Updated message');+ await user.click(screen.getByRole('button', { name: 'com_ui_save' }));++ await waitFor(() => expect(mockSetMessages).toHaveBeenCalled());+ expect(mockSetMessages).toHaveBeenCalledWith([+ expect.objectContaining({ messageId: message.messageId, text: 'Updated message' }),+ expect.objectContaining({ messageId: streamedAnswer.messageId, text: 'Half an answer' }),+ ]);+ });++ it('keeps the editor open with the draft when saving fails', async () => {+ const user = userEvent.setup();+ mockMutateAsync.mockRejectedValue(new Error('Save failed'));+ const { enterEdit } = renderEditor();++ await user.clear(screen.getByTestId('message-text-editor'));+ await user.type(screen.getByTestId('message-text-editor'), 'Unsaved message');+ await user.click(screen.getByRole('button', { name: 'com_ui_save' }));++ expect(await screen.findByText('com_ui_save_message_error')).toBeInTheDocument();+ expect(screen.getByTestId('message-text-editor')).toHaveValue('Unsaved message');+ expect(enterEdit).not.toHaveBeenCalled();+ });++ it('submits the edited user message with its original context', async () => {+ const user = userEvent.setup();+ const ask = jest.fn();+ const { enterEdit } = renderEditor({ ask });++ await user.clear(screen.getByTestId('message-text-editor'));+ await user.type(screen.getByTestId('message-text-editor'), 'Updated and rerun');+ await user.click(screen.getByRole('button', { name: 'com_ui_update_rerun' }));++ await waitFor(() =>+ expect(ask).toHaveBeenCalledWith(+ expect.objectContaining({+ text: 'Updated and rerun',+ parentMessageId: message.parentMessageId,+ conversationId: message.conversationId,+ }),+ expect.objectContaining({+ overrideFiles: message.files,+ overrideManualSkills: message.manualSkills,+ overrideQuotes: message.quotes,+ }),+ ),+ );+ expect(enterEdit).toHaveBeenCalledWith(true);+ });++ it('keeps the editor open with the draft when a rerun is refused mid-stream', async () => {+ const user = userEvent.setup();+ const ask = jest.fn().mockReturnValue(false);+ const { enterEdit, setSiblingIdx } = renderEditor({ ask });++ await user.clear(screen.getByTestId('message-text-editor'));+ await user.type(screen.getByTestId('message-text-editor'), 'Refused rerun');+ await user.click(screen.getByRole('button', { name: 'com_ui_update_rerun' }));++ await waitFor(() => expect(ask).toHaveBeenCalled());+ expect(screen.getByTestId('message-text-editor')).toHaveValue('Refused rerun');+ expect(setSiblingIdx).not.toHaveBeenCalled();+ expect(enterEdit).not.toHaveBeenCalled();+ });++ it('keeps an assistant edit open when a refused rerun would discard it', async () => {+ const user = userEvent.setup();+ mockGetMessages.mockReturnValue([message, assistantMessage]);+ const ask = jest.fn().mockReturnValue(false);+ const { enterEdit, setSiblingIdx } = renderEditor({ ask, editedMessage: assistantMessage });++ await user.clear(screen.getByTestId('message-text-editor'));+ await user.type(screen.getByTestId('message-text-editor'), 'Refused answer edit');+ await user.click(screen.getByRole('button', { name: 'com_ui_update_rerun' }));++ await waitFor(() => expect(ask).toHaveBeenCalled());+ expect(screen.getByTestId('message-text-editor')).toHaveValue('Refused answer edit');+ expect(setSiblingIdx).not.toHaveBeenCalled();+ expect(enterEdit).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/Chat/Messages/Feedback.tsx b/client/src/components/Chat/Messages/Feedback.tsxindex 24b521283d..af6b063797 100644--- a/client/src/components/Chat/Messages/Feedback.tsx+++ b/client/src/components/Chat/Messages/Feedback.tsx@@ -21,6 +21,7 @@ import {ThumbUpIcon,ThumbDownIcon,} from '@librechat/client';+import { hoverButtonClasses } from './styles';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -218,17 +219,8 @@ function FeedbackButtons({);}-function buttonClasses(isActive: boolean, isLast: boolean) {- return cn(- 'hover-button size-auto rounded-lg p-1.5 text-text-secondary-alt',- 'hover:text-text-primary hover:bg-surface-hover',- 'group-hover:visible group-focus-within:visible group-[.final-completion]:visible',- !isLast &&- 'group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:hover)]:opacity-0',- 'focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:outline-none',- isActive && 'active text-text-primary bg-surface-hover',- );-}+const buttonClasses = (isActive: boolean, isLast: boolean) =>+ hoverButtonClasses({ isActive, isLast });export default function Feedback({isLast = false,diff --git a/client/src/components/Chat/Messages/Fork.tsx b/client/src/components/Chat/Messages/Fork.tsxindex 653d83ba22..341c7187fc 100644--- a/client/src/components/Chat/Messages/Fork.tsx+++ b/client/src/components/Chat/Messages/Fork.tsx@@ -8,7 +8,7 @@ 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 { cn } from '~/utils';+import { hoverButtonClasses } from './styles';import store from '~/store';interface PopoverButtonProps {@@ -216,7 +216,6 @@ export default function Fork({const { showToast } = useToastContext();const [remember, setRemember] = useState(false);const { navigateToConvo } = useNavigateToConvo();- const [isActive, setIsActive] = useState(false);const timeoutRef = useRef<NodeJS.Timeout | null>(null);const [forkSetting, setForkSetting] = useRecoilState(store.forkSetting);const [activeSetting, setActiveSetting] = useState(optionLabels.default);@@ -225,16 +224,12 @@ export default function Fork({const popoverStore = Ariakit.usePopoverStore({placement: 'bottom',});+ /** Read the open state from the store rather than mirroring it: Escape and+ * outside clicks close the popover without going through the trigger, so a+ * hand-kept copy would leave the button reading as active forever. */+ const isActive = Ariakit.useStoreState(popoverStore, 'open');- const buttonStyle = cn(- 'hover-button size-auto rounded-lg p-1.5 text-text-secondary-alt',- 'hover:text-text-primary hover:bg-surface-hover',- 'group-hover:visible group-focus-within:visible group-[.final-completion]:visible',- !isLast &&- 'group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:hover)]:opacity-0',- 'focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:outline-none',- isActive && 'active text-text-primary bg-surface-hover',- );+ const buttonStyle = hoverButtonClasses({ isActive, isLast });const forkConvo = useForkConvoMutation({onSuccess: (data) => {@@ -346,7 +341,6 @@ export default function Fork({});} else {popoverStore.toggle();- setIsActive(popoverStore.getState().open);}}}type="button"@@ -367,7 +361,6 @@ export default function Fork({}}portal={true}unmountOnHide={true}- onClose={() => setIsActive(false)}><div className="flex h-8 w-full items-center justify-center text-sm text-text-primary">{localize(activeSetting)}diff --git a/client/src/components/Chat/Messages/HoverButtons.tsx b/client/src/components/Chat/Messages/HoverButtons.tsxindex b1a627953c..98771fd2b6 100644--- a/client/src/components/Chat/Messages/HoverButtons.tsx+++ b/client/src/components/Chat/Messages/HoverButtons.tsx@@ -12,6 +12,7 @@ import {import type { TConversation, TMessage, TFeedback } from 'librechat-data-provider';import { useGenerationsByLatest, useLocalize } from '~/hooks';import { Fork } from '~/components/Conversations';+import { hoverButtonClasses } from './styles';import MessageAudio from './MessageAudio';import Feedback from './Feedback';import { cn } from '~/utils';@@ -38,8 +39,6 @@ type HoverButtonProps = {title: string;icon: React.ReactNode;isActive?: boolean;- isVisible?: boolean;- isDisabled?: boolean;isLast?: boolean;className?: string;buttonStyle?: string;@@ -85,26 +84,11 @@ const HoverButton = memo(title,icon,isActive = false,- isVisible = true,- isDisabled = false,isLast = false,className = '',dataTestId,}: HoverButtonProps) => {- const buttonStyle = cn(- 'hover-button size-auto rounded-lg p-1.5 text-text-secondary-alt',- 'hover:text-text-primary hover:bg-surface-hover',- 'group-hover:visible group-focus-within:visible group-[.final-completion]:visible',- !isLast &&- isVisible &&- 'group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:hover)]:opacity-0',- /** `!` is load-bearing: the shared Button sets `disabled:opacity-50`, which outranks a- * plain `opacity-0` and would leave a dimmed ghost of the hidden action on screen. */- !isVisible && 'pointer-events-none !opacity-0',- 'focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:outline-none',- isActive && isVisible && 'active text-text-primary bg-surface-hover',- className,- );+ const buttonStyle = hoverButtonClasses({ isActive, isLast, className });return (<TooltipAnchor@@ -118,7 +102,6 @@ const HoverButton = memo(aria-label={title}className={buttonStyle}onClick={onClick}- disabled={isDisabled}>{icon}</Button>@@ -172,6 +155,7 @@ const HoverButtons = ({regenerateEnabled,continueSupported,forkingSupported,+ isActiveStreamingMessage,isEditableEndpoint,} = generationCapabilities;@@ -181,22 +165,6 @@ const HoverButtons = ({const { isCreatedByUser, error } = message;- if (error === true) {- return (- <div className="visible flex justify-center self-end lg:justify-start">- {regenerateEnabled && (- <HoverButton- onClick={regenerate}- title={localize('com_ui_regenerate')}- icon={<RegenerateIcon size="19" />}- isLast={isLast}- dataTestId={isLast ? 'regenerate-generation-button' : undefined}- />- )}- </div>- );- }-const onEdit = () => {if (isEditing) {return enterEdit(true);@@ -209,7 +177,7 @@ const HoverButtons = ({return (<div className="group visible flex justify-center gap-0.5 self-end focus-within:outline-none lg:justify-start">{/* Text to Speech */}- {TextToSpeech && (+ {TextToSpeech && !error && !isActiveStreamingMessage && (<MessageAudioindex={index}isLast={isLast}@@ -229,48 +197,50 @@ const HoverButtons = ({)}{/* Copy Button */}- <HoverButton- onClick={handleCopy}- title={- isCopied ? localize('com_ui_copied_to_clipboard') : localize('com_ui_copy_to_clipboard')- }- icon={isCopied ? <CheckMark className="h-[18px] w-[18px]" /> : <Clipboard size="19" />}- isLast={isLast}- className={cn(- 'ml-0 flex items-center gap-1.5 text-xs',- isSubmitting && isCreatedByUser- ? 'group-hover:opacity-100 [@media(hover:hover)]:opacity-0'- : '',- )}- dataTestId={!isCreatedByUser ? 'copy-response-button' : undefined}- />+ {!isActiveStreamingMessage && (+ <HoverButton+ onClick={handleCopy}+ title={+ isCopied ? localize('com_ui_copied_to_clipboard') : localize('com_ui_copy_to_clipboard')+ }+ icon={isCopied ? <CheckMark className="h-[18px] w-[18px]" /> : <Clipboard size="19" />}+ isLast={isLast}+ className={cn(+ 'ml-0 flex items-center gap-1.5 text-xs',+ isSubmitting && isCreatedByUser+ ? 'group-hover:opacity-100 [@media(hover:hover)]:opacity-0'+ : '',+ )}+ dataTestId={!isCreatedByUser ? 'copy-response-button' : undefined}+ />+ )}{/* Edit Button */}- {isEditableEndpoint && (+ {isEditableEndpoint && !hideEditButton && (<HoverButtonid={`edit-${message.messageId}`}onClick={onEdit}title={localize('com_ui_edit')}icon={<EditIcon size="19" />}isActive={isEditing}- isVisible={!hideEditButton}- isDisabled={hideEditButton}isLast={isLast}className={isCreatedByUser ? '' : 'active'}/>)}{/* Fork Button */}- <Fork- messageId={message.messageId}- conversationId={conversation.conversationId}- forkingSupported={forkingSupported}- latestMessageId={latestMessageId}- isLast={isLast}- />+ {!error && !isActiveStreamingMessage && (+ <Fork+ messageId={message.messageId}+ conversationId={conversation.conversationId}+ forkingSupported={forkingSupported}+ latestMessageId={latestMessageId}+ isLast={isLast}+ />+ )}{/* Feedback Buttons */}- {!isCreatedByUser && handleFeedback != null && (+ {!error && !isActiveStreamingMessage && !isCreatedByUser && handleFeedback != null && (<Feedback handleFeedback={handleFeedback} feedback={message.feedback} isLast={isLast} />)}diff --git a/client/src/components/Chat/Messages/Message.tsx b/client/src/components/Chat/Messages/Message.tsxindex 9a1ce7313e..cd52066cdb 100644--- a/client/src/components/Chat/Messages/Message.tsx+++ b/client/src/components/Chat/Messages/Message.tsx@@ -13,7 +13,7 @@ const MessageContainer = React.memo(function MessageContainer({}) {return (<div- className="text-token-text-primary w-full border-0 bg-transparent"+ className="w-full border-0 bg-transparent text-text-primary"onWheel={handleScroll}onTouchMove={handleScroll}>@@ -35,7 +35,7 @@ function Message(props: TMessageProps) {return (<MessageContainer handleScroll={handleScroll}>- <div className="m-auto justify-center p-4 py-2 md:gap-6">+ <div className="m-auto justify-center px-4 py-3 md:px-6"><MessageRender {...props} isSubmitting={effectiveIsSubmitting} chatContext={chatContext} /></div></MessageContainer>diff --git a/client/src/components/Chat/Messages/MessageParts.tsx b/client/src/components/Chat/Messages/MessageParts.tsxindex 6091cb0993..151a70f913 100644--- a/client/src/components/Chat/Messages/MessageParts.tsx+++ b/client/src/components/Chat/Messages/MessageParts.tsx@@ -1,5 +1,4 @@import React, { useMemo } from 'react';-import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';import type { TMessageContentParts } from 'librechat-data-provider';import type { TMessageProps, TMessageIcon } from '~/common';@@ -11,10 +10,10 @@ import {} from '~/utils';import { useMessageHelpers, useLocalize, useAttachments, useContentMetadata } from '~/hooks';import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';-import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';+import { revealOnRowHoverClasses, messageFooterClasses } from './styles';+import MessageRow from '~/components/Chat/Messages/ui/MessageRow';import MessageIcon from '~/components/Chat/Messages/MessageIcon';import ContentParts from './Content/ContentParts';-import { fontSizeAtom } from '~/store/fontSize';import SiblingSwitch from './SiblingSwitch';import HoverButtons from './HoverButtons';import SubRow from './SubRow';@@ -43,7 +42,6 @@ function MessageParts(props: TMessageProps) {regenerateMessage,} = useMessageHelpers(props);- const fontSize = useAtomValue(fontSizeAtom);const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);const { messageId = null, isCreatedByUser } = message ?? {};@@ -97,112 +95,73 @@ function MessageParts(props: TMessageProps) {return null;}- const getChatWidthClass = () => {- if (maximizeChatSpace) {- return 'w-full max-w-full md:px-5 lg:px-1 xl:px-5';- }- if (hasParallelContent) {- return 'md:max-w-[58rem] xl:max-w-[70rem]';- }- return 'md:max-w-[47rem] xl:max-w-[55rem]';- };-- const baseClasses = {- common: 'group mx-auto flex flex-1 gap-3 transition-all duration-300 transform-gpu',- chat: getChatWidthClass(),- };-return (- <>- <div- className="w-full border-0 bg-transparent"- onWheel={handleScroll}- onTouchMove={handleScroll}- >- <div className="m-auto justify-center p-4 py-2 md:gap-6">- <div- id={messageId ?? ''}- aria-label={getMessageAriaLabel(message, localize)}- className={cn(- baseClasses.common,- baseClasses.chat,- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-xheavy',- 'message-render',- )}- >- {!hasParallelContent && (- <div className="relative flex flex-shrink-0 flex-col items-center">- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full pt-0.5">- <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />- </div>- </div>- )}- <div- className={cn(- 'relative flex flex-col',- hasParallelContent ? 'w-full' : 'w-11/12',- isCreatedByUser ? 'user-turn' : 'agent-turn',- )}- >- {!hasParallelContent && (- <h2 className={cn('select-none font-semibold text-text-primary', fontSize)}>- <span className="sr-only">- {getHeaderPrefixForScreenReader(message, localize)}- </span>- {name}- <MessageTimestamp value={message.createdAt ?? message.clientTimestamp} />- </h2>- )}- <div className="flex flex-col gap-1">- <div className="flex min-h-[20px] max-w-full flex-grow flex-col gap-0">- <ContentParts- edit={edit}- isLast={isLast}- enterEdit={enterEdit}- siblingIdx={siblingIdx}- attachments={attachments}- isSubmitting={isSubmitting}- searchResults={searchResults}- manualSkills={message.manualSkills}- messageId={message.messageId}- authorHeader={authorHeader}- setSiblingIdx={setSiblingIdx}- isCreatedByUser={message.isCreatedByUser}- conversationId={conversation?.conversationId}- isLatestMessage={messageId === latestMessageId}- content={message.content as Array<TMessageContentParts | undefined>}- />- </div>- {isLast && isSubmitting ? (- <div className="mt-1 h-[31px] bg-transparent" />- ) : (- <SubRow classes="text-xs">- <SiblingSwitch- siblingIdx={siblingIdx}- siblingCount={siblingCount}- setSiblingIdx={setSiblingIdx}- />- <HoverButtons- index={index}- isEditing={edit}- message={message}- enterEdit={enterEdit}- isSubmitting={isSubmitting}- conversation={conversation ?? null}- regenerate={() => regenerateMessage()}- copyToClipboard={copyToClipboard}- handleContinue={handleContinue}- latestMessageId={latestMessageId}- isLast={isLast}- />- </SubRow>+ <div+ className="w-full border-0 bg-transparent"+ onWheel={handleScroll}+ onTouchMove={handleScroll}+ >+ <div className="m-auto justify-center px-4 py-3 md:px-6">+ <MessageRow+ id={messageId ?? ''}+ icon={<MessageIcon iconData={iconData} assistant={assistant} agent={agent} />}+ label={name}+ timestamp={message.createdAt ?? message.clientTimestamp}+ ariaLabel={getMessageAriaLabel(message, localize)}+ headerPrefix={getHeaderPrefixForScreenReader(message, localize)}+ isCreatedByUser={isCreatedByUser === true}+ hasParallelContent={hasParallelContent}+ fullWidth={maximizeChatSpace}+ isEditing={edit}+ footer={+ <SubRow classes={cn(messageFooterClasses, isCreatedByUser && 'justify-end')}>+ {/* While the answer is generating every other action is withheld, which+ would otherwise leave this counter sitting alone under a half-written+ response. It reveals on hover there, like the actions it sits with. */}+ <SiblingSwitch+ siblingIdx={siblingIdx}+ siblingCount={siblingCount}+ setSiblingIdx={setSiblingIdx}+ className={cn(+ isSubmitting && messageId === latestMessageId && revealOnRowHoverClasses,)}- </div>- </div>- </div>- </div>+ />+ <HoverButtons+ index={index}+ isEditing={edit}+ message={message}+ enterEdit={enterEdit}+ isSubmitting={isSubmitting}+ conversation={conversation ?? null}+ regenerate={() => regenerateMessage()}+ copyToClipboard={copyToClipboard}+ handleContinue={handleContinue}+ latestMessageId={latestMessageId}+ isLast={isLast}+ />+ </SubRow>+ }+ >+ <ContentParts+ edit={edit}+ isLast={isLast}+ enterEdit={enterEdit}+ siblingIdx={siblingIdx}+ attachments={attachments}+ isSubmitting={isSubmitting}+ searchResults={searchResults}+ manualSkills={message.manualSkills}+ messageId={message.messageId}+ authorHeader={authorHeader}+ setSiblingIdx={setSiblingIdx}+ isCreatedByUser={message.isCreatedByUser}+ conversationId={conversation?.conversationId}+ isLatestMessage={messageId === latestMessageId}+ content={message.content as Array<TMessageContentParts | undefined>}+ />+ </MessageRow></div>- </>+ </div>);}diff --git a/client/src/components/Chat/Messages/SearchMessage.tsx b/client/src/components/Chat/Messages/SearchMessage.tsxindex 6405f7bff8..42f972f6e5 100644--- a/client/src/components/Chat/Messages/SearchMessage.tsx+++ b/client/src/components/Chat/Messages/SearchMessage.tsx@@ -1,46 +1,18 @@import { memo, useMemo } from 'react';-import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';import type { TMessage } from 'librechat-data-provider';import type { TMessageProps, TMessageIcon } from '~/common';import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';-import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';+import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';+import MessageRow from '~/components/Chat/Messages/ui/MessageRow';import Icon from '~/components/Chat/Messages/MessageIcon';import { useAuthContext, useLocalize } from '~/hooks';import SearchContent from './Content/SearchContent';-import { fontSizeAtom } from '~/store/fontSize';import SearchButtons from './SearchButtons';import SubRow from './SubRow';-import { cn } from '~/utils';import store from '~/store';-const MessageAvatar = ({ iconData }: { iconData: TMessageIcon }) => (- <div className="relative flex flex-shrink-0 flex-col items-end">- <div className="pt-0.5">- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">- <Icon iconData={iconData} />- </div>- </div>- </div>-);--const MessageBody = ({ message, messageLabel, fontSize, authorHeader }) => (- <div- className={cn('relative flex w-11/12 flex-col', message.isCreatedByUser ? '' : 'agent-turn')}- >- <div className={cn('select-none font-semibold', fontSize)}>- {messageLabel}- <MessageTimestamp value={message.createdAt ?? message.clientTimestamp} />- </div>- <SearchContent message={message} authorHeader={authorHeader} />- <SubRow classes="text-xs">- <MinimalHoverButtons message={message} />- <SearchButtons message={message} />- </SubRow>- </div>-);-function searchFilesEqual(prev?: TMessage['files'], next?: TMessage['files']) {if (prev === next) {return true;@@ -94,7 +66,6 @@ export function areSearchMessagePropsEqual(}function SearchMessage({ message }: Pick<TMessageProps, 'message'>) {- const fontSize = useAtomValue(fontSizeAtom);const UsernameDisplay = useRecoilValue<boolean>(store.UsernameDisplay);const { user } = useAuthContext();const localize = useLocalize();@@ -138,17 +109,26 @@ function SearchMessage({ message }: Pick<TMessageProps, 'message'>) {}return (- <div className="text-token-text-primary w-full bg-transparent">- <div className="m-auto p-4 py-2 md:gap-6">- <div className="final-completion group mx-auto flex flex-1 gap-3 md:max-w-3xl md:px-5 lg:max-w-[40rem] lg:px-1 xl:max-w-[48rem] xl:px-5">- <MessageAvatar iconData={iconData} />- <MessageBody- message={message}- messageLabel={messageLabel}- fontSize={fontSize}- authorHeader={authorHeader}- />- </div>+ <div className="w-full bg-transparent text-text-primary">+ <div className="m-auto px-4 py-3 md:px-6">+ <MessageRow+ id={message.messageId}+ icon={<Icon iconData={iconData} />}+ label={messageLabel}+ timestamp={message.createdAt ?? message.clientTimestamp}+ ariaLabel={getMessageAriaLabel(message, localize)}+ headerPrefix={getHeaderPrefixForScreenReader(message, localize)}+ isCreatedByUser={message.isCreatedByUser === true}+ className="final-completion"+ footer={+ <SubRow classes={message.isCreatedByUser ? 'justify-end text-xs' : 'text-xs'}>+ <MinimalHoverButtons message={message} />+ <SearchButtons message={message} />+ </SubRow>+ }+ >+ <SearchContent message={message} authorHeader={authorHeader} />+ </MessageRow></div></div>);diff --git a/client/src/components/Chat/Messages/SiblingSwitch.tsx b/client/src/components/Chat/Messages/SiblingSwitch.tsxindex bdc9a6489c..4e566fb1c5 100644--- a/client/src/components/Chat/Messages/SiblingSwitch.tsx+++ b/client/src/components/Chat/Messages/SiblingSwitch.tsx@@ -4,12 +4,15 @@ import type { TMessageProps } from '~/common';import { useLocalize } from '~/hooks';import { cn } from '~/utils';-type TSiblingSwitchProps = Pick<TMessageProps, 'siblingIdx' | 'siblingCount' | 'setSiblingIdx'>;+type TSiblingSwitchProps = Pick<TMessageProps, 'siblingIdx' | 'siblingCount' | 'setSiblingIdx'> & {+ className?: string;+};export default function SiblingSwitch({siblingIdx,siblingCount,setSiblingIdx,+ className,}: TSiblingSwitchProps) {const localize = useLocalize();@@ -36,7 +39,10 @@ export default function SiblingSwitch({return siblingCount > 1 ? (<nav- className="visible flex items-center justify-center gap-2 self-center pt-0 text-xs"+ className={cn(+ 'visible flex items-center justify-center gap-2 self-center pt-0 text-xs',+ className,+ )}aria-label={localize('com_ui_sibling_navigation')}><Buttondiff --git a/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx b/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsxindex efebd8a82d..ed0bb12166 100644--- a/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx+++ b/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx@@ -1,12 +1,13 @@import React, { useMemo } from 'react';-import { RecoilRoot, type MutableSnapshot } from 'recoil';import { MemoryRouter } from 'react-router-dom';-import { render, screen, act } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query';+import { RecoilRoot, type MutableSnapshot } from 'recoil';+import { render, screen, act } from '@testing-library/react';import { QueryKeys, type TConversation, type TMessage } from 'librechat-data-provider';-import { ChatContext, MessagesViewProvider, useChatContext } from '~/Providers';+import { QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query';import { useLatestMessage, useLatestMessageId } from '~/hooks/Messages/useLatestMessage';+import { ChatContext, MessagesViewProvider, useChatContext } from '~/Providers';+import StructuredMessage from '~/components/Messages/MessageContent';import Message from '~/components/Chat/Messages/Message';import store from '~/store';@@ -25,14 +26,21 @@ jest.mock('~/components/Chat/Messages/Content/MessageContent', () => ({default: ({ text }: { text: string }) => <div data-testid="message-content">{text}</div>,}));-jest.mock('~/components/Chat/Messages/MessageIcon', () => ({+jest.mock('~/components/Chat/Messages/Content/ContentParts', () => ({__esModule: true,- default: () => <div data-testid="message-icon" />,+ default: ({ content }: { content?: TMessage['content'] }) => (+ <div data-testid="structured-message-content">{JSON.stringify(content ?? [])}</div>+ ),}));-jest.mock('~/components/Chat/Messages/ui/PlaceholderRow', () => ({+jest.mock('~/components/Chat/Messages/Content/Parts/AuthorHeader', () => ({__esModule: true,- default: () => <div data-testid="placeholder-row" />,+ default: () => <div data-testid="author-header" />,+}));++jest.mock('~/components/Chat/Messages/MessageIcon', () => ({+ __esModule: true,+ default: () => <div data-testid="message-icon" />,}));jest.mock('~/hooks', () => {@@ -44,6 +52,7 @@ jest.mock('~/hooks', () => {useMessageProcess,useMemoizedChatContext,useContentMetadata: () => ({ hasParallelContent: false }),+ useAttachments: () => ({ attachments: [], searchResults: undefined }),useLocalize: () => (key: string) => key,useMessageActions: ({chatContext,@@ -106,6 +115,16 @@ const canonicalAssistantMessage = {text: 'Streaming canonical response',} as TMessage;+const optimisticStructuredAssistantMessage = {+ ...optimisticAssistantMessage,+ content: [{ type: 'text', text: '' }],+} as TMessage;++const canonicalStructuredAssistantMessage = {+ ...canonicalAssistantMessage,+ content: [{ type: 'text', text: 'Streaming structured response' }],+} as TMessage;+function createQueryClient() {return new QueryClient({defaultOptions: {@@ -116,7 +135,7 @@ function createQueryClient() {});}-function DerivedStreamingRow() {+function DerivedStreamingRow({ structured = false }: { structured?: boolean }) {const queryClient = useQueryClient();const latestMessage = useLatestMessage(0);const latestMessageId = useLatestMessageId(0);@@ -151,20 +170,28 @@ function DerivedStreamingRow() {return null;}+ const MessageComponent = structured ? StructuredMessage : Message;return (<ChatContext.Provider value={chatContext}><MessagesViewProvider>- <Message message={latestMessage} currentEditId={null} setCurrentEditId={jest.fn()} />+ <MessageComponent+ message={latestMessage}+ currentEditId={null}+ setCurrentEditId={jest.fn()}+ siblingIdx={0}+ siblingCount={2}+ setSiblingIdx={jest.fn()}+ /></MessagesViewProvider></ChatContext.Provider>);}-function renderStreamingRow() {+function renderStreamingRow(structured = false) {const queryClient = createQueryClient();queryClient.setQueryData<TMessage[]>([QueryKeys.messages, conversation.conversationId],- [userMessage, optimisticAssistantMessage],+ [userMessage, structured ? optimisticStructuredAssistantMessage : optimisticAssistantMessage],);const initializeState = ({ set }: MutableSnapshot) => {@@ -176,7 +203,7 @@ function renderStreamingRow() {<QueryClientProvider client={queryClient}><RecoilRoot initializeState={initializeState}><MemoryRouter initialEntries={[`/c/${conversation.conversationId}`]}>- <DerivedStreamingRow />+ <DerivedStreamingRow structured={structured} /></MemoryRouter></RecoilRoot></QueryClientProvider>,@@ -190,14 +217,14 @@ describe('streaming hover actions', () => {mockHoverButtonsRenderCount = 0;});- it('does not mount hover actions while an optimistic assistant row is replaced', async () => {+ it('keeps actions mounted while an optimistic assistant row is replaced', async () => {const user = userEvent.setup();const queryClient = renderStreamingRow();await user.hover(screen.getByTestId('message-content'));- expect(screen.queryByTestId('hover-buttons')).toBeNull();- expect(mockHoverButtonsRenderCount).toBe(0);+ expect(screen.getByTestId('hover-buttons')).toBeInTheDocument();+ expect(mockHoverButtonsRenderCount).toBeGreaterThan(0);act(() => {queryClient.setQueryData<TMessage[]>(@@ -206,8 +233,55 @@ describe('streaming hover actions', () => {);});- expect(screen.queryByTestId('hover-buttons')).toBeNull();- expect(mockHoverButtonsRenderCount).toBe(0);- expect(screen.getByTestId('placeholder-row')).toBeInTheDocument();+ expect(screen.getByTestId('hover-buttons')).toBeInTheDocument();+ expect(mockHoverButtonsRenderCount).toBeGreaterThan(0);+ });++ it('keeps actions mounted for structured tool-capable responses', async () => {+ const user = userEvent.setup();+ const queryClient = renderStreamingRow(true);++ await user.hover(screen.getByTestId('structured-message-content'));++ expect(screen.getByTestId('hover-buttons')).toBeInTheDocument();++ act(() => {+ queryClient.setQueryData<TMessage[]>(+ [QueryKeys.messages, conversation.conversationId],+ [userMessage, canonicalStructuredAssistantMessage],+ );+ });++ expect(screen.getByTestId('hover-buttons')).toBeInTheDocument();+ });++ /**+ * Every other action is withheld from the row that is still generating, so an+ * always-visible retry counter would sit alone under a half-written answer. Both+ * response formats have to fade it the same way.+ */+ it.each([+ ['a plain text', false],+ ['a structured', true],+ ])('fades retry navigation to hover-only on %s streaming row', (_label, structured) => {+ renderStreamingRow(structured);++ expect(screen.getByRole('navigation', { name: 'com_ui_sibling_navigation' })).toHaveClass(+ '[@media(hover:hover)]:opacity-0',+ );+ });++ /**+ * The row that is still generating withholds every action, and a lone sibling+ * counter renders nothing, so its footer measures zero until the answer lands.+ * Reserving the height keeps the transcript still at the moment it does.+ */+ it.each([+ ['a plain text', false],+ ['a structured', true],+ ])('holds the footer height while %s response streams', (_label, structured) => {+ renderStreamingRow(structured);++ expect(screen.getByTestId('hover-buttons').parentElement).toHaveClass('min-h-[31px]');});});diff --git a/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx b/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsxindex 4a6ab73c4e..0e0a24792f 100644--- a/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx+++ b/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx@@ -1,6 +1,6 @@import React from 'react';-import { render } from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';+import { render, screen } from '@testing-library/react';import { RecoilRoot, type MutableSnapshot } from 'recoil';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { EModelEndpoint, type TConversation, type TMessage } from 'librechat-data-provider';@@ -21,7 +21,17 @@ const userMessage = {text: 'tell me a long story',} as TMessage;-function renderHoverButtons(isSubmitting: boolean) {+function renderHoverButtons({+ isSubmitting,+ message = userMessage,+ isLast = false,+ latestMessageId = 'assistant-1',+}: {+ isSubmitting: boolean;+ message?: TMessage;+ isLast?: boolean;+ latestMessageId?: string;+}) {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});@@ -34,48 +44,83 @@ function renderHoverButtons(isSubmitting: boolean) {<MemoryRouter><HoverButtonsindex={0}- isLast={false}+ isLast={isLast}isEditing={false}- message={userMessage}+ message={message}conversation={conversation}isSubmitting={isSubmitting}enterEdit={jest.fn()}regenerate={jest.fn()}handleContinue={jest.fn()}copyToClipboard={jest.fn()}- latestMessageId="assistant-1"+ latestMessageId={latestMessageId}/></MemoryRouter></RecoilRoot></QueryClientProvider>,);- const editButton = container.querySelector<HTMLButtonElement>(`#edit-${userMessage.messageId}`);- if (!editButton) {- throw new Error('edit button not rendered');- }- return editButton;+ return container;}describe('HoverButtons edit affordance', () => {- it('stays hidden on row hover while a generation is in flight', () => {- const editButton = renderHoverButtons(true);-- expect(editButton).toBeDisabled();- expect(editButton).toHaveClass('pointer-events-none');- expect(editButton.className).not.toMatch(/group-hover:opacity-100/);- expect(editButton.className).not.toMatch(/group-focus-within:opacity-100/);- /** Must outrank the shared Button's `disabled:opacity-50`; a bare `opacity-0` loses to it,- * and jsdom applies no stylesheet, so the important modifier is what we can assert here. */- expect(editButton).toHaveClass('!opacity-0');- expect(editButton).not.toHaveClass('opacity-0');+ it('keeps edit available on an earlier message while a generation is in flight', () => {+ const container = renderHoverButtons({ isSubmitting: true });+ const editButton = container.querySelector<HTMLButtonElement>(`#edit-${userMessage.messageId}`);++ expect(editButton).not.toBeNull();+ expect(editButton).toBeEnabled();+ expect(editButton).not.toHaveClass('pointer-events-none', 'opacity-0', '!opacity-0');});it('reveals on row hover once the generation settles', () => {- const editButton = renderHoverButtons(false);+ const container = renderHoverButtons({ isSubmitting: false });+ const editButton = container.querySelector<HTMLButtonElement>(`#edit-${userMessage.messageId}`);+ expect(editButton).not.toBeNull();expect(editButton).toBeEnabled();expect(editButton).toHaveClass('group-hover:opacity-100');expect(editButton).not.toHaveClass('pointer-events-none', 'opacity-0', '!opacity-0');});++ it('offers no actions at all on the actively streaming assistant message', () => {+ const assistantMessage = {+ ...userMessage,+ messageId: 'assistant-1',+ isCreatedByUser: false,+ text: 'Partial response',+ } as TMessage;++ const container = renderHoverButtons({+ isSubmitting: true,+ message: assistantMessage,+ isLast: true,+ latestMessageId: assistantMessage.messageId,+ });++ /** Copying, forking or editing half a sentence all act on text that is about+ * to change, so the response carries nothing until it settles. */+ expect(container.querySelector(`#edit-${assistantMessage.messageId}`)).toBeNull();+ expect(screen.queryByTestId('copy-response-button')).toBeNull();+ expect(container.querySelectorAll('button')).toHaveLength(0);+ });++ it('offers copy for an error response', () => {+ const errorMessage = {+ ...userMessage,+ messageId: 'assistant-error',+ isCreatedByUser: false,+ error: true,+ text: 'Tool execution failed',+ } as TMessage;++ renderHoverButtons({+ isSubmitting: false,+ message: errorMessage,+ isLast: true,+ latestMessageId: errorMessage.messageId,+ });++ expect(screen.getByTestId('copy-response-button')).toBeEnabled();+ });});diff --git a/client/src/components/Chat/Messages/__tests__/styles.spec.ts b/client/src/components/Chat/Messages/__tests__/styles.spec.tsnew file mode 100644index 0000000000..87653176d0--- /dev/null+++ b/client/src/components/Chat/Messages/__tests__/styles.spec.ts@@ -0,0 +1,45 @@+import { hoverButtonClasses, messageFooterClasses } from '../styles';++const FADE = '[@media(hover:hover)]:opacity-0';++describe('hoverButtonClasses', () => {+ it('fades an idle action out until the row is hovered', () => {+ expect(hoverButtonClasses()).toContain(FADE);+ expect(hoverButtonClasses()).toContain('group-hover:opacity-100');+ });++ it('marks an active action so the toolbar can key off it', () => {+ expect(hoverButtonClasses({ isActive: true })).toContain('hover-button-active');+ expect(hoverButtonClasses({ isActive: true })).toContain('active');+ });++ it('keeps every action opaque while any of them is active', () => {+ expect(hoverButtonClasses()).toContain('group-has-[.hover-button-active]:opacity-100');+ expect(hoverButtonClasses({ isActive: true })).toContain(+ 'group-has-[.hover-button-active]:opacity-100',+ );+ expect(hoverButtonClasses({ isLast: true })).toContain(+ 'group-has-[.hover-button-active]:opacity-100',+ );+ });++ it('does not use the legacy active class as the marker', () => {+ expect(hoverButtonClasses()).not.toContain('group-has-[.active]');+ });++ it('never fades the actions on the last row', () => {+ expect(hoverButtonClasses({ isLast: true })).not.toContain(FADE);+ });++ it('appends caller classes', () => {+ expect(hoverButtonClasses({ className: 'ml-0' })).toContain('ml-0');+ });+});++describe('messageFooterClasses', () => {+ /** A hover button is a 19px icon with p-1.5 either side, so the row it forms is+ * 31px. The footer holds that height even while it has nothing to show. */+ it('reserves the height of the action row', () => {+ expect(messageFooterClasses).toContain('min-h-[31px]');+ });+});diff --git a/client/src/components/Chat/Messages/styles.ts b/client/src/components/Chat/Messages/styles.tsnew file mode 100644index 0000000000..4ed8962b39--- /dev/null+++ b/client/src/components/Chat/Messages/styles.ts@@ -0,0 +1,57 @@+import { cn } from '~/utils';++/**+ * Reveal-on-hover for a control that shares the message footer with the hover actions.+ *+ * Pointer devices fade it out until the row is hovered or something inside it takes+ * focus. Touch devices, which cannot hover, keep it visible.+ */+export const revealOnRowHoverClasses =+ 'group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:hover)]:opacity-0';++/**+ * The message footer, holding the height of its action row.+ *+ * While an answer streams, every action is withheld and a lone sibling counter+ * renders nothing, so the row measures zero and then springs to the height of the+ * buttons the moment the answer lands. Holding that height from the start is what+ * keeps the transcript from stepping upward under the reader as a response+ * completes. The value is the height of a hover button, `p-1.5` either side of a+ * 19px icon.+ */+export const messageFooterClasses = 'min-h-[31px] text-xs';++type HoverButtonStyleOptions = {+ isActive?: boolean;+ isLast?: boolean;+ className?: string;+};++/**+ * Shared appearance for the message hover actions.+ *+ * The actions fade in with the row on pointer devices. When a button opens a+ * surface (the editor, the fork popover, a submitted rating) it reports+ * `isActive`, and the whole toolbar stays opaque for as long as that surface is+ * open, so the pointer can leave the row without the actions vanishing out from+ * under whatever it opened.+ *+ * The marker is deliberately not the legacy `active` class: `HoverButtons`+ * pins that one to the edit button of every assistant message, which would+ * hold the entire toolbar open on every assistant row.+ */+export const hoverButtonClasses = ({+ isActive = false,+ isLast = false,+ className,+}: HoverButtonStyleOptions = {}) =>+ cn(+ 'hover-button size-auto rounded-lg p-1.5 text-text-secondary-alt',+ 'hover:text-text-primary hover:bg-surface-hover',+ 'group-hover:visible group-focus-within:visible group-[.final-completion]:visible',+ !isLast && revealOnRowHoverClasses,+ 'group-has-[.hover-button-active]:visible group-has-[.hover-button-active]:opacity-100',+ 'focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:outline-none',+ isActive && 'hover-button-active active text-text-primary bg-surface-hover',+ className,+ );diff --git a/client/src/components/Chat/Messages/ui/MessageRender.tsx b/client/src/components/Chat/Messages/ui/MessageRender.tsxindex 046806b78c..d5e153724a 100644--- a/client/src/components/Chat/Messages/ui/MessageRender.tsx+++ b/client/src/components/Chat/Messages/ui/MessageRender.tsx@@ -1,5 +1,4 @@import React, { useCallback, useMemo, memo } from 'react';-import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';import type { TMessage } from 'librechat-data-provider';import type { TMessageProps, TMessageIcon, TMessageChatContext } from '~/common';@@ -9,15 +8,14 @@ import {getHeaderPrefixForScreenReader,getMessageAriaLabel,} from '~/utils';+import { revealOnRowHoverClasses, messageFooterClasses } from '~/components/Chat/Messages/styles';import MessageContent from '~/components/Chat/Messages/Content/MessageContent';-import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';import { useLocalize, useMessageActions, useContentMetadata } from '~/hooks';-import PlaceholderRow from '~/components/Chat/Messages/ui/PlaceholderRow';import SiblingSwitch from '~/components/Chat/Messages/SiblingSwitch';import HoverButtons from '~/components/Chat/Messages/HoverButtons';+import MessageRow from '~/components/Chat/Messages/ui/MessageRow';import MessageIcon from '~/components/Chat/Messages/MessageIcon';import SubRow from '~/components/Chat/Messages/SubRow';-import { fontSizeAtom } from '~/store/fontSize';import { MessageContext } from '~/Providers';import store from '~/store';@@ -99,7 +97,6 @@ const MessageRender = memo(function MessageRender({setCurrentEditId,chatContext,});- const fontSize = useAtomValue(fontSizeAtom);const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);const handleRegenerateMessage = useCallback(() => regenerateMessage(), [regenerateMessage]);@@ -146,106 +143,69 @@ const MessageRender = memo(function MessageRender({return null;}- const getChatWidthClass = () => {- if (maximizeChatSpace) {- return 'w-full max-w-full md:px-5 lg:px-1 xl:px-5';- }- if (hasParallelContent) {- return 'md:max-w-[58rem] xl:max-w-[70rem]';- }- return 'md:max-w-[47rem] xl:max-w-[55rem]';- };-- const baseClasses = {- common: 'group mx-auto flex flex-1 gap-3 transition-all duration-300 transform-gpu ',- chat: getChatWidthClass(),- };-- const conditionalClasses = {- focus: 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-xheavy',- };-return (- <div+ <MessageRowid={msg.messageId}- aria-label={getMessageAriaLabel(msg, localize)}- className={cn(- baseClasses.common,- baseClasses.chat,- conditionalClasses.focus,- 'message-render',- )}- >- {!hasParallelContent && (- <div className="relative flex flex-shrink-0 flex-col items-center">- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">- <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />- </div>- </div>- )}-- <div- className={cn(- 'relative flex flex-col',- hasParallelContent ? 'w-full' : 'w-11/12',- msg.isCreatedByUser ? 'user-turn' : 'agent-turn',- )}- >- {!hasParallelContent && (- <h2 className={cn('select-none font-semibold', fontSize)}>- <span className="sr-only">{getHeaderPrefixForScreenReader(msg, localize)}</span>- {messageLabel}- <MessageTimestamp value={msg.createdAt ?? msg.clientTimestamp} />- </h2>- )}+ icon={<MessageIcon iconData={iconData} assistant={assistant} agent={agent} />}+ label={messageLabel ?? ''}+ timestamp={msg.createdAt ?? msg.clientTimestamp}+ ariaLabel={getMessageAriaLabel(msg, localize)}+ headerPrefix={getHeaderPrefixForScreenReader(msg, localize)}+ isCreatedByUser={msg.isCreatedByUser === true}+ hasParallelContent={hasParallelContent}+ fullWidth={maximizeChatSpace}+ isEditing={edit}+ footer={+ <SubRow classes={cn(messageFooterClasses, msg.isCreatedByUser && 'justify-end')}>+ {/* A user turn is right-aligned, so its retry navigation belongs at the+ outer edge under the bubble rather than inboard of the actions.- <div className="flex flex-col gap-1">- <div className="flex min-h-[20px] max-w-full flex-grow flex-col gap-0">- <MessageContext.Provider value={messageContextValue}>- <MessageContent- ask={ask}- edit={edit}- isLast={isLast}- text={msg.text || ''}- message={msg}- enterEdit={enterEdit}- error={!!(msg.error ?? false)}- isSubmitting={isSubmitting}- unfinished={msg.unfinished ?? false}- isCreatedByUser={msg.isCreatedByUser ?? true}- siblingIdx={siblingIdx ?? 0}- setSiblingIdx={setSiblingIdx ?? (() => ({}))}- />- </MessageContext.Provider>- </div>- {hasNoChildren && isSubmitting ? (- <PlaceholderRow />- ) : (- <SubRow classes="text-xs">- <SiblingSwitch- siblingIdx={siblingIdx}- siblingCount={siblingCount}- setSiblingIdx={setSiblingIdx}- />- <HoverButtons- index={index}- isEditing={edit}- message={msg}- enterEdit={enterEdit}- isSubmitting={chatContext.isSubmitting}- conversation={conversation ?? null}- regenerate={handleRegenerateMessage}- copyToClipboard={copyToClipboard}- handleContinue={handleContinue}- latestMessageId={latestMessageId}- handleFeedback={handleFeedback}- isLast={isLast}- />- </SubRow>- )}- </div>- </div>- </div>+ While the answer is generating every other action is withheld, which+ would otherwise leave this counter sitting alone under a half-written+ response. It reveals on hover there, like the actions it sits with. */}+ <SiblingSwitch+ siblingIdx={siblingIdx}+ siblingCount={siblingCount}+ setSiblingIdx={setSiblingIdx}+ className={cn(+ msg.isCreatedByUser === true && 'order-last',+ isSubmitting && isLatestMessage && revealOnRowHoverClasses,+ )}+ />+ <HoverButtons+ index={index}+ isEditing={edit}+ message={msg}+ enterEdit={enterEdit}+ isSubmitting={chatContext.isSubmitting}+ conversation={conversation ?? null}+ regenerate={handleRegenerateMessage}+ copyToClipboard={copyToClipboard}+ handleContinue={handleContinue}+ latestMessageId={latestMessageId}+ handleFeedback={handleFeedback}+ isLast={isLast}+ />+ </SubRow>+ }+ >+ <MessageContext.Provider value={messageContextValue}>+ <MessageContent+ ask={ask}+ edit={edit}+ isLast={isLast}+ text={msg.text || ''}+ message={msg}+ enterEdit={enterEdit}+ error={!!(msg.error ?? false)}+ isSubmitting={isSubmitting}+ unfinished={msg.unfinished ?? false}+ isCreatedByUser={msg.isCreatedByUser ?? true}+ siblingIdx={siblingIdx ?? 0}+ setSiblingIdx={setSiblingIdx ?? (() => ({}))}+ />+ </MessageContext.Provider>+ </MessageRow>);}, areMessageRenderPropsEqual);MessageRender.displayName = 'MessageRender';diff --git a/client/src/components/Chat/Messages/ui/MessageRow.tsx b/client/src/components/Chat/Messages/ui/MessageRow.tsxnew file mode 100644index 0000000000..44b303a39c--- /dev/null+++ b/client/src/components/Chat/Messages/ui/MessageRow.tsx@@ -0,0 +1,111 @@+import type { ReactNode } from 'react';+import MessageTimestamp from './MessageTimestamp';+import { cn } from '~/utils';++type MessageRowProps = {+ id?: string;+ label: string;+ icon: ReactNode;+ children: ReactNode;+ footer: ReactNode;+ timestamp?: string | null;+ ariaLabel?: string;+ headerPrefix?: string;+ isCreatedByUser: boolean;+ hasParallelContent?: boolean;+ fullWidth?: boolean;+ isEditing?: boolean;+ className?: string;+};++export default function MessageRow({+ id,+ icon,+ label,+ footer,+ children,+ timestamp,+ ariaLabel,+ className,+ headerPrefix,+ isCreatedByUser,+ hasParallelContent = false,+ fullWidth = false,+ isEditing = false,+}: MessageRowProps) {+ const showAssistantHeader = !isCreatedByUser && !hasParallelContent;+ let widthClass = 'w-full max-w-3xl';+ if (fullWidth) {+ widthClass = 'w-full max-w-full';+ } else if (hasParallelContent) {+ widthClass = 'w-full md:max-w-[58rem] xl:max-w-[70rem]';+ }++ return (+ <div+ id={id}+ role="group"+ aria-label={ariaLabel}+ className={cn(+ 'message-render group mx-auto flex min-w-0 flex-1 font-theme-ui transition-[max-width] duration-theme-normal motion-reduce:transition-none',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary',+ isCreatedByUser ? 'justify-end' : 'items-start gap-3',+ widthClass,+ className,+ )}+ >+ {showAssistantHeader && (+ <div+ className="relative flex flex-shrink-0 flex-col items-center pt-0.5"+ aria-hidden="true"+ >+ <div className="flex size-6 items-center justify-center overflow-hidden rounded-full">+ {icon}+ </div>+ </div>+ )}++ <div+ className={cn(+ 'relative flex min-w-0 flex-col',+ isCreatedByUser ? 'user-turn' : 'agent-turn',+ (hasParallelContent || isEditing) && 'w-full',+ !hasParallelContent &&+ isCreatedByUser &&+ cn('ml-auto items-end', !isEditing && 'w-fit max-w-[90%] sm:max-w-[85%]'),+ !hasParallelContent && !isCreatedByUser && !isEditing && 'flex-1',+ )}+ >+ {!hasParallelContent &&+ (isCreatedByUser ? (+ <h2 className="sr-only">+ {headerPrefix}+ {label}+ <MessageTimestamp value={timestamp} />+ </h2>+ ) : (+ <h2 className="flex min-h-7 select-none items-center text-sm font-semibold text-text-primary">+ <span className="sr-only">{headerPrefix}</span>+ {label}+ <MessageTimestamp value={timestamp} />+ </h2>+ ))}++ <div className={cn('flex w-full flex-col gap-1', isCreatedByUser && 'items-end')}>+ <div+ className={cn(+ 'flex min-h-[20px] max-w-full flex-grow flex-col gap-0',+ isCreatedByUser && !isEditing+ ? 'w-fit rounded-theme-surface rounded-br-theme-control bg-surface-tertiary px-theme-normal py-2.5'+ : 'w-full',+ )}+ data-testid="message-body"+ >+ {children}+ </div>+ <div className={cn('w-full', isCreatedByUser && 'flex justify-end')}>{footer}</div>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/Chat/Messages/ui/PlaceholderRow.tsx b/client/src/components/Chat/Messages/ui/PlaceholderRow.tsxdeleted file mode 100644index e60dc28278..0000000000--- a/client/src/components/Chat/Messages/ui/PlaceholderRow.tsx+++ /dev/null@@ -1,9 +0,0 @@-import { memo } from 'react';--/** Height matches the SubRow action buttons row (31px) — keep in sync with HoverButtons */-const PlaceholderRow = memo(function PlaceholderRow() {- return <div className="mt-1 h-[31px] bg-transparent" />;-});-PlaceholderRow.displayName = 'PlaceholderRow';--export default PlaceholderRow;diff --git a/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx b/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsxnew file mode 100644index 0000000000..5ac311f5b7--- /dev/null+++ b/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx@@ -0,0 +1,101 @@+import { render, screen } from '@testing-library/react';+import MessageRow from '../MessageRow';++jest.mock('../MessageTimestamp', () => ({+ __esModule: true,+ default: () => <span data-testid="message-timestamp" />,+}));++const MESSAGE_BODY = 'Message body';++const renderRow = ({+ isCreatedByUser,+ hasParallelContent = false,+ fullWidth = false,+ isEditing = false,+}: {+ isCreatedByUser: boolean;+ hasParallelContent?: boolean;+ fullWidth?: boolean;+ isEditing?: boolean;+}) =>+ render(+ <MessageRow+ id="message-1"+ label={isCreatedByUser ? 'You' : 'Assistant'}+ icon={<span data-testid="message-icon" />}+ footer={<div data-testid="message-actions" />}+ ariaLabel={isCreatedByUser ? 'User message' : 'Assistant message'}+ headerPrefix="Message from "+ isCreatedByUser={isCreatedByUser}+ hasParallelContent={hasParallelContent}+ fullWidth={fullWidth}+ isEditing={isEditing}+ >+ <p>{MESSAGE_BODY}</p>+ </MessageRow>,+ );++describe('MessageRow', () => {+ it('renders user content as a right-aligned semantic surface without a visible avatar', () => {+ renderRow({ isCreatedByUser: true });++ const row = screen.getByLabelText('User message');+ const userTurn = row.querySelector('.user-turn');+ const messageSurface = screen.getByText(MESSAGE_BODY).parentElement;++ expect(row).toHaveAttribute('role', 'group');+ expect(row).toHaveClass('justify-end');+ expect(userTurn).toHaveClass('items-end');+ expect(messageSurface).toHaveClass('bg-surface-tertiary', 'rounded-theme-surface');+ expect(screen.queryByTestId('message-icon')).not.toBeInTheDocument();+ expect(screen.getByRole('heading', { hidden: true })).toHaveClass('sr-only');+ });++ it('keeps assistant identity visible beside an open reading column', () => {+ renderRow({ isCreatedByUser: false });++ const row = screen.getByLabelText('Assistant message');++ expect(row.querySelector('.agent-turn')).toHaveClass('flex-1');+ expect(screen.getByTestId('message-icon')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: /Assistant/ })).toBeVisible();+ });++ it('preserves the assistant turn marker for parallel content', () => {+ renderRow({ isCreatedByUser: false, hasParallelContent: true });++ const row = screen.getByLabelText('Assistant message');++ expect(row.querySelector('.agent-turn')).toHaveClass('w-full');+ expect(screen.queryByTestId('message-icon')).not.toBeInTheDocument();+ expect(screen.queryByRole('heading')).not.toBeInTheDocument();+ });++ it('expands an edited user message without nesting the editor in a bubble', () => {+ renderRow({ isCreatedByUser: true, isEditing: true });++ const row = screen.getByLabelText('User message');+ const messageSurface = screen.getByTestId('message-body');++ expect(row.querySelector('.user-turn')).toHaveClass('w-full');+ expect(messageSurface).toHaveClass('w-full');+ expect(messageSurface).not.toHaveClass('bg-surface-tertiary');+ });++ it('expands an edited assistant message to full width', () => {+ renderRow({ isCreatedByUser: false, isEditing: true });++ const row = screen.getByLabelText('Assistant message');+ const messageSurface = screen.getByTestId('message-body');++ expect(row.querySelector('.agent-turn')).toHaveClass('w-full');+ expect(messageSurface).toHaveClass('w-full');+ });++ it('allows the maximized preference to use the full conversation width', () => {+ renderRow({ isCreatedByUser: false, fullWidth: true });++ expect(screen.getByLabelText('Assistant message')).toHaveClass('max-w-full');+ });+});diff --git a/client/src/components/Endpoints/MessageEndpointIcon.spec.tsx b/client/src/components/Endpoints/MessageEndpointIcon.spec.tsxnew file mode 100644index 0000000000..ea5f95e2fa--- /dev/null+++ b/client/src/components/Endpoints/MessageEndpointIcon.spec.tsx@@ -0,0 +1,31 @@+import { render } from '@testing-library/react';+import { EModelEndpoint } from 'librechat-data-provider';+import MessageEndpointIcon from './MessageEndpointIcon';++describe('MessageEndpointIcon', () => {+ it('uses the semantic foreground when an endpoint icon has no background', () => {+ const { container } = render(+ <MessageEndpointIcon+ endpoint={EModelEndpoint.custom}+ model="custom-model"+ isCreatedByUser={false}+ />,+ );++ expect(container.firstElementChild).toHaveClass('text-text-primary');+ expect(container.firstElementChild).not.toHaveClass('text-white');+ });++ it('keeps a contrasting foreground when an endpoint icon has a colored background', () => {+ const { container } = render(+ <MessageEndpointIcon+ endpoint={EModelEndpoint.openAI}+ model="gpt-4"+ isCreatedByUser={false}+ />,+ );++ expect(container.firstElementChild).toHaveClass('text-white');+ expect(container.firstElementChild).not.toHaveClass('text-text-primary');+ });+});diff --git a/client/src/components/Endpoints/MessageEndpointIcon.tsx b/client/src/components/Endpoints/MessageEndpointIcon.tsxindex 9849170278..bfd197d281 100644--- a/client/src/components/Endpoints/MessageEndpointIcon.tsx+++ b/client/src/components/Endpoints/MessageEndpointIcon.tsx@@ -183,6 +183,8 @@ const MessageEndpointIcon: React.FC<IconProps> = (props) => {return icon;}+ const hasBackground = typeof bg === 'string' && bg.length > 0;+return (<divtitle={name ?? ''}@@ -192,7 +194,8 @@ const MessageEndpointIcon: React.FC<IconProps> = (props) => {height: size,}}className={cn(- 'relative flex h-9 w-9 items-center justify-center rounded-sm p-1 text-white',+ 'relative flex h-9 w-9 items-center justify-center rounded-sm p-1',+ hasBackground ? 'text-white' : 'text-text-primary',props.className ?? '',)}>diff --git a/client/src/components/Messages/ContentRender.tsx b/client/src/components/Messages/ContentRender.tsxindex 0eb73c5e47..354e15382d 100644--- a/client/src/components/Messages/ContentRender.tsx+++ b/client/src/components/Messages/ContentRender.tsx@@ -1,5 +1,4 @@import { useCallback, useMemo, memo } from 'react';-import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';import type { TMessage, TMessageContentParts } from 'librechat-data-provider';import type { TMessageProps, TMessageIcon, TMessageChatContext } from '~/common';@@ -9,16 +8,15 @@ import {getHeaderPrefixForScreenReader,getMessageAriaLabel,} from '~/utils';+import { revealOnRowHoverClasses, messageFooterClasses } from '~/components/Chat/Messages/styles';import { useAttachments, useLocalize, useMessageActions, useContentMetadata } from '~/hooks';import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';-import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';import ContentParts from '~/components/Chat/Messages/Content/ContentParts';-import PlaceholderRow from '~/components/Chat/Messages/ui/PlaceholderRow';import SiblingSwitch from '~/components/Chat/Messages/SiblingSwitch';import HoverButtons from '~/components/Chat/Messages/HoverButtons';+import MessageRow from '~/components/Chat/Messages/ui/MessageRow';import MessageIcon from '~/components/Chat/Messages/MessageIcon';import SubRow from '~/components/Chat/Messages/SubRow';-import { fontSizeAtom } from '~/store/fontSize';import store from '~/store';type ContentRenderProps = {@@ -102,7 +100,6 @@ const ContentRender = memo(function ContentRender({setCurrentEditId,chatContext,});- const fontSize = useAtomValue(fontSizeAtom);const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);const handleRegenerateMessage = useCallback(() => regenerateMessage(), [regenerateMessage]);@@ -110,7 +107,6 @@ const ContentRender = memo(function ContentRender({() => !(msg?.children?.length ?? 0) && (msg?.depth === latestMessageDepth || msg?.depth === -1),[msg?.children, msg?.depth, latestMessageDepth],);- const hasNoChildren = !(msg?.children?.length ?? 0);const isLatestMessage = msg?.messageId === latestMessageId;const iconData: TMessageIcon = useMemo(@@ -149,108 +145,65 @@ const ContentRender = memo(function ContentRender({return null;}- const getChatWidthClass = () => {- if (maximizeChatSpace) {- return 'w-full max-w-full md:px-5 lg:px-1 xl:px-5';- }- if (hasParallelContent) {- return 'md:max-w-[58rem] xl:max-w-[70rem]';- }- return 'md:max-w-[47rem] xl:max-w-[55rem]';- };-- const baseClasses = {- common: 'group mx-auto flex flex-1 gap-3 transition-all duration-300 transform-gpu ',- chat: getChatWidthClass(),- };-- const conditionalClasses = {- focus: 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-xheavy',- };-return (- <div+ <MessageRowid={msg.messageId}- aria-label={getMessageAriaLabel(msg, localize)}- className={cn(- baseClasses.common,- baseClasses.chat,- conditionalClasses.focus,- 'message-render',- )}+ icon={<MessageIcon iconData={iconData} assistant={assistant} agent={agent} />}+ label={messageLabel ?? ''}+ timestamp={msg.createdAt ?? msg.clientTimestamp}+ ariaLabel={getMessageAriaLabel(msg, localize)}+ headerPrefix={getHeaderPrefixForScreenReader(msg, localize)}+ isCreatedByUser={msg.isCreatedByUser === true}+ hasParallelContent={hasParallelContent}+ fullWidth={maximizeChatSpace}+ isEditing={edit}+ footer={+ <SubRow classes={cn(messageFooterClasses, msg.isCreatedByUser && 'justify-end')}>+ {/* While the answer is generating every other action is withheld, which+ would otherwise leave this counter sitting alone under a half-written+ response. It reveals on hover there, like the actions it sits with. */}+ <SiblingSwitch+ siblingIdx={siblingIdx}+ siblingCount={siblingCount}+ setSiblingIdx={setSiblingIdx}+ className={cn(isSubmitting && isLatestMessage && revealOnRowHoverClasses)}+ />+ <HoverButtons+ index={index}+ message={msg}+ isEditing={edit}+ enterEdit={enterEdit}+ isSubmitting={chatContext.isSubmitting}+ conversation={conversation ?? null}+ regenerate={handleRegenerateMessage}+ copyToClipboard={copyToClipboard}+ handleContinue={handleContinue}+ latestMessageId={latestMessageId}+ handleFeedback={handleFeedback}+ isLast={isLast}+ />+ </SubRow>+ }>- {!hasParallelContent && (- <div className="relative flex flex-shrink-0 flex-col items-center">- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">- <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />- </div>- </div>- )}-- <div- className={cn(- 'relative flex flex-col',- hasParallelContent ? 'w-full' : 'w-11/12',- msg.isCreatedByUser ? 'user-turn' : 'agent-turn',- )}- >- {!hasParallelContent && (- <h2 className={cn('select-none font-semibold', fontSize)}>- <span className="sr-only">{getHeaderPrefixForScreenReader(msg, localize)}</span>- {messageLabel}- <MessageTimestamp value={msg.createdAt ?? msg.clientTimestamp} />- </h2>- )}-- <div className="flex flex-col gap-1">- <div className="flex min-h-[20px] max-w-full flex-grow flex-col gap-0">- <ContentParts- edit={edit}- isLast={isLast}- enterEdit={enterEdit}- siblingIdx={siblingIdx}- messageId={msg.messageId}- attachments={attachments}- searchResults={searchResults}- manualSkills={msg.manualSkills}- authorHeader={authorHeader}- setSiblingIdx={setSiblingIdx}- isLatestMessage={isLatestMessage}- isSubmitting={isSubmitting}- isCreatedByUser={msg.isCreatedByUser}- createdAt={msg.createdAt ?? msg.clientTimestamp}- conversationId={conversation?.conversationId}- content={msg.content as Array<TMessageContentParts | undefined>}- />- </div>- {hasNoChildren && isSubmitting ? (- <PlaceholderRow />- ) : (- <SubRow classes="text-xs">- <SiblingSwitch- siblingIdx={siblingIdx}- siblingCount={siblingCount}- setSiblingIdx={setSiblingIdx}- />- <HoverButtons- index={index}- message={msg}- isEditing={edit}- enterEdit={enterEdit}- isSubmitting={chatContext.isSubmitting}- conversation={conversation ?? null}- regenerate={handleRegenerateMessage}- copyToClipboard={copyToClipboard}- handleContinue={handleContinue}- latestMessageId={latestMessageId}- handleFeedback={handleFeedback}- isLast={isLast}- />- </SubRow>- )}- </div>- </div>- </div>+ <ContentParts+ edit={edit}+ isLast={isLast}+ enterEdit={enterEdit}+ siblingIdx={siblingIdx}+ messageId={msg.messageId}+ attachments={attachments}+ searchResults={searchResults}+ manualSkills={msg.manualSkills}+ authorHeader={authorHeader}+ setSiblingIdx={setSiblingIdx}+ isLatestMessage={isLatestMessage}+ isSubmitting={isSubmitting}+ isCreatedByUser={msg.isCreatedByUser}+ createdAt={msg.createdAt ?? msg.clientTimestamp}+ conversationId={conversation?.conversationId}+ content={msg.content as Array<TMessageContentParts | undefined>}+ />+ </MessageRow>);}, areContentRenderPropsEqual);ContentRender.displayName = 'ContentRender';diff --git a/client/src/components/Messages/MessageContent.tsx b/client/src/components/Messages/MessageContent.tsxindex 60e5d7c58f..99608b5916 100644--- a/client/src/components/Messages/MessageContent.tsx+++ b/client/src/components/Messages/MessageContent.tsx@@ -13,7 +13,7 @@ const MessageContainer = React.memo(function MessageContainer({}) {return (<div- className="text-token-text-primary w-full border-0 bg-transparent"+ className="w-full border-0 bg-transparent text-text-primary"onWheel={handleScroll}onTouchMove={handleScroll}>@@ -35,7 +35,7 @@ function MessageContent(props: TMessageProps) {return (<MessageContainer handleScroll={handleScroll}>- <div className="m-auto justify-center p-4 py-2 md:gap-6">+ <div className="m-auto justify-center px-4 py-3 md:px-6"><ContentRender {...props} isSubmitting={effectiveIsSubmitting} chatContext={chatContext} /></div></MessageContainer>diff --git a/client/src/components/Share/Message.tsx b/client/src/components/Share/Message.tsxindex a4442f62c5..36e3db67c9 100644--- a/client/src/components/Share/Message.tsx+++ b/client/src/components/Share/Message.tsx@@ -1,20 +1,19 @@-import { useAtomValue } from 'jotai';import type { TMessageProps } from '~/common';import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';import MessageContent from '~/components/Chat/Messages/Content/MessageContent';-import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';+import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';import SearchContent from '~/components/Chat/Messages/Content/SearchContent';import SiblingSwitch from '~/components/Chat/Messages/SiblingSwitch';+import MessageRow from '~/components/Chat/Messages/ui/MessageRow';import SubRow from '~/components/Chat/Messages/SubRow';-import { fontSizeAtom } from '~/store/fontSize';+import { useAttachments, useLocalize } from '~/hooks';import { MessageContext } from '~/Providers';import MultiMessage from './MultiMessage';-import { useAttachments } from '~/hooks';import Icon from './MessageIcon';-import { cn } from '~/utils';+export default function Message(props: TMessageProps) {- const fontSize = useAtomValue(fontSizeAtom);+ const localize = useLocalize();const {message,siblingIdx,@@ -43,79 +42,27 @@ export default function Message(props: TMessageProps) {isCreatedByUser = true,} = message;- let messageLabel = '';- if (isCreatedByUser) {- messageLabel = 'anonymous';- } else {- messageLabel = message.sender ?? '';- }+ /** Whoever opens a share link is not the author of the prompts in it, so this row+ * keeps a neutral label. `com_user_message` reads "You", which is right in the chat+ * view and wrong here: it is the screen-reader heading for the user turn, and it+ * would credit every prompt the sharer wrote to the person reading the transcript. */+ const messageLabel = isCreatedByUser ? localize('com_ui_user') : (message.sender ?? '');return (<>- <div className="text-token-text-primary w-full border-0 bg-transparent">- <div className="m-auto justify-center p-4 py-2 md:gap-6">- <div className="final-completion group mx-auto flex flex-1 gap-3 md:max-w-[47rem] md:px-5 lg:px-1 xl:max-w-[55rem] xl:px-5">- <div className="relative flex flex-shrink-0 flex-col items-end">- <div>- <div className="pt-0.5">- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">- <Icon message={message} conversation={conversation} />- </div>- </div>- </div>- </div>- <div- className={cn('relative flex w-11/12 flex-col', isCreatedByUser ? '' : 'agent-turn')}- >- <div className={cn('select-none font-semibold', fontSize)}>- {messageLabel}- <MessageTimestamp value={message.createdAt ?? message.clientTimestamp} />- </div>- <div className="flex-col gap-1 md:gap-3">- <div className="flex min-h-[20px] max-w-full flex-grow flex-col gap-0">- <MessageContext.Provider- value={{- messageId,- isExpanded: false,- conversationId: conversation?.conversationId,- isSubmitting: false, // Share view is always read-only- isLatestMessage: false, // No concept of latest message in share view- }}- >- {message.content ? (- <SearchContent- message={message}- attachments={attachments}- searchResults={searchResults}- authorHeader={- isCreatedByUser ? undefined : (- <AuthorHeader- icon={<Icon message={message} conversation={conversation} />}- label={messageLabel}- />- )- }- />- ) : (- <MessageContent- edit={false}- error={error}- isLast={false}- ask={() => {}}- text={text || ''}- message={message}- isSubmitting={false}- enterEdit={() => ({})}- unfinished={unfinished}- siblingIdx={siblingIdx ?? 0}- isCreatedByUser={isCreatedByUser}- setSiblingIdx={setSiblingIdx ?? (() => ({}))}- />- )}- </MessageContext.Provider>- </div>- </div>- <SubRow classes="text-xs">+ <div className="w-full border-0 bg-transparent text-text-primary">+ <div className="m-auto justify-center px-4 py-3 md:px-6">+ <MessageRow+ id={messageId}+ icon={<Icon message={message} conversation={conversation} />}+ label={messageLabel}+ timestamp={message.createdAt ?? message.clientTimestamp}+ ariaLabel={getMessageAriaLabel(message, localize)}+ headerPrefix={getHeaderPrefixForScreenReader(message, localize)}+ isCreatedByUser={isCreatedByUser}+ className="final-completion"+ footer={+ <SubRow classes={isCreatedByUser ? 'justify-end text-xs' : 'text-xs'}><SiblingSwitchsiblingIdx={siblingIdx}siblingCount={siblingCount}@@ -123,8 +70,49 @@ export default function Message(props: TMessageProps) {/><MinimalHoverButtons message={message} searchResults={searchResults} /></SubRow>- </div>- </div>+ }+ >+ <MessageContext.Provider+ value={{+ messageId,+ isExpanded: false,+ conversationId: conversation?.conversationId,+ isSubmitting: false,+ isLatestMessage: false,+ }}+ >+ {message.content ? (+ <SearchContent+ message={message}+ attachments={attachments}+ searchResults={searchResults}+ authorHeader={+ isCreatedByUser ? undefined : (+ <AuthorHeader+ icon={<Icon message={message} conversation={conversation} />}+ label={messageLabel}+ />+ )+ }+ />+ ) : (+ <MessageContent+ edit={false}+ error={error}+ isLast={false}+ ask={() => {}}+ text={text || ''}+ message={message}+ isSubmitting={false}+ enterEdit={() => ({})}+ unfinished={unfinished}+ siblingIdx={siblingIdx ?? 0}+ isCreatedByUser={isCreatedByUser}+ setSiblingIdx={setSiblingIdx ?? (() => ({}))}+ />+ )}+ </MessageContext.Provider>+ </MessageRow></div></div><MultiMessagediff --git a/client/src/hooks/Messages/__tests__/useMessageScrolling.spec.tsx b/client/src/hooks/Messages/__tests__/useMessageScrolling.spec.tsxindex 97f56e2943..cc0771b60b 100644--- a/client/src/hooks/Messages/__tests__/useMessageScrolling.spec.tsx+++ b/client/src/hooks/Messages/__tests__/useMessageScrolling.spec.tsx@@ -83,6 +83,9 @@ class MockIntersectionObserver {}}+/** Matches the hook's glide fallback, the window in which a landing is still pending. */+const glideWindow = 700;+const originalResizeObserver = global.ResizeObserver;const originalIntersectionObserver = global.IntersectionObserver;@@ -190,17 +193,25 @@ describe('useMessageScrolling resize reconciliation', () => {).IntersectionObserver = originalIntersectionObserver;});- it('scrolls to the bottom when streaming content resizes and auto-scroll is active', () => {+ it('rides the bottom when streaming content resizes and auto-scroll is active', () => {renderScrolling();const observer = MockResizeObserver.last();expect(observer?.observe).toHaveBeenCalledWith(screen.getByTestId('content'));+ const scrollable = screen.getByTestId('scrollable');+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });+ scrollable.scrollTop = 700;+act(() => {observer?.trigger();});- expect(mockScrollToBottom).toHaveBeenCalledTimes(1);+ /** Written straight to the element rather than routed through the throttled+ * scrollIntoView helper, so an answer arriving a few pixels at a time flows+ * instead of lurching once every throttle window. */+ expect(scrollable.scrollTop).toBe(800);});it('reconciles message layout after an explicit scroll to bottom', () => {@@ -214,14 +225,26 @@ describe('useMessageScrolling resize reconciliation', () => {expect(mockReconcileMessageContentLayout).toHaveBeenCalledWith(scrollable);});- it('does not follow resizes after the user aborts streaming auto-scroll', () => {+ /**+ * `useMessageProcess` raises the abort flag on any wheel at all, downward ones+ * included, through a throttle whose trailing call lands after the gesture has+ * ended. Gating on it meant scrolling down to the newest word could never resume+ * the ride, while the scroll-to-bottom button, which touches no wheel, always+ * could. Position and direction answer that question instead.+ */+ it('rides the bottom for a reader who is on it, even with the abort flag raised', () => {renderScrolling({ contextOverrides: { abortScroll: true } });+ const scrollable = screen.getByTestId('scrollable');+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });+ scrollable.scrollTop = 700;+act(() => {MockResizeObserver.last()?.trigger();});- expect(mockScrollToBottom).not.toHaveBeenCalled();+ expect(scrollable.scrollTop).toBe(800);});it('does not follow resizes after the user scrolls away from the bottom', () => {@@ -241,6 +264,63 @@ describe('useMessageScrolling resize reconciliation', () => {expect(mockScrollToBottom).not.toHaveBeenCalled();});+ it('judges the first scroll against a real previous position, not against the top', () => {+ const setAbortScroll = jest.fn();+ renderScrolling({ contextOverrides: { setAbortScroll } });++ const scrollable = screen.getByTestId('scrollable');+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });++ /** A thread opens at its end, so the reader's first gesture carries a large+ * positive scrollTop. Measured from 0 it read as a jump down onto the end, and+ * the reader was re-pinned to the stream they were trying to leave. */+ setAbortScroll.mockClear();+ scrollable.scrollTop = 700;+ fireEvent.scroll(scrollable);++ expect(setAbortScroll).not.toHaveBeenCalled();++ /** With a baseline taken, the same gesture is judged on its real delta. */+ scrollable.scrollTop = 500;+ fireEvent.scroll(scrollable);++ act(() => {+ MockResizeObserver.last()?.trigger();+ });++ expect(scrollable.scrollTop).toBe(500);+ });++ it('obeys the first scroll away from a thread that was placed at its end', () => {+ renderScrolling();++ const scrollable = screen.getByTestId('scrollable');+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });++ /** The thread opens at its end without the reader touching it, so the position+ * it was placed at is what their first gesture has to be judged against. */+ scrollable.scrollTop = 800;+ act(() => {+ mockScrollCallback?.();+ });++ /** One PageUp, and it is the first event the handler sees. A key press buys a+ * single resize of grace and clears no flag of its own, so if the gesture is+ * spent taking a baseline the reader is ridden straight back to the end. */+ fireEvent.keyDown(screen.getByTestId('content'), { key: 'PageUp' });+ scrollable.scrollTop = 300;+ fireEvent.scroll(scrollable);++ act(() => {+ MockResizeObserver.last()?.trigger();+ MockResizeObserver.last()?.trigger();+ });++ expect(scrollable.scrollTop).toBe(300);+ });+it('does not follow the next resize after user interaction inside message content', () => {renderScrolling();@@ -253,6 +333,38 @@ describe('useMessageScrolling resize reconciliation', () => {expect(mockScrollToBottom).not.toHaveBeenCalled();});+ /**+ * One interaction rarely settles in a single frame: expanding a tool result renders+ * the container, then its contents arrive and grow it again. Only the first resize+ * was credited to the interaction, so the second read the reader as still riding the+ * stream and put them back on the bottom they had just deliberately left.+ */+ it('keeps an interaction that settles over several resizes from re-pinning the reader', () => {+ renderScrolling();++ const scrollable = screen.getByTestId('scrollable');+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });+ scrollable.scrollTop = 800;++ fireEvent.pointerDown(screen.getByTestId('content'));++ /** The expansion renders, which is the resize the interaction is credited with. */+ Object.defineProperty(scrollable, 'scrollHeight', { value: 2000, configurable: true });+ act(() => {+ MockResizeObserver.last()?.trigger();+ });+ expect(scrollable.scrollTop).toBe(800);++ /** Its contents then load. This belongs to the same interaction, not to the stream. */+ Object.defineProperty(scrollable, 'scrollHeight', { value: 2600, configurable: true });+ act(() => {+ MockResizeObserver.last()?.trigger();+ });++ expect(scrollable.scrollTop).toBe(800);+ });+it('clamps the scroll position back to content after a resize shrink', () => {renderScrolling({ contextOverrides: { abortScroll: true } });@@ -269,14 +381,202 @@ describe('useMessageScrolling resize reconciliation', () => {expect(mockScrollToBottom).not.toHaveBeenCalled();});+ /**+ * Sending arms a smooth glide down to the newest word, and the landing re-pins the+ * thread to the bottom. The landing is scheduled for the whole glide window, so a+ * reader who changes their mind and heads up mid-flight was pinned again anyway and+ * dragged back on the next streaming resize.+ */+ it('lets an upward gesture during the send glide beat the pending landing', () => {+ jest.useFakeTimers();+ try {+ const view = render(+ <RecoilRoot>+ <MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ const scrollable = screen.getByTestId('scrollable');+ const scrollTo = jest.fn();+ (scrollable as unknown as { scrollTo: jest.Mock }).scrollTo = scrollTo;+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });+ scrollable.scrollTop = 0;++ view.rerender(+ <RecoilRoot>+ <MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });++ /** The reader heads up while the glide is still in flight. */+ scrollable.scrollTop = 400;+ fireEvent.wheel(scrollable, { deltaY: -120 });++ act(() => {+ jest.advanceTimersByTime(glideWindow);+ });++ Object.defineProperty(scrollable, 'scrollHeight', { value: 1200, configurable: true });+ act(() => {+ MockResizeObserver.last()?.trigger();+ });++ expect(scrollable.scrollTop).toBe(400);+ } finally {+ jest.useRealTimers();+ }+ });++ /**+ * A reader who scrolls away during one answer leaves the abort flag raised, and+ * nothing lowers it until the next connection opens, which is after the send has+ * already been seen. Spending the start of the turn on that first pass left the+ * answer the reader had just asked for streaming offscreen.+ */+ it('starts the turn once a stale abort flag clears', () => {+ const view = render(+ <RecoilRoot>+ <MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ const scrollable = screen.getByTestId('scrollable');+ const scrollTo = jest.fn();+ (scrollable as unknown as { scrollTo: jest.Mock }).scrollTo = scrollTo;+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });+ scrollable.scrollTop = 0;++ /** They left the bottom during the previous answer, which is what raised it. */+ fireEvent.wheel(scrollable, { deltaY: -120 });++ view.rerender(+ <RecoilRoot>+ <MessagesViewContext.Provider+ value={createContextValue({ isSubmitting: true, abortScroll: true })}+ >+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ expect(scrollTo).not.toHaveBeenCalled();++ /** The connection opens and lowers the flag. */+ view.rerender(+ <RecoilRoot>+ <MessagesViewContext.Provider+ value={createContextValue({ isSubmitting: true, abortScroll: false })}+ >+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });+ });++ it('leaves the send glide alone while the answer streams in', () => {+ const view = render(+ <RecoilRoot>+ <MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ const scrollable = screen.getByTestId('scrollable');+ const scrollTo = jest.fn();+ (scrollable as unknown as { scrollTo: jest.Mock }).scrollTo = scrollTo;+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });+ scrollable.scrollTop = 0;++ view.rerender(+ <RecoilRoot>+ <MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });++ /** The next delta of the answer arrives while the glide is still travelling. */+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1100, configurable: true });+ view.rerender(+ <RecoilRoot>+ <MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>+ <ScrollingHarness messagesTree={[message, message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ /** A plain follow would have written scrollTop outright and killed the animation. */+ expect(scrollable.scrollTop).toBe(0);+ });++ /**+ * Following stands down for the length of the glide, so an answer that arrives+ * while it travels moves the bottom past the target the glide aimed at. Landing+ * has to close that gap, or a short response settles short of its own end.+ */+ it('catches up to the new bottom when the glide lands', () => {+ const view = render(+ <RecoilRoot>+ <MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ const scrollable = screen.getByTestId('scrollable');+ (scrollable as unknown as { scrollTo: jest.Mock }).scrollTo = jest.fn();+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });+ Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });+ scrollable.scrollTop = 0;++ view.rerender(+ <RecoilRoot>+ <MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>+ <ScrollingHarness messagesTree={[message]} />+ </MessagesViewContext.Provider>+ </RecoilRoot>,+ );++ /** The whole answer arrives before the glide reports that it landed. */+ Object.defineProperty(scrollable, 'scrollHeight', { value: 1400, configurable: true });+ act(() => {+ fireEvent(scrollable, new Event('scrollend'));+ });++ expect(scrollable.scrollTop).toBe(1200);+ });+it('does not clamp to rendered content bottom during general resize reconciliation', () => {- renderScrolling({ contextOverrides: { abortScroll: true } });+ renderScrolling();const scrollable = screen.getByTestId('scrollable');const content = screen.getByTestId('content');Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });++ /** Move away from the end so the reader is left alone, which is the state this+ * is about: reconciliation must not drag them to the rendered content bottom. */+ scrollable.scrollTop = 900;+ fireEvent.scroll(scrollable);scrollable.scrollTop = 700;+ fireEvent.scroll(scrollable);+setRect(scrollable, { top: 0, bottom: 200, height: 200 });setRect(content, { top: -700, bottom: -200, height: 500 });diff --git a/client/src/hooks/Messages/useCopyToClipboard.spec.ts b/client/src/hooks/Messages/useCopyToClipboard.spec.tsindex 6e0844100a..b5059a4fd1 100644--- a/client/src/hooks/Messages/useCopyToClipboard.spec.ts+++ b/client/src/hooks/Messages/useCopyToClipboard.spec.ts@@ -1,6 +1,6 @@-import { renderHook, act } from '@testing-library/react';import copy from 'copy-to-clipboard';import { ContentTypes } from 'librechat-data-provider';+import { renderHook, act } from '@testing-library/react';import type {SearchResultData,ProcessedOrganic,@@ -64,6 +64,35 @@ describe('useCopyToClipboard', () => {});});+ it('copies errors and tool input and output with surrounding text', () => {+ const content = [+ { type: ContentTypes.TEXT, text: 'I checked the deployment.' },+ {+ type: ContentTypes.TOOL_CALL,+ tool_call: {+ type: 'tool_call',+ name: 'get_deployment',+ args: '{"service":"web"}',+ output: '{"status":"failed"}',+ },+ },+ { type: ContentTypes.ERROR, error: 'Deployment lookup failed' },+ ] as TMessageContentParts[];++ const { result } = renderHook(() => useCopyToClipboard({ content }));++ act(() => {+ result.current(mockSetIsCopied);+ });++ const copiedText = mockCopy.mock.calls[0]?.[0];+ expect(copiedText).toContain('I checked the deployment.');+ expect(copiedText).toContain('get_deployment');+ expect(copiedText).toContain('service');+ expect(copiedText).toContain('status');+ expect(copiedText).toContain('Deployment lookup failed');+ });+it('should reset isCopied after timeout', () => {const { result } = renderHook(() =>useCopyToClipboard({diff --git a/client/src/hooks/Messages/useCopyToClipboard.ts b/client/src/hooks/Messages/useCopyToClipboard.tsindex f827d95200..c0cd2aebbd 100644--- a/client/src/hooks/Messages/useCopyToClipboard.ts+++ b/client/src/hooks/Messages/useCopyToClipboard.ts@@ -1,7 +1,8 @@import { useCallback, useEffect, useRef } from 'react';import copy from 'copy-to-clipboard';-import { ContentTypes, SearchResultData } from 'librechat-data-provider';+import { SearchResultData } from 'librechat-data-provider';import type { TMessage } from 'librechat-data-provider';+import type { LocalizeFunction } from '~/common';import {SPAN_REGEX,CLEANUP_REGEX,@@ -9,6 +10,8 @@ import {STANDALONE_PATTERN,INVALID_CITATION_REGEX,} from '~/utils/citations';+import { formatMessageContent } from '~/hooks/Conversations/format';+import useLocalize from '~/hooks/useLocalize';type Source = {link: string;@@ -27,6 +30,35 @@ const refTypeMap: Record<string, string> = {video: 'videos',};+export function serializeMessageForClipboard({+ text,+ content,+ localize,+}: Partial<Pick<TMessage, 'text' | 'content'>> & { localize: LocalizeFunction }): string {+ if (!Array.isArray(content) || content.length === 0) {+ return text ?? '';+ }++ return content+ .filter((part) => part != null)+ .map((part) => {+ const formatted = formatMessageContent({+ sender: '',+ content: part,+ format: 'text',+ localize,+ });+ if (formatted.length === 0) {+ return '';+ }++ const [label, value] = formatted;+ return label ? `${label}:\n${value}` : value;+ })+ .filter((value) => value.trim().length > 0)+ .join('\n');+}+export default function useCopyToClipboard({text,content,@@ -34,6 +66,7 @@ export default function useCopyToClipboard({}: Partial<Pick<TMessage, 'text' | 'content'>> & {searchResults?: { [key: string]: SearchResultData };}) {+ const localize = useLocalize();const copyTimeoutRef = useRef<NodeJS.Timeout | null>(null);useEffect(() => {@@ -51,17 +84,7 @@ export default function useCopyToClipboard({}setIsCopied(true);- // Get the message text from content or text- let messageText = text ?? '';- if (content) {- messageText = content.reduce((acc, curr, i) => {- if (curr.type === ContentTypes.TEXT) {- const text = typeof curr.text === 'string' ? curr.text : (curr.text?.value ?? '');- return acc + text + (i === content.length - 1 ? '' : '\n');- }- return acc;- }, '');- }+ const messageText = serializeMessageForClipboard({ text, content, localize });// Early return if no search dataif (!searchResults || Object.keys(searchResults).length === 0) {@@ -100,7 +123,7 @@ export default function useCopyToClipboard({setIsCopied(false);}, 3000);},- [text, content, searchResults],+ [text, content, searchResults, localize],);return copyToClipboard;diff --git a/client/src/hooks/Messages/useMessageScrolling.ts b/client/src/hooks/Messages/useMessageScrolling.tsindex b15b4aff51..03cce40878 100644--- a/client/src/hooks/Messages/useMessageScrolling.ts+++ b/client/src/hooks/Messages/useMessageScrolling.ts@@ -9,6 +9,22 @@ import store from '~/store';const resizeFollowThreshold = 120;+/** How long a glide is given to land before per-frame following resumes. */+const glideTimeout = 700;++/** Arriving counts from further out than leaving does, because while an answer+ * streams the end is a moving target: it recedes between the reader's last+ * wheel tick and the frame that measures it, so someone scrolling all the way+ * down still lands tens of pixels short. Judging arrival as tightly as+ * departure means they can never quite catch it. */+const attachThreshold = 150;+const detachThreshold = 24;++const prefersReducedMotion = () =>+ typeof window !== 'undefined' &&+ typeof window.matchMedia === 'function' &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;+export default function useMessageScrolling(messagesTree?: TMessage[] | null) {const autoScroll = useRecoilValue(store.autoScroll);@@ -16,6 +32,21 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {const contentRef = useRef<HTMLDivElement | null>(null);const messagesEndRef = useRef<HTMLDivElement | null>(null);const isNearBottomRef = useRef(true);+ /** The single authority for whether the thread is riding the stream. Driven only+ * by what the reader does, never by the observer, whose zero-height sentinel+ * flickers as content grows and was the source of the attach/detach churn. */+ const isStuckRef = useRef(true);+ const isGlidingRef = useRef(false);+ /** Raised wherever a reader gesture lets go of the bottom, so a glide already in+ * flight knows not to re-pin them when it lands. */+ const glideInterruptedRef = useRef(false);+ const glideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ /** Seeded below zero rather than at 0 so the first event after mount is read as+ * "no previous sample" instead of as a jump down from the top. Every+ * programmatic move writes the position it left the thread at, so this stands+ * only until something has actually placed the thread. */+ const lastScrollTopRef = useRef(-1);+ const wasSubmittingRef = useRef(false);const suppressNextResizeFollowRef = useRef(false);const { conversation, conversationId } = useMessagesConversation();const { setAbortScroll, isSubmitting, abortScroll } = useMessagesSubmission();@@ -29,20 +60,95 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {return distance <= resizeFollowThreshold;}, []);- /** The scroll-to-bottom button owns the IntersectionObserver (so its- * visibility state never re-renders the message tree host) and reports- * intersection back through this callback. */+ /** The scroll-to-bottom button owns the IntersectionObserver (so its visibility+ * state never re-renders the message tree host) and reports intersection back+ * through this callback.+ *+ * It reports only. The sentinel it watches has no height and is observed at a+ * 0.85 threshold, a ratio a zero-area box cannot reach, so it flickers while an+ * answer streams. Letting it decide whether to ride the stream is what made the+ * thread attach and detach on its own.+ */const handleNearBottomChange = useCallback((isNearBottom: boolean) => {isNearBottomRef.current = isNearBottom;}, []);+ const distanceFromEnd = useCallback(() => {+ const scrollEl = scrollableRef.current;+ if (!scrollEl) {+ return 0;+ }+ return scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight;+ }, []);++ /** Direction is judged against the last sample, so anything that moves the thread+ * on the reader's behalf has to leave one behind. A thread opening at its end, or+ * ridden down by the stream, is placed without the reader touching it; with no+ * record of where it was put, their first gesture is spent taking the baseline+ * instead of being obeyed, and a keyboard scroll away from the end is lost. */+ const rememberScrollPosition = useCallback(() => {+ const scrollEl = scrollableRef.current;+ if (!scrollEl) {+ return;+ }+ lastScrollTopRef.current = scrollEl.scrollTop;+ }, []);+const debouncedHandleScroll = useCallback(() => {+ const scrollEl = scrollableRef.current;isNearBottomRef.current = getIsNearBottom();- }, [getIsNearBottom]);+ if (!scrollEl) {+ return;+ }++ /** Direction comes from where the thread actually moved, which covers the+ * wheel, a trackpad and a dragged scrollbar alike. */+ const top = scrollEl.scrollTop;+ const previousTop = lastScrollTopRef.current;+ lastScrollTopRef.current = top;++ /** A thread opens already scrolled to its end, so the first event carries a+ * large positive `scrollTop` with nothing to compare it against. Measuring it+ * from 0 calls it downward, and the gesture that produced it, a reader pushing+ * up and away from the stream, is swallowed: a single PageUp reads as an+ * arrival and leaves the thread riding the answer. Take this one as the+ * baseline and judge direction from the next. */+ if (previousTop < 0) {+ return;+ }++ const movingDown = top >= previousTop;+ const distance = distanceFromEnd();++ /** Arriving is judged here rather than on the wheel tick that started it: the+ * browser animates wheel scrolling, so at tick time the thread is still far+ * short of where that tick is taking it, and reading the distance then calls+ * a gesture that lands on the end a miss. */+ if (movingDown) {+ if (distance <= attachThreshold) {+ isStuckRef.current = true;+ /** Cleared unconditionally rather than on a read of the current value.+ * `Message` raises this on every wheel tick, downward ones included, so+ * it is set again on the way here; and the value this closure can see is+ * a render behind, so a conditional clear loses the race and leaves the+ * ride vetoed for the rest of the answer. Recoil no-ops an unchanged+ * write, so repeating it costs nothing. */+ setAbortScroll(false);+ }+ return;+ }++ if (distance > detachThreshold) {+ isStuckRef.current = false;+ glideInterruptedRef.current = true;+ }+ }, [distanceFromEnd, getIsNearBottom, setAbortScroll]);const scrollCallback = () => {reconcileMessageContentLayout(scrollableRef.current);isNearBottomRef.current = true;+ isStuckRef.current = true;+ rememberScrollPosition();};const { scrollToRef: scrollToBottom, handleSmoothToRef } = useScrollToRef({@@ -54,6 +160,74 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {},});+ /**+ * Ride the bottom of the thread.+ *+ * Written straight to `scrollTop` rather than routed through the throttled+ * `scrollIntoView` helper: an answer arrives a few pixels at a time, so+ * correcting on every frame reads as the text simply flowing upward, while+ * correcting every 145ms reads as a thread that lurches.+ *+ * The glide is for distance only, when a send has to travel from wherever the+ * reader was down to the newest word. Following while one is in flight would+ * cancel it on the first frame.+ */+ const followBottom = useCallback((behavior: ScrollBehavior = 'auto') => {+ const scrollEl = scrollableRef.current;+ if (!scrollEl) {+ return;+ }+ const target = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);+ if (Math.abs(scrollEl.scrollTop - target) < 1) {+ return;+ }++ if (behavior !== 'smooth' || prefersReducedMotion()) {+ scrollEl.scrollTop = target;+ /** Riding the bottom re-affirms that we are on it. The throttled helper this+ * replaced did the same through its callback, and without it a single+ * under-reported intersection ends the ride for the rest of the turn. */+ isNearBottomRef.current = true;+ isStuckRef.current = true;+ lastScrollTopRef.current = target;+ return;+ }++ isGlidingRef.current = true;+ glideInterruptedRef.current = false;+ if (glideTimerRef.current != null) {+ clearTimeout(glideTimerRef.current);+ }+ const land = () => {+ isGlidingRef.current = false;+ scrollEl.removeEventListener('scrollend', land);+ if (glideTimerRef.current != null) {+ clearTimeout(glideTimerRef.current);+ glideTimerRef.current = null;+ }+ /** Scrolling up during the glide is the reader taking over. Re-pinning them+ * here would hand the thread straight back to the stream on the next resize,+ * and the timeout fires for the whole glide window even once the animation+ * has visibly settled, so the gesture has to win outright. */+ if (glideInterruptedRef.current) {+ return;+ }+ isNearBottomRef.current = true;+ isStuckRef.current = true;+ /** Following stands down for the whole trip, so anything that streamed in+ * meanwhile moved the bottom past the target this glide aimed at. Close that+ * gap on arrival, or a short answer settles a few lines short of its end. */+ const settled = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);+ if (Math.abs(scrollEl.scrollTop - settled) >= 1) {+ scrollEl.scrollTop = settled;+ }+ lastScrollTopRef.current = scrollEl.scrollTop;+ };+ scrollEl.addEventListener('scrollend', land, { once: true });+ glideTimerRef.current = setTimeout(land, glideTimeout);+ scrollEl.scrollTo({ top: target, behavior: 'smooth' });+ }, []);+const clampScrollToContent = useCallback(() => {const scrollEl = scrollableRef.current;if (!scrollEl) {@@ -79,14 +253,35 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {if (suppressNextResizeFollowRef.current) {suppressNextResizeFollowRef.current = false;isNearBottomRef.current = getIsNearBottom();+ /** An interaction rarely settles in one frame: a tool result expands, then its+ * contents arrive and grow it again. Only the first resize is credited to the+ * gesture, so letting go of the ride has to happen here. Leaving it to the+ * resize that follows means reading a reader who has just been pushed far up+ * their own thread as still riding the stream, and handing them back to the+ * bottom they deliberately left. Where the interaction actually left them+ * decides it, so one that kept them on the end keeps streaming. */+ isStuckRef.current = isNearBottomRef.current;return;}- if (shouldFollowResize && isSubmitting && abortScroll !== true && isNearBottomRef.current) {- scrollToBottom?.();+ /** A glide already on its way to the bottom is heading exactly where this+ * would put us, and touching the position would cancel it. */+ if (isGlidingRef.current) {+ return;+ }++ /** Deliberately not gated on `abortScroll`. `useMessageProcess` raises that on+ * any wheel at all, downward ones included, through a 500ms throttle whose+ * trailing call lands after the gesture has ended: no clear timed to the+ * gesture can outlive it, which is why scrolling down to the newest word+ * could never resume the ride while the button, which touches no wheel,+ * always could. Whether the reader is riding the stream is answered here by+ * where they actually are and which way they were going. */+ if (shouldFollowResize && isSubmitting && isStuckRef.current) {+ followBottom();}},- [abortScroll, clampScrollToContent, getIsNearBottom, isSubmitting, scrollToBottom],+ [clampScrollToContent, followBottom, getIsNearBottom, isSubmitting],);useEffect(() => {@@ -118,6 +313,59 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {};}, []);+ useEffect(() => {+ const scrollEl = scrollableRef.current;+ if (!scrollEl || typeof window === 'undefined') {+ return;+ }++ /** Direction decides, not position. Heading up lets go at once and stays let+ * go, however close to the end the reader still is; anything position-based+ * drags them back before they have cleared the band, which reads as the+ * thread refusing to be scrolled.+ *+ * Heading down only re-attaches on arrival at the end.+ *+ * `Message` aborts auto-scroll on `wheel` alone, and a tick against the end+ * moves nothing and so fires no `scroll`, leaving that flag set with nothing+ * to clear it. Clearing it on arrival is what lets the ride resume; the+ * button escaped the problem only by never touching the wheel. */+ /** An upward tick releases immediately, without waiting to see where it lands.+ * Re-attaching is left entirely to arrival, handled on scroll.+ *+ * A downward tick clears the abort flag outright. `Message` raises it on any+ * wheel at all, and a tick against the end moves nothing, so it fires no+ * `scroll` for the arrival handler to answer: the last tick of scrolling down+ * to the newest word leaves the ride vetoed with nothing left to lift it.+ * Scrolling down is never an intent to abandon the stream. */+ const onWheel = (event: WheelEvent) => {+ if (event.deltaY < 0) {+ isStuckRef.current = false;+ glideInterruptedRef.current = true;+ return;+ }+ /** Next frame, not now: React binds `Message`'s handler at the root, above+ * this container, so it runs after this one and would put the flag straight+ * back. Clearing once the event has finished dispatching is what makes it+ * stick. */+ window.requestAnimationFrame(() => setAbortScroll(false));+ };++ scrollEl.addEventListener('wheel', onWheel, { passive: true });+ return () => {+ scrollEl.removeEventListener('wheel', onWheel);+ };+ }, [setAbortScroll]);++ useEffect(+ () => () => {+ if (glideTimerRef.current != null) {+ clearTimeout(glideTimerRef.current);+ }+ },+ [],+ );+useEffect(() => {if (!messagesTree || messagesTree.length === 0) {return;@@ -127,8 +375,33 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {return;}- if (isSubmitting && scrollToBottom && abortScroll !== true) {- scrollToBottom();+ const startedSubmitting = isSubmitting && !wasSubmittingRef.current;++ if (!isSubmitting) {+ wasSubmittingRef.current = false;+ }++ /** The start of a turn is spent only once it can be acted on. A reader who+ * scrolled away during the last answer leaves the abort flag raised, and+ * nothing lowers it until the next connection opens, which is after this effect+ * has already seen the send. Marking the turn as started on that first pass+ * spent it against a closed gate: by the time the flag cleared there was no+ * start left to honour and the reader was still detached, so the answer they+ * had just asked for streamed on offscreen. */+ if (isSubmitting && abortScroll !== true) {+ wasSubmittingRef.current = true;+ /** Sending re-attaches: the reader asked for this answer, so take them to it.+ * The one long trip of a turn, and the only one worth animating. */+ if (startedSubmitting) {+ isNearBottomRef.current = true;+ isStuckRef.current = true;+ followBottom('smooth');+ } else if (isStuckRef.current && !isGlidingRef.current) {+ /** Every delta of the answer reruns this effect, and a plain follow writes+ * scrollTop outright, which cancels an animation on its first frame. The+ * glide is left to finish the trip it started. */+ followBottom();+ }}return () => {@@ -136,7 +409,7 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {scrollToBottom && scrollToBottom.cancel();}};- }, [isSubmitting, messagesTree, scrollToBottom, abortScroll]);+ }, [isSubmitting, messagesTree, scrollToBottom, abortScroll, followBottom]);useEffect(() => {if (!messagesEndRef.current || !scrollableRef.current) {diff --git a/client/src/hooks/useGenerationsByLatest.ts b/client/src/hooks/useGenerationsByLatest.tsindex ddedc3ec15..88c02511f7 100644--- a/client/src/hooks/useGenerationsByLatest.ts+++ b/client/src/hooks/useGenerationsByLatest.ts@@ -40,6 +40,7 @@ export default function useGenerationsByLatest({finish_reason &&finish_reason !== 'stop' &&!isEditing &&+ !isSubmitting &&!searchResult &&isEditableEndpoint;@@ -58,8 +59,11 @@ export default function useGenerationsByLatest({const regenerateEnabled =!isCreatedByUser && !searchResult && !isEditing && !isSubmitting && branchingSupported;+ const isActiveStreamingMessage =+ isSubmitting && (latestMessageId == null || messageId === latestMessageId);+const hideEditButton =- isSubmitting ||+ isActiveStreamingMessage ||error ||searchResult ||!branchingSupported ||@@ -71,6 +75,7 @@ export default function useGenerationsByLatest({forkingSupported,continueSupported,regenerateEnabled,+ isActiveStreamingMessage,isEditableEndpoint,hideEditButton,};diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 0a47014d49..e816dd43b9 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1536,6 +1536,7 @@"com_ui_message_nav_go_to_user": "Go to user message: {{0}}","com_ui_message_nav_next": "Navigate to next message","com_ui_message_nav_previous": "Navigate to previous message",+ "com_ui_message_part_empty": "Message content cannot be empty.","com_ui_method": "Method","com_ui_microphone_unavailable": "Microphone is not available","com_ui_min_tags": "Cannot remove more values, a minimum of {{0}} are required.",@@ -1788,9 +1789,10 @@"com_ui_sandbox_starting": "Starting sandbox environment","com_ui_save": "Save","com_ui_save_badge_changes": "Save badge changes?",+ "com_ui_save_before_rerun": "Rerunning applies one edited section at a time. Save to keep all of these changes.","com_ui_save_key_error": "Failed to save API key. Please try again.","com_ui_save_key_success": "API key saved successfully",- "com_ui_save_submit": "Save & Submit",+ "com_ui_save_message_error": "The message could not be saved. Your changes are still in the editor.","com_ui_saved": "Saved!","com_ui_saving": "Saving...","com_ui_schema": "Schema",@@ -2139,8 +2141,10 @@"com_ui_unpin_error": "Failed to unpin conversation","com_ui_unset": "Unset","com_ui_untitled": "Untitled",+ "com_ui_unsaved_changes": "Unsaved changes","com_ui_update": "Update","com_ui_update_mcp_server": "Update MCP server",+ "com_ui_update_rerun": "Update & rerun","com_ui_update_shared_link": "Update link","com_ui_update_shared_link_confirm_description": "This publishes the latest messages and your current file-sharing choice to the existing link. The URL stays the same, and anyone with access can see the updated snapshot.","com_ui_update_shared_link_confirm_title": "Update shared link?",diff --git a/client/src/style.css b/client/src/style.cssindex aa0fdb90a3..bb45a39c03 100644--- a/client/src/style.css+++ b/client/src/style.css@@ -2098,9 +2098,10 @@ html {transform-origin: 50% 50%;}-.message-content {+.message-content,+.message-editor-text {font-size: var(--markdown-font-size, var(--font-size-base));- line-height: 1.4;+ line-height: 1.6;}.message-content pre code {diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.jsindex 2e759e91fc..30528fc540 100644--- a/e2e/setup/fake-model.js+++ b/e2e/setup/fake-model.js@@ -25,6 +25,7 @@ const ASSERT_PROVIDER_FILE_MARKER = 'E2E_ASSERT_PROVIDER_FILE:';const ASSERT_AGENT_CONTEXT_MARKER = 'E2E_ASSERT_AGENT_CONTEXT:';const ASSERT_QUOTE_MARKER = 'E2E_ASSERT_QUOTE:';const REPLY_MARKER = 'E2E_REPLY:';+const THINK_REPLY_MARKER = 'E2E_THINK_REPLY:';const COUNTED_REPLY_MARKER = 'E2E_COUNTED_REPLY:';const ORDERED_REPLY_MARKER = 'E2E_ORDERED_REPLY:';const SLOW_REPLY_MARKER = 'E2E_SLOW_REPLY:';@@ -488,6 +489,15 @@ function replyResponses(text) {};}+ const thinkName = getMarkerValue(text, THINK_REPLY_MARKER);+ if (thinkName) {+ /** The `<think>` tags are parsed downstream by the agents stream pipeline, so this+ * yields a reasoning part followed by a text part: two separately editable parts. */+ return {+ responses: [`<think>E2E reasoning ${thinkName}</think>\n\nE2E reply ${thinkName}`],+ };+ }+const countedName = getMarkerValue(text, COUNTED_REPLY_MARKER);if (countedName) {const count = (countedReplies.get(countedName) ?? 0) + 1;diff --git a/e2e/specs/messages.spec.ts b/e2e/specs/messages.spec.tsindex 91131701c8..f986d1f0e4 100644--- a/e2e/specs/messages.spec.ts+++ b/e2e/specs/messages.spec.ts@@ -100,7 +100,7 @@ test.describe('Messaging suite', () => {await page.getByRole('button', { name: 'edit' }).click();const editResponsePromise = [page.waitForResponse(waitForServerStream),- await page.getByRole('button', { name: 'Save & Submit' }).click(),+ await page.getByRole('button', { name: 'Update & rerun' }).click(),];const [editResponse] = (await Promise.all(editResponsePromise)) as [Response];diff --git a/e2e/specs/mock/helpers.ts b/e2e/specs/mock/helpers.tsindex c4fba0bc2d..fa08d43bc3 100644--- a/e2e/specs/mock/helpers.ts+++ b/e2e/specs/mock/helpers.ts@@ -97,6 +97,10 @@ export const messagesView = (page: Page) => page.getByTestId('messages-view');export const replyPrompt = (label: string) => `E2E_REPLY:${label}`;export const replyText = (label: string) => `E2E reply ${label}`;+/** Same, for a reply that streams a reasoning part ahead of its text part. */+export const thinkPrompt = (label: string) => `E2E_THINK_REPLY:${label}`;+export const thinkText = (label: string) => `E2E reasoning ${label}`;+/** The mock reply as rendered in the conversation, scoped to the messages view. */export function mockReply(page: Page) {return messagesView(page).getByText(new RegExp(MOCK_REPLY_TEXT, 'i'));diff --git a/e2e/specs/mock/hover-actions.spec.ts b/e2e/specs/mock/hover-actions.spec.tsindex a55e7915ae..4a53bd51d8 100644--- a/e2e/specs/mock/hover-actions.spec.ts+++ b/e2e/specs/mock/hover-actions.spec.ts@@ -6,16 +6,18 @@ import {messagesView,selectMockEndpoint,sendMessage,+ sendMessageAndWaitForCompletion,} from './helpers';/**- * Regression guard for the edit action leaking through mid-stream.+ * Regression guard for the actions offered on a half-written response.*- * The unit spec can only assert class names: jsdom applies no stylesheet, so it- * cannot see that the shared Button's `disabled:opacity-50` (specificity 0,2,0)- * outranks a plain `opacity-0` (0,1,0) and repaints the hidden pencil at half- * opacity. Only a real browser resolves that cascade, which is why this lives- * here rather than in Jest.+ * Edit and fork cannot act on a message that is still streaming, so the toolbar+ * omits them outright rather than rendering them disabled: the shared Button's+ * `disabled:opacity-50` (specificity 0,2,0) outranks a plain `opacity-0` (0,1,0)+ * and would repaint a dimmed ghost of the hidden action. Asserting absence is+ * what makes that ghost unrepresentable, and jsdom resolves no stylesheet, so+ * the guard lives here rather than in Jest.*/const uniqueLabel = (prefix: string) =>@@ -27,10 +29,16 @@ const userTurn = (page: Page) =>.filter({ has: page.locator('.user-turn') }).last();+const assistantTurn = (page: Page) =>+ messagesView(page)+ .locator('.message-render')+ .filter({ has: page.locator('.agent-turn') })+ .last();+const stopButton = (page: Page) => page.getByRole('button', { name: 'Stop generating' });test.describe('message hover actions', () => {- test('keeps the edit action fully hidden while a generation streams', async ({ page }) => {+ test('withholds inapplicable actions while a generation streams', async ({ page }) => {test.setTimeout(120000);const label = uniqueLabel('hover-edit');@@ -41,26 +49,137 @@ test.describe('message hover actions', () => {expect(run.ok()).toBeTruthy();await expect(messagesView(page).getByText('chunk-010')).toBeVisible({ timeout: 15000 });- const row = userTurn(page);- const editButton = row.locator('button[id^="edit-"]');- const copyButton = row.getByRole('button', { name: 'Copy to clipboard' });-- await row.hover();+ const streaming = assistantTurn(page);+ const streamingEdit = streaming.locator('button[id^="edit-"]');+ const streamingFork = streaming.getByRole('button', { name: 'Open Fork Menu' });- /** Pin the window: if the stream already settled, the edit assertion below+ /** Pin the window: if the stream already settled, every assertion below* would be checking the wrong state and pass for the wrong reason. */await expect(stopButton(page)).toBeVisible();- /** The sibling action proves the row is genuinely hovered — without it a- * broken hover would make the edit assertion pass for the wrong reason. */- await expect(copyButton).toHaveCSS('opacity', '1');- await expect(editButton).toHaveCSS('opacity', '0');- await expect(editButton).toBeDisabled();+ /** Copying half a sentence is never what the reader wants, so the response+ * offers nothing at all until it settles. */+ const streamingCopy = streaming.getByRole('button', { name: 'Copy to clipboard' });+ await expect(streamingCopy).toHaveCount(0);+ await expect(streamingEdit).toHaveCount(0);+ await expect(streamingFork).toHaveCount(0);++ /** The settled turn above carries the positive control: the toolbar system is+ * mounted and working, so the absences above read as "withheld" rather than+ * "nothing rendered yet". */+ await expect(userTurn(page).locator('button[id^="edit-"]')).toBeEnabled();- /** ...and the affordance must come back, or "hidden" would just be "gone". */+ /** ...and the response earns them back, or "withheld" would just be "gone". */await expect(stopButton(page)).toBeHidden({ timeout: 60000 });+ await expect(streamingCopy).toBeEnabled();+ await expect(streamingEdit).toBeEnabled();+ await expect(streamingFork).toBeEnabled();+ });++ /**+ * A trigger whose surface is open must survive the pointer leaving the row,+ * or the editor and the fork popover end up anchored to an invisible button.+ *+ * Both assertions deliberately move focus out of the row first. `.message-render`+ * carries the `group`, so an editor focused inside it satisfies+ * `group-focus-within:opacity-100` on its own: asserting while the textarea still+ * holds focus passes whether or not the active state is honoured.+ */+ test('keeps a triggered action visible once the pointer leaves the row', async ({ page }) => {+ test.setTimeout(120000);++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);++ /** A second turn demotes the first row out of `isLast`, the only state that+ * fades the actions at all. */+ expect((await sendMessageAndWaitForCompletion(page, 'First turn.')).ok()).toBeTruthy();+ expect((await sendMessageAndWaitForCompletion(page, 'Second turn.')).ok()).toBeTruthy();++ const row = messagesView(page)+ .locator('.message-render')+ .filter({ has: page.locator('.user-turn') })+ .first();+ const editButton = row.locator('button[id^="edit-"]');+ const forkButton = row.getByRole('button', { name: 'Open Fork Menu' });++ /** Baseline: an idle action really does fade, so the assertions below are+ * measuring the active state rather than a row that never hides anything. */await row.hover();await expect(editButton).toBeEnabled();+ await page.mouse.move(0, 0);+ await expect(editButton).toHaveCSS('opacity', '0');++ await row.hover();+ await editButton.click();+ await expect(row.getByTestId('message-text-editor')).toBeVisible();+ await page.locator('body').click({ position: { x: 5, y: 5 } });+ await page.mouse.move(0, 0);+ await expect(row.getByTestId('message-text-editor')).toBeVisible();await expect(editButton).toHaveCSS('opacity', '1');++ /** Escape only lands while the textarea holds focus, and the pointer left the+ * row several steps ago, so close the editor through its own control. */+ await row.hover();+ await row.getByRole('button', { name: 'Cancel' }).click();+ await expect(row.getByTestId('message-text-editor')).toHaveCount(0);+ await page.mouse.move(0, 0);+ await expect(forkButton).toHaveCSS('opacity', '0');++ /** The fork popover is portalled, so the row holds no focus while it is open. */+ await row.hover();+ await forkButton.click();+ await page.mouse.move(0, 0);+ await expect(forkButton).toHaveCSS('opacity', '1');+ });++ /**+ * Holding only the trigger open leaves the rest of the toolbar faded, so the row+ * reads as a single floating button while its surface is open. Any active action+ * keeps every sibling opaque.+ */+ test('keeps the whole toolbar visible while one action is open', async ({ page }) => {+ test.setTimeout(120000);++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);++ expect((await sendMessageAndWaitForCompletion(page, 'First turn.')).ok()).toBeTruthy();+ expect((await sendMessageAndWaitForCompletion(page, 'Second turn.')).ok()).toBeTruthy();++ const row = messagesView(page)+ .locator('.message-render')+ .filter({ has: page.locator('.user-turn') })+ .first();+ const editButton = row.locator('button[id^="edit-"]');+ const forkButton = row.getByRole('button', { name: 'Open Fork Menu' });+ const copyButton = row.getByRole('button', { name: 'Copy to clipboard' });++ await row.hover();+ await expect(editButton).toBeEnabled();+ await page.mouse.move(0, 0);+ await expect(copyButton).toHaveCSS('opacity', '0');+ await expect(forkButton).toHaveCSS('opacity', '0');++ await row.hover();+ await forkButton.click();+ await page.mouse.move(0, 0);++ await expect(forkButton).toHaveCSS('opacity', '1');+ await expect(copyButton).toHaveCSS('opacity', '1');+ await expect(editButton).toHaveCSS('opacity', '1');++ /** Closing by Escape rather than the trigger is the path that used to strand the+ * fork button in its active state, which would now pin the whole toolbar open. */+ /** Closing by Escape rather than the trigger is the path that used to strand the+ * fork button in its active state, which would now pin the whole toolbar open.+ * Escape hands focus back to the trigger, so drop it before measuring the fade+ * or `group-focus-within` keeps the row lit on its own. */+ await page.keyboard.press('Escape');+ await expect(page.locator('.popover-animate')).toHaveCount(0);+ await page.locator('body').click({ position: { x: 5, y: 5 } });+ await page.mouse.move(0, 0);+ await expect(copyButton).toHaveCSS('opacity', '0');+ await expect(forkButton).toHaveCSS('opacity', '0');});});diff --git a/e2e/specs/mock/message-edit-layout.spec.ts b/e2e/specs/mock/message-edit-layout.spec.tsnew file mode 100644index 0000000000..9331c89b66--- /dev/null+++ b/e2e/specs/mock/message-edit-layout.spec.ts@@ -0,0 +1,127 @@+import { expect, test } from '@playwright/test';+import type { Page } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ messagesView,+ replyText,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+ thinkPrompt,+ thinkText,+} from './helpers';++/** The edit surface reports "Unsaved changes" and, for a multi-part response, "Save these+ * edits first, then rerun the response." Both share the footer's status slot so that+ * neither can add a row and push the rest of the conversation down while typing. */++const EDIT_SECTION = 'section[aria-label="Edit message"]';++const editorSection = (page: Page) => page.locator(EDIT_SECTION);++type EditMetrics = {+ footer: number;+ section: number;+ status: string;+};++async function measureEditor(page: Page): Promise<EditMetrics> {+ return page.evaluate((selector) => {+ const section = document.querySelector(selector);+ if (!section) {+ throw new Error('edit section not found');+ }+ const footer = section.querySelector('footer');+ if (!footer) {+ throw new Error('edit footer not found');+ }+ const status = footer.querySelector('span');+ return {+ footer: Math.round(footer.getBoundingClientRect().height),+ section: Math.round(section.getBoundingClientRect().height),+ status: status ? status.textContent.trim() : '',+ };+ }, EDIT_SECTION);+}++async function openChat(page: Page) {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+}++async function startEditing(page: Page, row: ReturnType<Page['locator']>) {+ await row.hover();+ const editButton = row.locator('button[id^="edit-"]').first();+ await expect(editButton).toBeEnabled();+ await editButton.click();+ await expect(editorSection(page)).toBeVisible();+ await page.mouse.move(0, 0);+}++test.describe('message edit layout stability', () => {+ test('typing in a user message editor does not resize the row', async ({ page }) => {+ await openChat(page);+ const response = await sendMessageAndWaitForCompletion(page, 'E2E_REPLY:edit-layout-user');+ expect(response.ok()).toBeTruthy();++ const row = messagesView(page)+ .locator('.message-render')+ .filter({ has: page.locator('.user-turn') })+ .last();+ await startEditing(page, row);++ const clean = await measureEditor(page);+ expect(clean.status).toBe('');++ const editor = row.getByTestId('message-text-editor');+ await editor.click();+ await editor.press('End');+ await editor.type(' plus an edit');++ await expect.poll(async () => (await measureEditor(page)).status).toBe('Unsaved changes');++ const dirty = await measureEditor(page);+ expect(dirty.footer).toBe(clean.footer);+ expect(dirty.section).toBe(clean.section);+ });++ test('the rerun hint shares the status slot without adding a row', async ({ page }) => {+ test.setTimeout(120000);+ await openChat(page);+ const label = 'edit-layout-parts';+ const response = await sendMessageAndWaitForCompletion(page, thinkPrompt(label));+ expect(response.ok()).toBeTruthy();+ await expect(messagesView(page).getByText(replyText(label))).toBeVisible();++ const row = messagesView(page)+ .locator('.message-render')+ .filter({ has: page.locator('.agent-turn') })+ .last();+ await startEditing(page, row);++ const editors = editorSection(page).getByRole('textbox');+ await expect(editors).toHaveCount(2);++ const clean = await measureEditor(page);+ expect(clean.status).toBe('');++ /** One changed part is just an unsaved edit; the second is what gates rerun. */+ await editors.nth(0).fill(`${thinkText(label)} revised`);+ await expect.poll(async () => (await measureEditor(page)).status).toBe('Unsaved changes');+ const single = await measureEditor(page);++ await editors.nth(1).fill(`${replyText(label)} revised`);+ await expect+ .poll(async () => (await measureEditor(page)).status)+ .toBe('Rerunning applies one edited section at a time. Save to keep all of these changes.');+ const both = await measureEditor(page);++ expect(single.footer).toBe(clean.footer);+ expect(both.footer).toBe(clean.footer);+ expect(both.section).toBe(single.section);++ await expect(+ editorSection(page).getByRole('button', { name: 'Update & rerun' }),+ ).toBeDisabled();+ });+});diff --git a/e2e/specs/mock/message-tree.spec.ts b/e2e/specs/mock/message-tree.spec.tsindex 8ac3959c2c..922dda45a3 100644--- a/e2e/specs/mock/message-tree.spec.ts+++ b/e2e/specs/mock/message-tree.spec.ts@@ -1031,7 +1031,7 @@ test.describe('message tree stream operations', () => {await expect(editor).toBeVisible();await editor.fill(editedMiddlePrompt);await waitForGenerationStart(page, () =>- page.getByRole('button', { name: 'Save & Submit' }).click(),+ page.getByRole('button', { name: 'Update & rerun' }).click(),);await expect(messagesView(page).getByText(editedMiddleReply)).toBeVisible({ timeout: 30000 });diff --git a/e2e/specs/mock/message-visual.spec.ts b/e2e/specs/mock/message-visual.spec.tsnew file mode 100644index 0000000000..afb30be0e9--- /dev/null+++ b/e2e/specs/mock/message-visual.spec.ts@@ -0,0 +1,213 @@+import { expect, test } from '@playwright/test';+import type { Locator, Page } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ messagesView,+ replyPrompt,+ replyText,+ selectMockEndpoint,+ sendMessage,+ sendMessageAndWaitForCompletion,+} from './helpers';++type VisualTheme = 'light' | 'dark';+type VisualViewport = {+ height: number;+ name: 'desktop' | 'mobile';+ snapshotSuffix: '' | '-mobile';+ width: number;+};++const THEMES: VisualTheme[] = ['light', 'dark'];+const VIEWPORTS: VisualViewport[] = [+ { name: 'desktop', width: 1280, height: 900, snapshotSuffix: '' },+ { name: 'mobile', width: 390, height: 844, snapshotSuffix: '-mobile' },+];+const PROVIDER_C = { label: 'Mock Provider C', model: 'mock-model-c' };+const MCP_SERVER_TITLE = 'E2E Memory';+const VISUAL_OPTIONS = {+ animations: 'disabled' as const,+ caret: 'hide' as const,+ maxDiffPixels: 20,+ scale: 'css' as const,+};++/**+ * Pixel baselines only compare cleanly against the machine that produced them, and this+ * repository tracks none. Until baselines are generated on the runner image itself, the+ * flows below still run and assert their structure, while the screenshot comparison is+ * opt-in through `E2E_VISUAL_SNAPSHOTS=1 npx playwright test --config=e2e/playwright.config.mock.ts --update-snapshots`.+ */+const VISUAL_BASELINES_ENABLED = process.env.E2E_VISUAL_SNAPSHOTS === '1';++const messageRows = (page: Page) => messagesView(page).locator('.message-render');+const userRow = (page: Page) =>+ messageRows(page)+ .filter({ has: page.locator('.user-turn') })+ .last();+const assistantRow = (page: Page) =>+ messageRows(page)+ .filter({ has: page.locator('.agent-turn') })+ .last();+const stopButton = (page: Page) => page.getByRole('button', { name: 'Stop generating' });++async function openChat(page: Page, theme: VisualTheme, viewport: VisualViewport) {+ await page.addInitScript((selectedTheme: VisualTheme) => {+ localStorage.setItem('color-theme', selectedTheme);+ localStorage.removeItem('theme-definition');+ localStorage.removeItem('theme-colors');+ localStorage.removeItem('theme-name');+ localStorage.removeItem('theme-source');+ }, theme);+ await page.setViewportSize({ width: viewport.width, height: viewport.height });+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await expect(page.locator('html')).toHaveClass(new RegExp(`(^|\\s)${theme}(\\s|$)`));+}++async function expectMessageScreenshot(locator: Locator, name: string) {+ await expect(locator).toBeVisible();+ await locator.scrollIntoViewIfNeeded();+ await locator.page().evaluate(async () => {+ await document.fonts.ready;+ });+ if (!VISUAL_BASELINES_ENABLED) {+ return;+ }+ await expect(locator).toHaveScreenshot(name, VISUAL_OPTIONS);+}++async function selectEphemeralMCP(page: Page) {+ await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();+ const serverItem = page.getByRole('menuitemcheckbox', {+ name: new RegExp(MCP_SERVER_TITLE),+ });+ await expect(serverItem).toBeVisible();+ await serverItem.click();+ await expect(serverItem).toHaveAttribute('aria-checked', 'true');+ await page.keyboard.press('Escape');+}++test.skip(process.platform !== 'linux', 'Message visual baselines target the Linux CI runner');++for (const viewport of VIEWPORTS) {+ for (const theme of THEMES) {+ test.describe(`${theme} ${viewport.name} message visuals`, () => {+ test(`captures normal user and assistant messages`, async ({ page }) => {+ await openChat(page, theme, viewport);+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);++ const normalPrompt =+ viewport.name === 'mobile'+ ? 'Give me a concise plan for a calm morning before a busy day with several appointments.'+ : 'Give me a concise plan for a calm morning.';+ const response = await sendMessageAndWaitForCompletion(page, normalPrompt);+ expect(response.ok()).toBeTruthy();++ await expectMessageScreenshot(+ userRow(page),+ `message-normal-user-${theme}${viewport.snapshotSuffix}.png`,+ );+ await expectMessageScreenshot(+ assistantRow(page),+ `message-normal-assistant-${theme}${viewport.snapshotSuffix}.png`,+ );+ });++ test(`captures an active streaming response`, async ({ page }) => {+ test.setTimeout(60000);+ await openChat(page, theme, viewport);+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);++ const response = await sendMessage(+ page,+ `E2E_EMPTY_SLOW_REPLY:message-visual-stream-${viewport.name}`,+ );+ expect(response.ok()).toBeTruthy();+ await expect(stopButton(page)).toBeVisible();++ await expectMessageScreenshot(+ assistantRow(page),+ `message-streaming-${theme}${viewport.snapshotSuffix}.png`,+ );++ await stopButton(page).click();+ await expect(stopButton(page)).toBeHidden({ timeout: 30000 });+ });++ test(`captures a user message in edit mode`, async ({ page }) => {+ await openChat(page, theme, viewport);+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);++ const editPrompt =+ viewport.name === 'mobile'+ ? 'Turn this longer mobile message into an editable draft that wraps across multiple lines.'+ : 'Turn this message into an editable draft.';+ const response = await sendMessageAndWaitForCompletion(page, editPrompt);+ expect(response.ok()).toBeTruthy();++ const row = userRow(page);+ await row.hover();+ const editButton = row.locator('button[id^="edit-"]');+ await expect(editButton).toBeEnabled();+ await editButton.click();+ await expect(row.getByTestId('message-text-editor')).toBeVisible();+ await page.mouse.move(0, 0);++ await expectMessageScreenshot(+ row,+ `message-editing-${theme}${viewport.snapshotSuffix}.png`,+ );+ });++ test(`captures an applied steer message`, async ({ page }) => {+ test.setTimeout(150000);+ const setupLabel = `message-visual-steer-setup-${viewport.name}`;+ const runLabel = `message-visual-steer-${viewport.name}`;+ const steerText =+ viewport.name === 'mobile'+ ? 'Prioritize the three most important steps and keep each one concise.'+ : 'Prioritize the three most important steps.';++ const setupViewport = viewport.name === 'mobile' ? VIEWPORTS[0] : viewport;+ await openChat(page, theme, setupViewport);+ await selectMockEndpoint(page, PROVIDER_C);+ await selectEphemeralMCP(page);++ const setupResponse = await sendMessageAndWaitForCompletion(page, replyPrompt(setupLabel));+ expect(setupResponse.ok()).toBeTruthy();+ await expect(messagesView(page).getByText(replyText(setupLabel))).toBeVisible();++ const runResponse = await sendMessage(page, `E2E_STEER_TOOL_REPLY:${runLabel}`);+ expect(runResponse.ok()).toBeTruthy();++ const input = page.getByRole('textbox', { name: 'Message input' });+ await input.fill(steerText);+ const duringRunSendButton = page.getByTestId('during-run-send-button');+ await expect(duringRunSendButton).toHaveAttribute('data-during-run-action', 'steer');+ await input.press('Enter');++ const steerPart = messagesView(page)+ .getByTestId('steer-part')+ .filter({ hasText: steerText });+ await expect(steerPart).toHaveCount(1, { timeout: 60000 });+ await expect(+ messagesView(page).getByText(`E2E steer tool reply done ${runLabel}`),+ ).toBeVisible({+ timeout: 60000,+ });++ await page.setViewportSize({ width: viewport.width, height: viewport.height });+ const closeSidebarButton = page.getByTestId('close-sidebar-button');+ if (viewport.name === 'mobile' && (await closeSidebarButton.isVisible())) {+ await closeSidebarButton.click();+ }++ await expectMessageScreenshot(+ steerPart,+ `message-steered-${theme}${viewport.snapshotSuffix}.png`,+ );+ });+ });+ }+}