a.filepath).join(',')}
+ data-submitting={String(isSubmitting)}
+ />
+ );
+ },
ExecuteCode: () =>
,
ImageGen: () =>
,
AgentUpdate: () =>
,
@@ -261,6 +267,27 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {
expect(groups[0].getAttribute('data-count')).toBe('2');
});
+ it('marks grouped artifacts as history while another response regenerates', () => {
+ const content = [makeMcpToolCall('t1'), makeMcpToolCall('t2')];
+ const attachments = [imageAttachment('t1'), imageAttachment('t2')];
+
+ const { rerender } = renderContentParts({
+ ...baseProps,
+ isSubmitting: true,
+ isLatestMessage: false,
+ content,
+ attachments,
+ });
+ expect(screen.getByTestId('attachment-group')).toHaveAttribute('data-submitting', 'false');
+
+ rerender(
+
+
+ ,
+ );
+ expect(screen.getByTestId('attachment-group')).toHaveAttribute('data-submitting', 'true');
+ });
+
it('does not group a single tool call — image renders inline (no hoist)', () => {
const content = [makeMcpToolCall('t1')];
const attachments = [imageAttachment('t1', 'a.png')];
diff --git a/client/src/hooks/Artifacts/__tests__/useArtifacts.test.ts b/client/src/hooks/Artifacts/__tests__/useArtifacts.test.ts
index 02228a8695..57a9dcb4a6 100644
--- a/client/src/hooks/Artifacts/__tests__/useArtifacts.test.ts
+++ b/client/src/hooks/Artifacts/__tests__/useArtifacts.test.ts
@@ -506,6 +506,34 @@ describe('useArtifacts', () => {
expect(mockSetCurrentArtifactId).toHaveBeenCalledWith('artifact-2');
});
+ it('does not select a historical sibling artifact when regeneration begins', () => {
+ const selected = createArtifact({
+ id: 'selected',
+ messageId: 'original-response',
+ lastUpdateTime: 1000,
+ });
+ const historical = createArtifact({
+ id: 'historical',
+ messageId: 'previous-sibling',
+ lastUpdateTime: 2000,
+ content: 'old preview',
+ });
+ (useRecoilValue as jest.Mock).mockReturnValue({ selected });
+ (useRecoilState as jest.Mock).mockReturnValue(['selected', mockSetCurrentArtifactId]);
+ const { rerender } = renderHook(() => useArtifacts());
+ mockSetCurrentArtifactId.mockClear();
+
+ (useArtifactsContext as jest.Mock).mockReturnValue({
+ ...defaultContext,
+ isSubmitting: true,
+ latestMessageId: 'original-response_',
+ });
+ (useRecoilValue as jest.Mock).mockReturnValue({ selected, historical });
+ rerender();
+
+ expect(mockSetCurrentArtifactId).not.toHaveBeenCalled();
+ });
+
it('should not advance to a new CODE artifact during streaming', () => {
const artifact1 = createArtifact({ id: 'artifact-1', lastUpdateTime: 1000, content: 'c1' });
diff --git a/client/src/hooks/Artifacts/useArtifacts.ts b/client/src/hooks/Artifacts/useArtifacts.ts
index 279883ecfc..897e79c37b 100644
--- a/client/src/hooks/Artifacts/useArtifacts.ts
+++ b/client/src/hooks/Artifacts/useArtifacts.ts
@@ -229,7 +229,10 @@ export default function useArtifacts() {
}
const latestArtifactId = orderedArtifactIds[orderedArtifactIds.length - 1];
const latestArtifact = artifacts?.[latestArtifactId];
- if (latestArtifact?.content === lastContentRef.current && !justFinishedSubmitting) {
+ if (latestArtifact?.messageId !== latestMessageId) {
+ return;
+ }
+ if (latestArtifact.content === lastContentRef.current && !justFinishedSubmitting) {
return;
}
lastContentRef.current = latestArtifact?.content ?? null;
diff --git a/client/src/hooks/Files/__tests__/useAttachmentPreviewSync.spec.tsx b/client/src/hooks/Files/__tests__/useAttachmentPreviewSync.spec.tsx
index 95af147229..73a6e1f359 100644
--- a/client/src/hooks/Files/__tests__/useAttachmentPreviewSync.spec.tsx
+++ b/client/src/hooks/Files/__tests__/useAttachmentPreviewSync.spec.tsx
@@ -26,6 +26,7 @@ import type {
TFilePreview,
} from 'librechat-data-provider';
import type { ReactNode } from 'react';
+import { MessageContext } from '~/Providers/MessageContext';
import store from '~/store';
type AttachmentFixture = TFile & TAttachmentMetadata;
@@ -126,7 +127,9 @@ function setup({
children: (
<>
- {children}
+
+ {children}
+
>
),
}),
@@ -158,7 +161,10 @@ function setup({
*/
function setupWithTransitions(
initialPreview?: TFilePreview,
- { isSubmittingAtMount = true }: { isSubmittingAtMount?: boolean } = {},
+ {
+ isSubmittingAtMount = true,
+ messageIsSubmittingAtMount = isSubmittingAtMount,
+ }: { isSubmittingAtMount?: boolean; messageIsSubmittingAtMount?: boolean } = {},
) {
let currentPreview = initialPreview;
mockUseFilePreview.mockReset();
@@ -174,7 +180,7 @@ function setupWithTransitions(
* the transition. (A non-subscribing snapshot read inside an
* effect would capture the value as of the previous commit, which
* misses the flag set fired in *this* render's effect tick.) */
- const flag = useRecoilValue(store.previewJustResolved(id));
+ const flag = useRecoilValue(store.previewJustResolved([messageId, id]));
useEffect(() => {
flagRef.current = flag;
}, [flag]);
@@ -192,7 +198,11 @@ function setupWithTransitions(
}}
>
- {children}
+
+ {children}
+
),
},
@@ -413,10 +423,10 @@ describe('useAttachmentPreviewSync', () => {
/* The signal is the bridge to ToolArtifactCard's auto-open path:
* the card mounts after the routing re-runs (post-transition), so
* it can't observe the transition itself. Setting a one-shot flag
- * keyed by file_id lets the card consume the signal on its very
- * first effect tick. We assert on the flag directly here; the
+ * keyed by message and file lets only the owner consume the signal
+ * on its first effect tick. We assert on the flag directly here; the
* consume+open behavior lives in `ToolArtifactCard`'s coverage. */
- it('flips the per-file_id flag on the pending→ready transition', () => {
+ it('flips the owning message and file flag on the pending→ready transition', () => {
const ctx = setupWithTransitions({ file_id: fileId, status: 'pending' });
expect(ctx.justResolved).toBe(false);
ctx.setPreview({
@@ -428,6 +438,100 @@ describe('useAttachmentPreviewSync', () => {
expect(ctx.justResolved).toBe(true);
});
+ it('does not flag a previous response preview as newly resolved during regeneration', () => {
+ const ctx = setupWithTransitions(
+ { file_id: fileId, status: 'pending' },
+ { isSubmittingAtMount: true, messageIsSubmittingAtMount: false },
+ );
+ ctx.setPreview({
+ file_id: fileId,
+ status: 'ready',
+ text: '
',
+ textFormat: 'html',
+ });
+ expect(ctx.justResolved).toBe(false);
+ });
+
+ it('reclassifies a reused pending file when its owning response changes to the live one', () => {
+ let preview: TFilePreview | undefined = { file_id: fileId, status: 'pending' };
+ let owner = 'historical-response';
+ let isSubmitting = false;
+ mockUseFilePreview.mockReset();
+ mockUseFilePreview.mockImplementation(() => ({ data: preview, isFetching: false }));
+
+ const flags = { live: false, history: false };
+ const FlagProbe = () => {
+ flags.live = useRecoilValue(store.previewJustResolved(['live-response', fileId]));
+ flags.history = useRecoilValue(store.previewJustResolved(['historical-response', fileId]));
+ return null;
+ };
+ const { rerender } = renderHook(
+ ({ attachment }: { attachment: TAttachment }) => useAttachmentPreviewSync(attachment),
+ {
+ initialProps: { attachment: makeAttachment({ messageId: owner }) },
+ wrapper: ({ children }: { children: ReactNode }) => (
+
+
+
+ {children}
+
+
+ ),
+ },
+ );
+ owner = 'live-response';
+ isSubmitting = true;
+ rerender({ attachment: makeAttachment({ messageId: owner }) });
+ preview = {
+ file_id: fileId,
+ status: 'ready',
+ text: '
',
+ textFormat: 'html',
+ };
+ rerender({ attachment: makeAttachment({ messageId: owner }) });
+ expect(flags.live).toBe(true);
+ expect(flags.history).toBe(false);
+ });
+
+ it('does not flag a live file that becomes history before its preview resolves', () => {
+ let preview: TFilePreview | undefined = { file_id: fileId, status: 'pending' };
+ let owner = 'live-response';
+ let isSubmitting = true;
+ mockUseFilePreview.mockReset();
+ mockUseFilePreview.mockImplementation(() => ({ data: preview, isFetching: false }));
+
+ let historyFlag = false;
+ const FlagProbe = () => {
+ historyFlag = useRecoilValue(store.previewJustResolved(['historical-response', fileId]));
+ return null;
+ };
+ const { rerender } = renderHook(
+ ({ attachment }: { attachment: TAttachment }) => useAttachmentPreviewSync(attachment),
+ {
+ initialProps: { attachment: makeAttachment({ messageId: owner }) },
+ wrapper: ({ children }: { children: ReactNode }) => (
+
+
+
+ {children}
+
+
+ ),
+ },
+ );
+ owner = 'historical-response';
+ isSubmitting = false;
+ rerender({ attachment: makeAttachment({ messageId: owner }) });
+ preview = {
+ file_id: fileId,
+ status: 'ready',
+ text: '
',
+ textFormat: 'html',
+ };
+ rerender({ attachment: makeAttachment({ messageId: owner }) });
+ expect(historyFlag).toBe(false);
+ });
+
it('does NOT flip the flag when the polled status is "failed"', () => {
/* Failed previews stay as a download-only chip — nothing to
* auto-open. The signal must stay false so the eventual
diff --git a/client/src/hooks/Files/useAttachmentPreviewSync.ts b/client/src/hooks/Files/useAttachmentPreviewSync.ts
index f6595c9a36..4300519312 100644
--- a/client/src/hooks/Files/useAttachmentPreviewSync.ts
+++ b/client/src/hooks/Files/useAttachmentPreviewSync.ts
@@ -1,6 +1,7 @@
import { useEffect, useRef } from 'react';
import { useRecoilCallback, useSetRecoilState } from 'recoil';
import type { TAttachment, TFile, TFilePreview } from 'librechat-data-provider';
+import { useMessageContext } from '~/Providers/MessageContext';
import { useFilePreview } from '~/data-provider';
import { useShareContext } from '~/Providers';
import store from '~/store';
@@ -61,44 +62,36 @@ export default function useAttachmentPreviewSync(
attachment: TAttachment | undefined,
): UseAttachmentPreviewSyncResult {
const setAttachmentsMap = useSetRecoilState(store.messageAttachmentsMap);
- /* `useRecoilCallback` reads/writes without subscribing this hook to
- * the per-file_id flag — we only ever set it on the pending→ready
- * edge, so subscribing would cause needless re-renders. */
+ const { isSubmitting, messageId: contextMessageId } = useMessageContext();
+ /* `useRecoilCallback` writes without subscribing this hook to
+ * another message or file's pending→ready flag. */
const flagJustResolved = useRecoilCallback(
({ set }) =>
- (id: string) => {
- set(store.previewJustResolved(id), true);
+ (ownerId: string, id: string) => {
+ set(store.previewJustResolved([ownerId, id]), true);
},
[],
);
- /* Capture `isAnySubmitting` at first render via a non-subscribing
- * snapshot read. Mirrors `ToolArtifactCard`'s `mountedDuringStreamRef`
- * pattern so this hook applies the same "is the user actively in a
- * turn?" classification as the card itself. The ref is the gate that
- * distinguishes a *fresh* deferred-preview resolution (auto-open
- * eligible) from a *stale* DB-pending record resolving on a history
- * load (auto-open must NOT fire — the user is scrolling old data,
- * not awaiting a result). Without this gate, navigating back to a
- * conversation whose immediate-persist snapshot left the message's
- * attachments at `status: 'pending'` would re-trigger auto-open
- * every time the polling layer caught up — which is exactly the
- * pre-PR "panel pops open on every visit" UX the team explicitly
- * removed. */
- const readInitialIsSubmitting = useRecoilCallback(
- ({ snapshot }) =>
- () =>
- snapshot.getLoadable(store.isSubmittingFamily(0)).valueMaybe() ?? false,
- [],
- );
- const mountedDuringStreamRef = useRef
(null);
- if (mountedDuringStreamRef.current === null) {
- mountedDuringStreamRef.current = readInitialIsSubmitting();
- }
-
const file = (attachment ?? undefined) as Partial | undefined;
const fileId = file?.file_id;
const baseStatus: 'pending' | 'ready' | 'failed' = file?.status ?? 'ready';
const messageId = (attachment as Partial | undefined)?.messageId;
+ const ownerMessageId = contextMessageId || messageId;
+ /** A reused row must observe the pending→ready edge for its current owner, not its last one. */
+ const streamRef = useRef({
+ ownerMessageId,
+ fileId,
+ wasSubmitting: isSubmitting === true,
+ previousStatus: null as 'pending' | 'ready' | 'failed' | null,
+ });
+ if (streamRef.current.ownerMessageId !== ownerMessageId || streamRef.current.fileId !== fileId) {
+ streamRef.current = {
+ ownerMessageId,
+ fileId,
+ wasSubmitting: isSubmitting === true,
+ previousStatus: null,
+ };
+ }
const { shareId } = useShareContext();
const enabled = !!fileId && baseStatus === 'pending';
@@ -113,30 +106,31 @@ export default function useAttachmentPreviewSync(
const previewError = polled?.previewError ?? file?.previewError;
/* Track the previous effective status so we can fire the
- * pending→ready edge exactly once per session. Two gates have to
+ * pending→ready edge for the owning message and file. Two gates have to
* pass for the auto-open flag to flip:
* 1. We actually observed the transition (prev → curr).
- * 2. The hook mounted during an active stream — i.e. the file is
- * part of the user's current turn, not a history load. A
+ * 2. This message mounted during its own active stream, not a
+ * historical sibling displayed while another turn submits. A
* page-navigation mount (or refresh) of a stale-pending DB
* record will see the same transition when polling catches
* up, but we must NOT auto-open in that case — the user is
* revisiting old work, not waiting on a fresh result.
- * Refs are read inline so the effect doesn't have to list them as
- * deps (mutating a ref doesn't subscribe). */
- const prevStatusRef = useRef<'pending' | 'ready' | 'failed' | null>(null);
+ * The per-owner ref is reset before the effect when a different message
+ * or file takes this row, so a transition from the previous owner
+ * cannot be mistaken for a fresh preview. */
useEffect(() => {
- const prev = prevStatusRef.current;
- prevStatusRef.current = effectiveStatus;
+ const prev = streamRef.current.previousStatus;
+ streamRef.current.previousStatus = effectiveStatus;
if (
prev === 'pending' &&
effectiveStatus === 'ready' &&
fileId &&
- mountedDuringStreamRef.current === true
+ ownerMessageId &&
+ streamRef.current.wasSubmitting
) {
- flagJustResolved(fileId);
+ flagJustResolved(ownerMessageId, fileId);
}
- }, [effectiveStatus, fileId, flagJustResolved]);
+ }, [effectiveStatus, fileId, ownerMessageId, flagJustResolved]);
/* On a terminal poll response (ready or failed), upsert into the
* shared attachments map. Mirrors the SSE handler's by-file_id
diff --git a/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts b/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
index 058d8abbc9..14507b4655 100644
--- a/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
@@ -403,6 +403,95 @@ describe('resolveErrorTurn', () => {
metadata: { streamStartFailed: true },
} as unknown as TResData;
+ it('keeps a failed regeneration under its existing user turn when no content streamed', () => {
+ const regenerateSubmission = {
+ ...submission,
+ isRegenerate: true,
+ userMessage: {
+ ...userMessage,
+ messageId: 'temporary-user-id',
+ overrideParentMessageId: userMessage.messageId,
+ },
+ initialResponse: { ...initialResponse, messageId: 'response-id_' },
+ } as EventSubmission;
+ const siblings = [
+ { ...initialResponse, messageId: 'previous-sibling' },
+ { ...initialResponse, messageId: 'response-id' },
+ ];
+
+ const failedSubmission = {
+ ...regenerateSubmission,
+ regenerateMessages: [userMessage, ...siblings],
+ };
+ const { errorResponse } = resolveErrorTurn({
+ data: {
+ text: 'Model spec mismatch',
+ metadata: { streamStartFailed: true },
+ } as unknown as TResData,
+ submission: failedSubmission,
+ getMessages: () => [userMessage, siblings[0], regenerateSubmission.initialResponse],
+ isNewConversationRoute: false,
+ });
+
+ expect(errorResponse.messageId).toBe('response-id_');
+ expect(errorResponse.parentMessageId).toBe(userMessage.messageId);
+ expect(errorResponse.text).toBe('Model spec mismatch');
+ expect(
+ mergeErrorMessages({ ...failedSubmission, errorMessage: errorResponse }).map(
+ (message) => message.messageId,
+ ),
+ ).toEqual(['user-1', 'previous-sibling', 'response-id', 'response-id_']);
+
+ const addressed = resolveErrorTurn({
+ data: {
+ conversationId: 'conversation-1',
+ messageId: 'response-id_',
+ isCreatedByUser: false,
+ text: 'Model spec mismatch',
+ } as unknown as TResData,
+ submission: failedSubmission,
+ getMessages: () => [userMessage, regenerateSubmission.initialResponse],
+ isNewConversationRoute: false,
+ });
+ expect(addressed.errorResponse.parentMessageId).toBe(userMessage.messageId);
+ });
+
+ it.each([
+ ['transport failure', undefined],
+ [
+ 'server-addressed failure',
+ {
+ conversationId: 'conversation-1',
+ messageId: 'response-id_',
+ isCreatedByUser: false,
+ text: 'Model spec mismatch',
+ },
+ ],
+ ])('keeps a partially streamed regeneration on its original branch after a %s', (_name, data) => {
+ const regenerateSubmission = {
+ ...submission,
+ isRegenerate: true,
+ userMessage: {
+ ...userMessage,
+ messageId: 'temporary-user-id',
+ overrideParentMessageId: userMessage.messageId,
+ },
+ initialResponse: { ...initialResponse, messageId: 'response-id_' },
+ } as EventSubmission;
+ const streamed = { ...regenerateSubmission.initialResponse, content: streamedParts };
+
+ const { errorResponse } = resolveErrorTurn({
+ data: data as TResData | undefined,
+ submission: regenerateSubmission,
+ getMessages: () => [userMessage, streamed],
+ isNewConversationRoute: false,
+ });
+
+ expect(errorResponse.messageId).toBe('response-id_');
+ expect(errorResponse.parentMessageId).toBe(userMessage.messageId);
+ expect(errorResponse.content?.at(-1)?.type).toBe(ContentTypes.ERROR);
+ });
+
it('keeps what the run streamed and takes the failure as one more part', () => {
const { conversationId, errorResponse, recover } = resolveErrorTurn({
data: startFailure,
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index ebadfd8257..e202d545ff 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -91,16 +91,23 @@ const SKILL_QUERY_KEYS = [
QueryKeys.skillNodeContent,
] as const;
+/** A regenerated response is parented to the saved turn, never its unsaved replay copy. */
+const responseParentMessageId = (
+ initialResponse: TMessage,
+ userMessage: TMessage,
+ isRegenerate?: boolean,
+) =>
+ isRegenerate && initialResponse.parentMessageId
+ ? initialResponse.parentMessageId
+ : userMessage.messageId;
+
export const buildCreatedInitialResponse = ({
initialResponse,
userMessage,
isRegenerate = false,
}: Pick): TMessage => ({
...initialResponse,
- parentMessageId:
- isRegenerate && initialResponse.parentMessageId
- ? initialResponse.parentMessageId
- : userMessage.messageId,
+ parentMessageId: responseParentMessageId(initialResponse, userMessage, isRegenerate),
messageId:
isRegenerate && initialResponse.messageId
? initialResponse.messageId
@@ -332,11 +339,13 @@ const createErrorMessage = ({
text: '',
content: appendErrorPart(streamedContent, errorText),
};
- if (
- submission.userMessage.messageId &&
- submission.userMessage.messageId !== errorMessage.parentMessageId
- ) {
- errorMessage.parentMessageId = submission.userMessage.messageId;
+ const parentMessageId = responseParentMessageId(
+ submission.initialResponse,
+ submission.userMessage,
+ submission.isRegenerate,
+ );
+ if (parentMessageId && parentMessageId !== errorMessage.parentMessageId) {
+ errorMessage.parentMessageId = parentMessageId;
}
return errorMessage;
}
@@ -373,6 +382,11 @@ export const resolveErrorTurn = ({
isNewConversationRoute: boolean;
}): ErrorTurn => {
const { userMessage, initialResponse } = submission;
+ const parentMessageId = responseParentMessageId(
+ initialResponse,
+ userMessage,
+ submission.isRegenerate,
+ );
const conversationId =
userMessage.conversationId ?? submission.conversation?.conversationId ?? '';
@@ -382,7 +396,7 @@ export const resolveErrorTurn = ({
...initialResponse,
...metadata,
error: true,
- parentMessageId: userMessage.messageId,
+ parentMessageId,
};
if (errorMessage.messageId === undefined || errorMessage.messageId === '') {
@@ -423,7 +437,7 @@ export const resolveErrorTurn = ({
tMessageSchema.parse({
...data,
error: true,
- parentMessageId: userMessage.messageId,
+ parentMessageId,
}) as TMessage,
),
};
diff --git a/client/src/store/artifacts.ts b/client/src/store/artifacts.ts
index a92844293a..a4903074eb 100644
--- a/client/src/store/artifacts.ts
+++ b/client/src/store/artifacts.ts
@@ -1,6 +1,6 @@
import { atom, atomFamily, selectorFamily } from 'recoil';
-import { logger } from '~/utils';
import type { Artifact } from '~/common';
+import { logger } from '~/utils';
export const artifactsState = atom | null>({
key: 'artifactsState',
@@ -91,13 +91,13 @@ export const artifactByIdSelector = selectorFamily
/**
* One-shot signal that an attachment's deferred preview just transitioned
* from `pending` to `ready` during the current session — keyed by
- * `file_id` (raw, NOT the `tool-artifact-${file_id}` form).
+ * `[messageId, file_id]`. The same file can appear in more than one response;
+ * a historical card must not consume a live response's pending signal.
*
* The preview-sync hook flips this to `true` on the pending→ready edge.
- * `ToolArtifactCard` reads it on mount; if set, it auto-opens the panel
- * (even when no submission is in flight) and then resets the flag, so
- * subsequent re-mounts (panel close/reopen, re-render of the same card
- * from history) do not steal focus a second time.
+ * `ToolArtifactCard` reads it for the same owning message; if set, it
+ * auto-opens the panel (even when no submission is in flight) and then
+ * resets the flag, so later mounts of that response do not steal focus.
*
* Why a separate signal rather than reusing `mountedDuringStreamRef`:
* the deferred render can complete *after* the SSE stream has closed,
@@ -109,7 +109,7 @@ export const artifactByIdSelector = selectorFamily
* scrolling through history doesn't get the panel popping open every
* time a previously resolved chip enters the viewport.
*/
-export const previewJustResolved = atomFamily({
+export const previewJustResolved = atomFamily({
key: 'previewJustResolved',
default: false,
});