mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-18 14:08:21 +00:00
🫸 fix: Keep Historical Artifacts Closed During Regeneration (#16511)
* 🫸 fix: Keep Historical Artifacts Closed During Regeneration * 🫸 fix: Restrict Artifact Panel Selection to the Active Response * 🫸 fix: Keep Failed Regenerations in Their Original Branch * 🫸 fix: Isolate Artifact Preview Freshness by Response --------- Co-authored-by: Lia <lia@librechat.ai>
This commit is contained in:
parent
d7e7064692
commit
5682f77fc6
12 changed files with 558 additions and 127 deletions
|
|
@ -1198,7 +1198,17 @@ const ContentPartsBody = memo(function ContentPartsBody({
|
|||
});
|
||||
|
||||
const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
|
||||
const { attachments, messageId, conversationId } = props;
|
||||
const { attachments, messageId, conversationId, isSubmitting, isLatestMessage } = props;
|
||||
const messageContext = useMemo(
|
||||
() => ({
|
||||
messageId,
|
||||
conversationId,
|
||||
isExpanded: false as const,
|
||||
isSubmitting: isLatestMessage === true && isSubmitting,
|
||||
isLatestMessage,
|
||||
}),
|
||||
[messageId, conversationId, isSubmitting, isLatestMessage],
|
||||
);
|
||||
const toolState = useRef<{
|
||||
messageId: string;
|
||||
conversationId: string | null | undefined;
|
||||
|
|
@ -1245,13 +1255,15 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
|
|||
const attachmentsByName = useMemo(() => buildAttachmentsByName(attachments), [attachments]);
|
||||
const media = useMemo(() => ({ attachmentsByName }), [attachmentsByName]);
|
||||
return (
|
||||
<MediaContext.Provider value={media}>
|
||||
<ReasoningDisclosureContext.Provider value={reasoningDisclosures}>
|
||||
<ToolDisclosureContext.Provider value={toolDisclosures}>
|
||||
<ContentPartsBody {...props} />
|
||||
</ToolDisclosureContext.Provider>
|
||||
</ReasoningDisclosureContext.Provider>
|
||||
</MediaContext.Provider>
|
||||
<MessageContext.Provider value={messageContext}>
|
||||
<MediaContext.Provider value={media}>
|
||||
<ReasoningDisclosureContext.Provider value={reasoningDisclosures}>
|
||||
<ToolDisclosureContext.Provider value={toolDisclosures}>
|
||||
<ContentPartsBody {...props} />
|
||||
</ToolDisclosureContext.Provider>
|
||||
</ReasoningDisclosureContext.Provider>
|
||||
</MediaContext.Provider>
|
||||
</MessageContext.Provider>
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';
|
||||
import type { Artifact } from '~/common';
|
||||
import { artifactRowKind, isCodeOnlyArtifact } from '~/utils/artifacts';
|
||||
import { useMessageContext } from '~/Providers/MessageContext';
|
||||
import { displayFilename } from './attachmentTypes';
|
||||
import { useAttachmentLink } from './LogLink';
|
||||
import ArtifactRow from './ArtifactRow';
|
||||
|
|
@ -46,8 +47,8 @@ interface ToolArtifactCardProps {
|
|||
* Without that guard, both cards would observe each other's write
|
||||
* and trade overwrites in a loop.
|
||||
*
|
||||
* 3. **Focus + open on mount** (deps: artifact.id, artifact.type) —
|
||||
* gated on `isSubmitting` captured at first render via a ref AND
|
||||
* 3. **Focus + open on ownership change** (deps: artifact.id, artifact.type, ownerMessageId) —
|
||||
* gated on this message's `isSubmitting` captured on mount AND
|
||||
* on `artifact.type !== CODE`. A card mounted *during* streaming
|
||||
* for a rich-preview bucket (HTML, React, Markdown, plain text)
|
||||
* steals panel focus and forces `artifactsVisibility = true` so
|
||||
|
|
@ -66,6 +67,8 @@ interface ToolArtifactCardProps {
|
|||
*/
|
||||
const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps) => {
|
||||
const claimKey = useId();
|
||||
const { isSubmitting, messageId } = useMessageContext();
|
||||
const ownerMessageId = messageId || attachment.messageId || '';
|
||||
const file = attachment as TFile & TAttachmentMetadata;
|
||||
const fileId = file.file_id;
|
||||
const setVisible = useSetRecoilState(store.artifactsVisibility);
|
||||
|
|
@ -77,45 +80,27 @@ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps)
|
|||
const [claim, setClaim] = useRecoilState(store.toolArtifactClaim(artifact.id));
|
||||
const isSelected = artifact.id === currentArtifactId;
|
||||
const isMyClaim = claim === claimKey;
|
||||
/* Read+reset on mount only — `useRecoilCallback` avoids subscribing
|
||||
* to the per-file_id flag (no re-renders when other files resolve).
|
||||
/* Read+reset only for this response — `useRecoilCallback` avoids subscribing
|
||||
* to other file or message flags (no re-renders when other previews resolve).
|
||||
* The deferred-preview hook flips this to `true` on the pending→ready
|
||||
* edge; we consume it once and reset, so repeat mounts (panel close
|
||||
* then reopen, history scroll) don't auto-open a second time. */
|
||||
const consumeJustResolved = useRecoilCallback(
|
||||
({ snapshot, reset }) =>
|
||||
(id: string) => {
|
||||
const flagged = snapshot.getLoadable(store.previewJustResolved(id)).valueMaybe() ?? false;
|
||||
(ownerId: string, id: string) => {
|
||||
const signal = store.previewJustResolved([ownerId, id]);
|
||||
const flagged = snapshot.getLoadable(signal).valueMaybe() ?? false;
|
||||
if (flagged) {
|
||||
reset(store.previewJustResolved(id));
|
||||
reset(signal);
|
||||
}
|
||||
return flagged;
|
||||
},
|
||||
[],
|
||||
);
|
||||
/**
|
||||
* Captured at first render via a non-subscribing snapshot read so the
|
||||
* downstream effect doesn't re-fire (and the component doesn't
|
||||
* re-render) every time `isSubmittingFamily(0)` flips. Cards that mount
|
||||
* mid-stream stay "fresh" for the rest of their lifetime; cards that
|
||||
* mount post-stream stay "history" even if the user sends a new
|
||||
* message while this card stays mounted.
|
||||
*/
|
||||
const readInitialIsSubmitting = useRecoilCallback(
|
||||
({ snapshot }) =>
|
||||
() =>
|
||||
// `valueMaybe()` returns `undefined` if the atom is in an error
|
||||
// or loading state instead of throwing — defensive against an
|
||||
// upstream selector failure surfacing during card mount. The
|
||||
// `?? false` default is correct because a card we can't classify
|
||||
// as streaming is one we should treat as history (don't steal
|
||||
// focus / open the panel).
|
||||
snapshot.getLoadable(store.isSubmittingFamily(0)).valueMaybe() ?? false,
|
||||
[],
|
||||
);
|
||||
const mountedDuringStreamRef = useRef<boolean | null>(null);
|
||||
if (mountedDuringStreamRef.current === null) {
|
||||
mountedDuringStreamRef.current = readInitialIsSubmitting();
|
||||
/** Positional reconciliation can reuse this card for another response with the same file ID. */
|
||||
const mountedDuringStreamRef = useRef({ ownerMessageId, isSubmitting: isSubmitting === true });
|
||||
if (mountedDuringStreamRef.current.ownerMessageId !== ownerMessageId) {
|
||||
mountedDuringStreamRef.current = { ownerMessageId, isSubmitting: isSubmitting === true };
|
||||
}
|
||||
|
||||
useLayoutEffect(() => {
|
||||
|
|
@ -161,8 +146,8 @@ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps)
|
|||
return;
|
||||
}
|
||||
/* Two paths qualify the card for auto-open:
|
||||
* 1. Streaming-time mount — ref captured `isSubmitting === true`
|
||||
* at first render. The card is part of the live response, so
|
||||
* 1. Streaming-time ownership — ref captured `isSubmitting === true`
|
||||
* when this message became the owner. The card is part of the live response, so
|
||||
* the legacy "panel pops open as artifacts arrive" UX applies.
|
||||
* 2. Just-resolved deferred preview — `useAttachmentPreviewSync`
|
||||
* sets a one-shot flag on the pending→ready edge. The
|
||||
|
|
@ -174,8 +159,9 @@ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps)
|
|||
* History mounts (file already resolved on page load) hit neither
|
||||
* path, so the panel stays closed on navigation — no jarring
|
||||
* auto-open just from scrolling past an old artifact. */
|
||||
const justResolved = fileId ? consumeJustResolved(fileId) : false;
|
||||
if (!mountedDuringStreamRef.current && !justResolved) {
|
||||
const justResolved =
|
||||
fileId && ownerMessageId ? consumeJustResolved(ownerMessageId, fileId) : false;
|
||||
if (!mountedDuringStreamRef.current.isSubmitting && !justResolved) {
|
||||
return;
|
||||
}
|
||||
// Streaming arrival or just-resolved preview: focus the new artifact
|
||||
|
|
@ -185,7 +171,15 @@ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps)
|
|||
// never actually open — `Presentation` gates rendering on visibility.
|
||||
setCurrentArtifactId(artifact.id);
|
||||
setVisible(true);
|
||||
}, [artifact.id, artifact.type, fileId, consumeJustResolved, setCurrentArtifactId, setVisible]);
|
||||
}, [
|
||||
artifact.id,
|
||||
artifact.type,
|
||||
fileId,
|
||||
ownerMessageId,
|
||||
consumeJustResolved,
|
||||
setCurrentArtifactId,
|
||||
setVisible,
|
||||
]);
|
||||
|
||||
const { handleDownload } = useAttachmentLink({
|
||||
href: attachment.filepath ?? '',
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { render, screen, fireEvent, act } from '@testing-library/react';
|
|||
import type { TAttachment } from 'librechat-data-provider';
|
||||
import type { MutableSnapshot } from 'recoil';
|
||||
import Attachment, { AttachmentGroup } from '../Attachment';
|
||||
import { MessageContext } from '~/Providers/MessageContext';
|
||||
import store from '~/store';
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
|
|
@ -85,12 +86,20 @@ const baseAttachment = (overrides: Partial<TAttachment> = {}): TAttachment =>
|
|||
* the way each test expects. Default `streaming: true` matches the
|
||||
* legacy SSE-arrival flow that the bulk of these tests exercise.
|
||||
*/
|
||||
const inMessage = (ui: React.ReactElement, isSubmitting: boolean) => (
|
||||
<MessageContext.Provider value={{ messageId: 'test-response', isExpanded: true, isSubmitting }}>
|
||||
{ui}
|
||||
</MessageContext.Provider>
|
||||
);
|
||||
|
||||
const renderWith = (ui: React.ReactElement, opts: { streaming?: boolean } = {}) => {
|
||||
const streaming = opts.streaming ?? true;
|
||||
const initializeState = (snapshot: MutableSnapshot) => {
|
||||
snapshot.set(store.isSubmittingFamily(0), streaming);
|
||||
};
|
||||
return render(<RecoilRoot initializeState={initializeState}>{ui}</RecoilRoot>);
|
||||
return render(
|
||||
<RecoilRoot initializeState={initializeState}>{inMessage(ui, streaming)}</RecoilRoot>,
|
||||
);
|
||||
};
|
||||
|
||||
interface ArtifactsSnapshot {
|
||||
|
|
@ -130,7 +139,7 @@ const renderWithProbe = (ui: React.ReactElement, opts: { streaming?: boolean } =
|
|||
snapshot = snap;
|
||||
}}
|
||||
/>
|
||||
{ui}
|
||||
{inMessage(ui, streaming)}
|
||||
</RecoilRoot>,
|
||||
);
|
||||
return {
|
||||
|
|
@ -443,6 +452,154 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
expect(snap.currentArtifactId).toBeNull();
|
||||
});
|
||||
|
||||
it('does not open a historical artifact remounted while another response regenerates', () => {
|
||||
const html = baseAttachment({
|
||||
file_id: 'previous-answer',
|
||||
filename: 'previous.html',
|
||||
text: '<h1>previous answer</h1>',
|
||||
});
|
||||
const initializeState = (snap: MutableSnapshot) => {
|
||||
snap.set(store.isSubmittingFamily(0), true);
|
||||
snap.set(store.artifactsVisibility, false);
|
||||
};
|
||||
let snapshot: ArtifactsSnapshot = {
|
||||
visibility: false,
|
||||
currentArtifactId: null,
|
||||
artifactIds: [],
|
||||
};
|
||||
render(
|
||||
<RecoilRoot initializeState={initializeState}>
|
||||
<StateProbe onSnapshot={(next) => (snapshot = next)} />
|
||||
<MessageContext.Provider
|
||||
value={{ messageId: 'previous-response', isExpanded: true, isSubmitting: false }}
|
||||
>
|
||||
<Attachment attachment={html} />
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
expect(snapshot.artifactIds).toContain('tool-artifact-previous-answer');
|
||||
expect(snapshot.currentArtifactId).toBeNull();
|
||||
expect(snapshot.visibility).toBe(false);
|
||||
});
|
||||
|
||||
it('auto-opens when a reused artifact row changes from a historical to a live response', () => {
|
||||
const oldFile = baseAttachment({
|
||||
file_id: 'reused-file',
|
||||
filename: 'output.html',
|
||||
text: '<p>previous</p>',
|
||||
messageId: 'previous-response',
|
||||
});
|
||||
const state = { currentArtifactId: null as string | null, visibility: false };
|
||||
const renderRow = (messageId: string, isSubmitting: boolean, attachment: TAttachment) => (
|
||||
<RecoilRoot initializeState={({ set }) => set(store.artifactsVisibility, false)}>
|
||||
<StateProbe
|
||||
onSnapshot={(snapshot) => {
|
||||
state.currentArtifactId = snapshot.currentArtifactId;
|
||||
state.visibility = snapshot.visibility;
|
||||
}}
|
||||
/>
|
||||
<MessageContext.Provider value={{ messageId, isSubmitting, isExpanded: true }}>
|
||||
<Attachment attachment={attachment} />
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>
|
||||
);
|
||||
|
||||
const { rerender } = render(renderRow('previous-response', false, oldFile));
|
||||
expect(state.currentArtifactId).toBeNull();
|
||||
rerender(
|
||||
renderRow('new-response', true, {
|
||||
...oldFile,
|
||||
messageId: 'new-response',
|
||||
text: '<p>new result</p>',
|
||||
}),
|
||||
);
|
||||
expect(state.currentArtifactId).toBe('tool-artifact-reused-file');
|
||||
expect(state.visibility).toBe(true);
|
||||
});
|
||||
|
||||
it('does not reopen a reused live artifact when its new owner is historical', () => {
|
||||
const liveFile = baseAttachment({
|
||||
file_id: 'reused-live-file',
|
||||
filename: 'output.html',
|
||||
text: '<p>live</p>',
|
||||
messageId: 'live-response',
|
||||
});
|
||||
const state = { currentArtifactId: null as string | null, visibility: false };
|
||||
const renderRow = (messageId: string, isSubmitting: boolean, attachment: TAttachment) => (
|
||||
<RecoilRoot>
|
||||
<StateProbe
|
||||
onSnapshot={(snapshot) => {
|
||||
state.currentArtifactId = snapshot.currentArtifactId;
|
||||
state.visibility = snapshot.visibility;
|
||||
}}
|
||||
/>
|
||||
<MessageContext.Provider value={{ messageId, isSubmitting, isExpanded: true }}>
|
||||
<Attachment attachment={attachment} />
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>
|
||||
);
|
||||
|
||||
const { rerender } = render(renderRow('live-response', true, liveFile));
|
||||
expect(state.currentArtifactId).toBe('tool-artifact-reused-live-file');
|
||||
fireEvent.click(screen.getByRole('button', { expanded: true }));
|
||||
expect(state.currentArtifactId).toBeNull();
|
||||
rerender(
|
||||
renderRow('older-response', false, {
|
||||
...liveFile,
|
||||
messageId: 'older-response',
|
||||
text: '<p>historic</p>',
|
||||
}),
|
||||
);
|
||||
expect(state.currentArtifactId).toBeNull();
|
||||
expect(state.visibility).toBe(false);
|
||||
});
|
||||
|
||||
it('does not consume a deferred preview from a different response with the same file ID', () => {
|
||||
const fileId = 'shared-preview';
|
||||
const activeMessageId = 'current-response';
|
||||
const file = baseAttachment({
|
||||
file_id: fileId,
|
||||
filename: 'chart.xlsx',
|
||||
text: '<table>resolved</table>',
|
||||
textFormat: 'html',
|
||||
});
|
||||
const state = { currentArtifactId: null as string | null, visibility: false };
|
||||
const renderRows = (includeActive: boolean) => (
|
||||
<RecoilRoot
|
||||
initializeState={({ set }) => {
|
||||
set(store.artifactsVisibility, false);
|
||||
set(store.previewJustResolved([activeMessageId, fileId]), true);
|
||||
}}
|
||||
>
|
||||
<StateProbe
|
||||
onSnapshot={(snapshot) => {
|
||||
state.currentArtifactId = snapshot.currentArtifactId;
|
||||
state.visibility = snapshot.visibility;
|
||||
}}
|
||||
/>
|
||||
<MessageContext.Provider
|
||||
value={{ messageId: 'previous-response', isExpanded: true, isSubmitting: false }}
|
||||
>
|
||||
<Attachment attachment={{ ...file, messageId: 'previous-response' }} />
|
||||
</MessageContext.Provider>
|
||||
{includeActive && (
|
||||
<MessageContext.Provider
|
||||
value={{ messageId: activeMessageId, isExpanded: true, isSubmitting: false }}
|
||||
>
|
||||
<Attachment attachment={{ ...file, messageId: activeMessageId }} />
|
||||
</MessageContext.Provider>
|
||||
)}
|
||||
</RecoilRoot>
|
||||
);
|
||||
|
||||
const { rerender } = render(renderRows(false));
|
||||
expect(state.currentArtifactId).toBeNull();
|
||||
expect(state.visibility).toBe(false);
|
||||
rerender(renderRows(true));
|
||||
expect(state.currentArtifactId).toBe('tool-artifact-shared-preview');
|
||||
expect(state.visibility).toBe(true);
|
||||
});
|
||||
|
||||
it('does NOT auto-open a streaming CODE artifact (test.py is click-to-open)', () => {
|
||||
// Source-code artifacts are excluded from streaming auto-open even
|
||||
// when isSubmitting=true. The agent often emits supporting `.py` /
|
||||
|
|
@ -470,7 +627,7 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
snapshot = snap;
|
||||
}}
|
||||
/>
|
||||
<Attachment attachment={py} />
|
||||
{inMessage(<Attachment attachment={py} />, true)}
|
||||
</RecoilRoot>,
|
||||
);
|
||||
// Artifact registered (so the panel can find it on click)…
|
||||
|
|
@ -507,7 +664,7 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
snapshot = snap;
|
||||
}}
|
||||
/>
|
||||
<Attachment attachment={html} />
|
||||
{inMessage(<Attachment attachment={html} />, true)}
|
||||
</RecoilRoot>,
|
||||
);
|
||||
expect(snapshot.visibility).toBe(true);
|
||||
|
|
@ -552,7 +709,7 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
* (`isSubmitting=false`), the freshly resolved chip would render in
|
||||
* place but never auto-open the panel — the legacy auto-open path
|
||||
* is gated only on streaming. `useAttachmentPreviewSync` flips the
|
||||
* `previewJustResolved(file_id)` flag on the pending→ready edge to
|
||||
* `previewJustResolved([messageId, file_id])` flag on the pending→ready edge to
|
||||
* bridge that gap; `ToolArtifactCard` consumes it on mount and
|
||||
* auto-opens regardless of submission state. The flag is one-shot:
|
||||
* a subsequent re-mount (panel close/reopen, history scroll) must
|
||||
|
|
@ -566,7 +723,7 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
const initializeState = (snap: MutableSnapshot) => {
|
||||
snap.set(store.isSubmittingFamily(0), false);
|
||||
snap.set(store.artifactsVisibility, false);
|
||||
snap.set(store.previewJustResolved('just-resolved-xlsx'), true);
|
||||
snap.set(store.previewJustResolved(['test-response', 'just-resolved-xlsx']), true);
|
||||
};
|
||||
let snapshot: ArtifactsSnapshot = {
|
||||
visibility: false,
|
||||
|
|
@ -580,7 +737,7 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
snapshot = snap;
|
||||
}}
|
||||
/>
|
||||
<Attachment attachment={xlsx} />
|
||||
{inMessage(<Attachment attachment={xlsx} />, false)}
|
||||
</RecoilRoot>,
|
||||
);
|
||||
expect(snapshot.currentArtifactId).toBe('tool-artifact-just-resolved-xlsx');
|
||||
|
|
@ -601,7 +758,7 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
const initializeState = (snap: MutableSnapshot) => {
|
||||
snap.set(store.isSubmittingFamily(0), false);
|
||||
snap.set(store.artifactsVisibility, false);
|
||||
snap.set(store.previewJustResolved('one-shot-xlsx'), true);
|
||||
snap.set(store.previewJustResolved(['test-response', 'one-shot-xlsx']), true);
|
||||
};
|
||||
let snapshot: ArtifactsSnapshot = {
|
||||
visibility: false,
|
||||
|
|
@ -615,7 +772,7 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
snapshot = snap;
|
||||
}}
|
||||
/>
|
||||
<Attachment attachment={xlsx} />
|
||||
{inMessage(<Attachment attachment={xlsx} />, false)}
|
||||
</RecoilRoot>,
|
||||
);
|
||||
/* First mount auto-opened. Now simulate a fresh Recoil tree with the
|
||||
|
|
@ -637,7 +794,7 @@ describe('ToolArtifactCard click behaviour', () => {
|
|||
snapshot = snap;
|
||||
}}
|
||||
/>
|
||||
<Attachment attachment={xlsx} />
|
||||
{inMessage(<Attachment attachment={xlsx} />, false)}
|
||||
</RecoilRoot>,
|
||||
);
|
||||
expect(snapshot.currentArtifactId).toBeNull();
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { RecoilRoot } from 'recoil';
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import type { TAttachment } from 'librechat-data-provider';
|
||||
import type { MutableSnapshot } from 'recoil';
|
||||
import { MessageContext } from '~/Providers/MessageContext';
|
||||
import LogContent from '../LogContent';
|
||||
import store from '~/store';
|
||||
|
||||
|
|
@ -75,7 +76,15 @@ const renderWith = (ui: React.ReactElement, opts: { streaming?: boolean } = {})
|
|||
const initializeState = (snapshot: MutableSnapshot) => {
|
||||
snapshot.set(store.isSubmittingFamily(0), streaming);
|
||||
};
|
||||
return render(<RecoilRoot initializeState={initializeState}>{ui}</RecoilRoot>);
|
||||
return render(
|
||||
<RecoilRoot initializeState={initializeState}>
|
||||
<MessageContext.Provider
|
||||
value={{ messageId: 'test-response', isExpanded: true, isSubmitting: streaming }}
|
||||
>
|
||||
{ui}
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('LogContent attachment routing', () => {
|
||||
|
|
|
|||
|
|
@ -82,13 +82,19 @@ jest.mock('../Parts', () => ({
|
|||
StreamingThoughtPeek: ({ text }: { text: string }) => (
|
||||
<div data-testid="streaming-thought-peek">{text}</div>
|
||||
),
|
||||
AttachmentGroup: ({ attachments }: { attachments?: TAttachment[] }) => (
|
||||
<div
|
||||
data-testid="attachment-group"
|
||||
data-count={attachments?.length ?? 0}
|
||||
data-paths={(attachments ?? []).map((a) => a.filepath).join(',')}
|
||||
/>
|
||||
),
|
||||
AttachmentGroup: ({ attachments }: { attachments?: TAttachment[] }) => {
|
||||
const { isSubmitting } = jest
|
||||
.requireActual<typeof import('~/Providers/MessageContext')>('~/Providers/MessageContext')
|
||||
.useMessageContext();
|
||||
return (
|
||||
<div
|
||||
data-testid="attachment-group"
|
||||
data-count={attachments?.length ?? 0}
|
||||
data-paths={(attachments ?? []).map((a) => a.filepath).join(',')}
|
||||
data-submitting={String(isSubmitting)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
ExecuteCode: () => <div data-testid="execute-code" />,
|
||||
ImageGen: () => <div data-testid="image-gen" />,
|
||||
AgentUpdate: () => <div data-testid="agent-update" />,
|
||||
|
|
@ -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(
|
||||
<RecoilRoot>
|
||||
<ContentParts {...baseProps} isSubmitting content={content} attachments={attachments} />
|
||||
</RecoilRoot>,
|
||||
);
|
||||
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')];
|
||||
|
|
|
|||
|
|
@ -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' });
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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: (
|
||||
<>
|
||||
<Bridge />
|
||||
{children}
|
||||
<MessageContext.Provider value={{ messageId, isExpanded: true, isSubmitting }}>
|
||||
{children}
|
||||
</MessageContext.Provider>
|
||||
</>
|
||||
),
|
||||
}),
|
||||
|
|
@ -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(
|
|||
}}
|
||||
>
|
||||
<FlagProbe id={fileId} />
|
||||
{children}
|
||||
<MessageContext.Provider
|
||||
value={{ messageId, isExpanded: true, isSubmitting: messageIsSubmittingAtMount }}
|
||||
>
|
||||
{children}
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>
|
||||
),
|
||||
},
|
||||
|
|
@ -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: '<table>old response</table>',
|
||||
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 }) => (
|
||||
<RecoilRoot>
|
||||
<FlagProbe />
|
||||
<MessageContext.Provider value={{ messageId: owner, isExpanded: true, isSubmitting }}>
|
||||
{children}
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>
|
||||
),
|
||||
},
|
||||
);
|
||||
owner = 'live-response';
|
||||
isSubmitting = true;
|
||||
rerender({ attachment: makeAttachment({ messageId: owner }) });
|
||||
preview = {
|
||||
file_id: fileId,
|
||||
status: 'ready',
|
||||
text: '<table>new answer</table>',
|
||||
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 }) => (
|
||||
<RecoilRoot>
|
||||
<FlagProbe />
|
||||
<MessageContext.Provider value={{ messageId: owner, isExpanded: true, isSubmitting }}>
|
||||
{children}
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>
|
||||
),
|
||||
},
|
||||
);
|
||||
owner = 'historical-response';
|
||||
isSubmitting = false;
|
||||
rerender({ attachment: makeAttachment({ messageId: owner }) });
|
||||
preview = {
|
||||
file_id: fileId,
|
||||
status: 'ready',
|
||||
text: '<table>old answer</table>',
|
||||
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
|
||||
|
|
|
|||
|
|
@ -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<boolean | null>(null);
|
||||
if (mountedDuringStreamRef.current === null) {
|
||||
mountedDuringStreamRef.current = readInitialIsSubmitting();
|
||||
}
|
||||
|
||||
const file = (attachment ?? undefined) as Partial<TFile> | undefined;
|
||||
const fileId = file?.file_id;
|
||||
const baseStatus: 'pending' | 'ready' | 'failed' = file?.status ?? 'ready';
|
||||
const messageId = (attachment as Partial<TAttachment> | 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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<EventSubmission, 'initialResponse' | 'userMessage' | 'isRegenerate'>): 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,
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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<Record<string, Artifact | undefined> | null>({
|
||||
key: 'artifactsState',
|
||||
|
|
@ -91,13 +91,13 @@ export const artifactByIdSelector = selectorFamily<Artifact | undefined, string>
|
|||
/**
|
||||
* 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<Artifact | undefined, string>
|
|||
* scrolling through history doesn't get the panel popping open every
|
||||
* time a previously resolved chip enters the viewport.
|
||||
*/
|
||||
export const previewJustResolved = atomFamily<boolean, string>({
|
||||
export const previewJustResolved = atomFamily<boolean, [messageId: string, fileId: string]>({
|
||||
key: 'previewJustResolved',
|
||||
default: false,
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue