Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🖇️ feat: Reference Selected Chat Text with Multi-Quote Popup (#13868)

Danny Avila5eb1c2c10708
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index 03653333b4..871a398e23 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -7,6 +7,7 @@ const {
getBalanceConfig,
buildMessageFiles,
extractFileContext,
+ getReferencedQuotes,
encodeAndFormatAudios,
encodeAndFormatVideos,
encodeAndFormatDocuments,
@@ -277,6 +278,21 @@ class BaseClient {
text: message,
});
+ /**
+ * Attach quoted excerpts (the "Add to chat" selections from `req.body.quotes`)
+ * before `getReqData`/`onStart` fire, so the optimistic bubble, resumable job
+ * metadata, and the saved row all carry them. Only on fresh turns — edits
+ * replay an existing message that already has its quotes. The excerpts are
+ * merged into the model-facing text later, per message, in `buildMessages`,
+ * keeping the stored `text` clean while the count stays consistent.
+ */
+ if (!opts.isEdited) {
+ const referencedQuotes = getReferencedQuotes(this.options.req?.body?.quotes);
+ if (referencedQuotes != null) {
+ userMessage.quotes = referencedQuotes;
+ }
+ }
+
if (typeof opts?.getReqData === 'function') {
opts.getReqData({
userMessage,
diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.js
index 1e8fc13ba2..40c4a1e05e 100644
--- a/api/app/clients/specs/BaseClient.test.js
+++ b/api/app/clients/specs/BaseClient.test.js
@@ -1316,4 +1316,60 @@ describe('BaseClient', () => {
expect(userSave[0].files[0].file_id).toBe('file-abc');
});
});
+
+ describe('sendMessage quote references', () => {
+ // The blockquote merge itself lives in AgentClient.buildMessages / prependQuotes
+ // (covered by packages/api specs). BaseClient's job is to attach the normalized
+ // quotes onto the user message early and keep the stored text clean.
+ test('attaches normalized quotes before getReqData fires and keeps stored text clean', async () => {
+ TestClient.options.req = { body: { quotes: [' the selected text ', '', 42] } };
+ TestClient.saveMessageToDatabase = jest.fn().mockResolvedValue({ message: {} });
+ let captured;
+ await TestClient.sendMessage('What does this mean?', {
+ getReqData: (data) => {
+ if (data.userMessage) {
+ captured = { text: data.userMessage.text, quotes: data.userMessage.quotes };
+ }
+ },
+ });
+
+ // Quotes are present (trimmed, non-strings dropped) at getReqData time, and
+ // the user text is never mutated by the merge.
+ expect(captured).toBeDefined();
+ expect(captured.quotes).toEqual(['the selected text']);
+ expect(captured.text).toBe('What does this mean?');
+
+ const userSave = TestClient.saveMessageToDatabase.mock.calls.find(
+ ([msg]) => msg.isCreatedByUser,
+ );
+ expect(userSave[0].text).toBe('What does this mean?');
+ expect(userSave[0].quotes).toEqual(['the selected text']);
+ });
+
+ test('persists multiple quotes in order on the saved message', async () => {
+ TestClient.options.req = { body: { quotes: ['first excerpt', 'second excerpt'] } };
+ TestClient.saveMessageToDatabase = jest.fn().mockResolvedValue({ message: {} });
+
+ await TestClient.sendMessage('Compare these');
+
+ const userSave = TestClient.saveMessageToDatabase.mock.calls.find(
+ ([msg]) => msg.isCreatedByUser,
+ );
+ expect(userSave[0].text).toBe('Compare these');
+ expect(userSave[0].quotes).toEqual(['first excerpt', 'second excerpt']);
+ });
+
+ test('leaves the message untouched when no quotes are provided', async () => {
+ TestClient.options.req = { body: {} };
+ TestClient.saveMessageToDatabase = jest.fn().mockResolvedValue({ message: {} });
+
+ await TestClient.sendMessage('Just a question');
+
+ const userSave = TestClient.saveMessageToDatabase.mock.calls.find(
+ ([msg]) => msg.isCreatedByUser,
+ );
+ expect(userSave[0].text).toBe('Just a question');
+ expect(userSave[0].quotes).toBeUndefined();
+ });
+ });
});
diff --git a/api/server/controllers/agents/__tests__/jobReplacement.spec.js b/api/server/controllers/agents/__tests__/jobReplacement.spec.js
index efa79ca4ba..7f7a775b75 100644
--- a/api/server/controllers/agents/__tests__/jobReplacement.spec.js
+++ b/api/server/controllers/agents/__tests__/jobReplacement.spec.js
@@ -35,6 +35,15 @@ jest.mock('@librechat/data-schemas', () => ({
jest.mock('@librechat/api', () => ({
isEnabled: jest.fn().mockReturnValue(false),
GenerationJobManager: mockGenerationJobManager,
+ getReferencedQuotes: jest.fn((quotes) => {
+ if (!Array.isArray(quotes)) {
+ return null;
+ }
+ const normalized = quotes
+ .filter((quote) => typeof quote === 'string' && quote.trim().length > 0)
+ .map((quote) => quote.trim());
+ return normalized.length > 0 ? normalized : null;
+ }),
checkAndIncrementPendingRequest: jest.fn().mockResolvedValue({ allowed: true }),
decrementPendingRequest: (...args) => mockDecrementPendingRequest(...args),
getViolationInfo: jest.fn(),
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
index de07b4ab54..8024b8d408 100644
--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
@@ -86,6 +86,15 @@ jest.mock('@librechat/api', () => ({
buildMessageFiles: jest.fn(() => []),
resolveTitleTiming: jest.fn(() => 'immediate'),
GenerationJobManager: mockGenerationJobManager,
+ getReferencedQuotes: jest.fn((quotes) => {
+ if (!Array.isArray(quotes)) {
+ return null;
+ }
+ const normalized = quotes
+ .filter((quote) => typeof quote === 'string' && quote.trim().length > 0)
+ .map((quote) => quote.trim());
+ return normalized.length > 0 ? normalized : null;
+ }),
cleanupMCPRequestContext: (...args) => mockCleanupMCPRequestContext(...args),
createMCPRequestContext: (...args) => mockCreateMCPRequestContext(...args),
getMCPRequestContext: (...args) => mockGetMCPRequestContext(...args),
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 0182ade3ae..b6032530c9 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -39,6 +39,7 @@ const {
filterMalformedContentParts,
countFormattedMessageTokens,
prependFileContext,
+ prependQuotes,
hydrateMissingIndexTokenCounts,
injectSkillPrimes,
collectFreshSkillPrimeNames,
@@ -377,12 +378,32 @@ class AgentClient extends BaseClient {
prependFileContext(formattedMessage, message.fileContext);
}
+ /**
+ * Durably re-merge quoted excerpts into every user turn that carries them
+ * (current and historical) so the model receives the referenced context on
+ * every prompt and the token count matches what was persisted. Applied to
+ * the memory copy too so the canonical per-message count includes them.
+ */
+ if (Array.isArray(message.quotes) && message.quotes.length > 0) {
+ prependQuotes(formattedMessage, message.quotes);
+ prependQuotes(memoryFormattedMessage, message.quotes);
+ }
+
memoryPayload.push(memoryFormattedMessage);
const dbTokenCount = Number(orderedMessages[i].tokenCount);
const hasDbTokenCount = Number.isFinite(dbTokenCount) && dbTokenCount > 0;
+ /**
+ * Force a recount when the message carries quotes: a plain text-only
+ * "Save" edit recomputes `tokenCount` from `text` alone while leaving
+ * `message.quotes` persisted, so the stored count would undercount the
+ * quote block this turn prepends. Recounting from the quote-merged memory
+ * copy keeps context accounting accurate (and self-heals stale counts).
+ */
const needsCanonicalTokenCount =
- !hasDbTokenCount || (this.isVisionModel && (message.image_urls || message.files));
+ !hasDbTokenCount ||
+ (this.isVisionModel && (message.image_urls || message.files)) ||
+ (Array.isArray(message.quotes) && message.quotes.length > 0);
let canonicalTokenCount = hasDbTokenCount ? dbTokenCount : 0;
if (needsCanonicalTokenCount) {
diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js
index c2bcd5c12e..0b8c0cee1a 100644
--- a/api/server/controllers/agents/request.js
+++ b/api/server/controllers/agents/request.js
@@ -4,6 +4,7 @@ const {
sendEvent,
getViolationInfo,
buildMessageFiles,
+ getReferencedQuotes,
resolveTitleTiming,
GenerationJobManager,
filterPersistableAbortContent,
@@ -93,16 +94,25 @@ function getPreliminaryResponseMessageId({ messageId, responseMessageId }) {
return `${messageId.replace(/_+$/, '')}_`;
}
-function getPreliminaryUserMessage({ messageId, parentMessageId, text }, conversationId) {
+function getPreliminaryUserMessage({ messageId, parentMessageId, text, quotes }, conversationId) {
if (typeof messageId !== 'string' || messageId.length === 0) {
return null;
}
+ /**
+ * Seed normalized quotes here too: if the user aborts before `sendMessage`
+ * reaches `onStart` (during init/tool loading), `abortMiddleware` falls back
+ * to this preliminary metadata, which must carry the excerpts so the stopped
+ * turn keeps its `MessageQuotes`.
+ */
+ const referencedQuotes = getReferencedQuotes(quotes);
+
return {
messageId,
parentMessageId,
conversationId,
text,
+ ...(referencedQuotes != null && { quotes: referencedQuotes }),
};
}
@@ -439,6 +449,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
parentMessageId: userMsg.parentMessageId,
conversationId: userMsg.conversationId,
text: userMsg.text,
+ quotes: userMsg.quotes,
},
});
@@ -930,6 +941,7 @@ const _LegacyAgentController = async (req, res, next, initializeClient, addTitle
parentMessageId: userMsg.parentMessageId,
conversationId,
text: userMsg.text,
+ quotes: userMsg.quotes,
},
});
};
diff --git a/api/server/middleware/abortMiddleware.js b/api/server/middleware/abortMiddleware.js
index 8b339b05ba..35bd53c579 100644
--- a/api/server/middleware/abortMiddleware.js
+++ b/api/server/middleware/abortMiddleware.js
@@ -159,6 +159,7 @@ async function abortMessage(req, res) {
parentMessageId: jobData.userMessage.parentMessageId,
conversationId: jobData.userMessage.conversationId,
text: jobData.userMessage.text,
+ quotes: jobData.userMessage.quotes,
isCreatedByUser: true,
})
: null,
diff --git a/api/server/middleware/moderateText.js b/api/server/middleware/moderateText.js
index 775afbafbf..1aed0991ad 100644
--- a/api/server/middleware/moderateText.js
+++ b/api/server/middleware/moderateText.js
@@ -1,5 +1,5 @@
const axios = require('axios');
-const { isEnabled } = require('@librechat/api');
+const { isEnabled, getReferencedQuotes, mergeQuotedText } = require('@librechat/api');
const { logger } = require('@librechat/data-schemas');
const { ErrorTypes } = require('librechat-data-provider');
const denyRequest = require('./denyRequest');
@@ -11,10 +11,29 @@ async function moderateText(req, res, next) {
try {
const { text } = req.body;
+ /**
+ * Moderate the typed text, each quoted excerpt, and the merged blockquote+text
+ * exactly as the model receives it. Quotes are normalized via
+ * `getReferencedQuotes` first (matching `BaseClient`); moderating the merged
+ * string also covers content split across a quote and the typed body. The
+ * moderation API accepts an array of inputs.
+ */
+ const safeText = typeof text === 'string' ? text : '';
+ const inputs = [];
+ if (safeText.length > 0) {
+ inputs.push(safeText);
+ }
+ const quotes = getReferencedQuotes(req.body.quotes);
+ if (quotes != null) {
+ inputs.push(...quotes);
+ inputs.push(mergeQuotedText(safeText, quotes));
+ }
+ const input = inputs.length > 1 ? inputs : (inputs[0] ?? text);
+
const response = await axios.post(
process.env.OPENAI_MODERATION_REVERSE_PROXY || 'https://api.openai.com/v1/moderations',
{
- input: text,
+ input,
},
{
headers: {
diff --git a/client/src/common/types.ts b/client/src/common/types.ts
index 9cdebffd2b..a27743a8f0 100644
--- a/client/src/common/types.ts
+++ b/client/src/common/types.ts
@@ -365,6 +365,13 @@ export type TOptions = {
* pills are still visible on the user bubble.
*/
overrideManualSkills?: string[];
+ /**
+ * Carry forward a user message's quoted excerpts when resubmitting /
+ * regenerating that same message — the compose-time atom is drained on the
+ * original submit, so without this the second turn would lose the quoted
+ * context even though the references still show on the user bubble.
+ */
+ overrideQuotes?: string[];
/** Added conversation for multi-convo feature - sent to server as part of submission payload */
addedConvo?: t.TConversation;
};
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index baed7ba4a2..c02ee15e1a 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -25,6 +25,7 @@ import PendingManualSkillsChips from './PendingManualSkillsChips';
import { cn, getModelSpec, removeFocusRings } from '~/utils';
import { useGetStartupConfig } from '~/data-provider';
import { mainTextareaId, BadgeItem } from '~/common';
+import PendingQuoteChips from './PendingQuoteChips';
import AttachFileChat from './Files/AttachFileChat';
import FileFormChat from './Files/FileFormChat';
import TextareaHeader from './TextareaHeader';
@@ -32,6 +33,7 @@ import PromptsCommand from './PromptsCommand';
import SkillsCommand from './SkillsCommand';
import AudioRecorder from './AudioRecorder';
import CollapseChat from './CollapseChat';
+import QuoteButton from './QuoteButton';
import StreamAudio from './StreamAudio';
import TokenUsage from './TokenUsage';
import StopButton from './StopButton';
@@ -115,6 +117,12 @@ const ChatForm = memo(function ChatForm({
() => conversation?.conversationId ?? Constants.NEW_CONVO,
[conversation?.conversationId],
);
+ /**
+ * The quote feature merges excerpts server-side in `BaseClient.sendMessage`,
+ * which the Assistants endpoints bypass — so hide the UI there rather than
+ * letting users queue quotes the assistant never receives.
+ */
+ const quotesEnabled = useMemo(() => !isAssistantsEndpoint(endpoint), [endpoint]);
const isRTL = useMemo(
() => (chatDirection != null ? chatDirection?.toLowerCase() === 'rtl' : false),
@@ -250,6 +258,8 @@ const ChatForm = memo(function ChatForm({
)}
>
<div className="relative flex h-full flex-1 items-stretch md:flex-col">
+ {/* Primary composer owns the selection popup so split-view doesn't double it. */}
+ {index === 0 && quotesEnabled && <QuoteButton conversationId={conversationId} />}
<div className={cn('flex w-full items-center', isRTL && 'flex-row-reverse')}>
<Mention
index={index}
@@ -285,6 +295,7 @@ const ChatForm = memo(function ChatForm({
>
<TextareaHeader addedConvo={addedConvo} setAddedConvo={setAddedConvo} />
<PendingManualSkillsChips conversationId={conversationId} />
+ {quotesEnabled && <PendingQuoteChips conversationId={conversationId} />}
{/* WIP */}
<EditBadges
isEditingChatBadges={isEditingBadges}
diff --git a/client/src/components/Chat/Input/PendingQuoteChips.tsx b/client/src/components/Chat/Input/PendingQuoteChips.tsx
new file mode 100644
index 0000000000..7ba436c062
--- /dev/null
+++ b/client/src/components/Chat/Input/PendingQuoteChips.tsx
@@ -0,0 +1,170 @@
+import { memo, useRef, useState, useEffect, useCallback } from 'react';
+import * as Ariakit from '@ariakit/react';
+import { TextQuote, X } from 'lucide-react';
+import { useRecoilValue, useSetRecoilState } from 'recoil';
+import { useLocalize } from '~/hooks';
+import store from '~/store';
+
+const CHIP_CLASS =
+ 'inline-flex max-w-full items-center gap-1 rounded-2xl border border-border-light bg-surface-secondary px-2.5 py-1.5 text-sm text-text-secondary';
+const REMOVE_BTN_CLASS =
+ '-mr-0.5 shrink-0 rounded-full p-0.5 text-text-secondary hover:bg-surface-tertiary hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-xheavy';
+const TRIGGER_CLASS =
+ 'inline-flex min-w-0 items-center gap-1.5 rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-xheavy';
+/** Grace period so moving the pointer between the chip and the popup doesn't close it. */
+const CLOSE_DELAY_MS = 120;
+
+/**
+ * Chip row rendered above the textarea for excerpts the user quoted via the
+ * "Add to chat" selection popup. Shows a single chip: the excerpt text for one
+ * selection, or a collapsed "{n} selections" pill for multiple — so the
+ * composer never fills with a row of chips.
+ *
+ * The collapsed pill is an Ariakit `Popover` disclosure: it opens on
+ * click / Enter / Space (keyboard users tab through the excerpts, Escape closes
+ * and Ariakit restores focus to the trigger) and on hover for mouse users.
+ * `autoFocusOnShow` is disabled so opening never pulls focus off the composer;
+ * `autoFocusOnHide` still returns focus to the trigger when focus was inside.
+ *
+ * Reads + writes `pendingQuotesByConvoId` directly; the atom is drained in
+ * `useChatFunctions.ask` on submit, so chips disappear once the message is sent
+ * (the excerpts then re-render as `MessageQuotes` on the user bubble).
+ */
+function PendingQuoteChips({ conversationId }: { conversationId: string }) {
+ const localize = useLocalize();
+ const quotes = useRecoilValue(store.pendingQuotesByConvoId(conversationId));
+ const setQuotes = useSetRecoilState(store.pendingQuotesByConvoId(conversationId));
+
+ const popover = Ariakit.usePopoverStore({ placement: 'top-start' });
+ const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ /**
+ * Ariakit only restores focus to the trigger on hide when it took focus on
+ * show, so keep `autoFocusOnShow` on for keyboard/click opens (Escape returns
+ * focus to the trigger) and off for hover so it never pulls focus off the
+ * composer mid-typing.
+ */
+ const [focusOnShow, setFocusOnShow] = useState(true);
+
+ const cancelClose = useCallback(() => {
+ if (closeTimerRef.current != null) {
+ clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = null;
+ }
+ }, []);
+ const openByPointer = useCallback(() => {
+ cancelClose();
+ setFocusOnShow(false);
+ popover.show();
+ }, [cancelClose, popover]);
+ const scheduleClose = useCallback(() => {
+ cancelClose();
+ closeTimerRef.current = setTimeout(() => popover.hide(), CLOSE_DELAY_MS);
+ }, [cancelClose, popover]);
+
+ useEffect(() => cancelClose, [cancelClose]);
+
+ const clearAll = useCallback(() => setQuotes([]), [setQuotes]);
+ const removeAt = useCallback(
+ (index: number) => setQuotes((prev) => prev.filter((_, i) => i !== index)),
+ [setQuotes],
+ );
+
+ if (quotes.length === 0) {
+ return null;
+ }
+
+ const isMulti = quotes.length > 1;
+
+ return (
+ <div
+ className="flex flex-wrap gap-1.5 px-2 pt-2"
+ role="list"
+ aria-label={localize('com_ui_quotes_queued')}
+ data-testid="pending-quote-chips"
+ data-quote-count={quotes.length}
+ >
+ {!isMulti ? (
+ <span role="listitem" className={CHIP_CLASS}>
+ <TextQuote className="h-4 w-4 shrink-0 text-cyan-500" aria-hidden="true" />
+ <span className="max-w-[16rem] truncate" title={quotes[0]}>
+ {quotes[0]}
+ </span>
+ <button
+ type="button"
+ aria-label={localize('com_ui_remove_quote')}
+ onClick={clearAll}
+ className={REMOVE_BTN_CLASS}
+ >
+ <X className="h-3.5 w-3.5" aria-hidden="true" />
+ </button>
+ </span>
+ ) : (
+ <>
+ <span
+ role="listitem"
+ className={CHIP_CLASS}
+ onPointerEnter={openByPointer}
+ onPointerLeave={scheduleClose}
+ >
+ <Ariakit.PopoverDisclosure
+ store={popover}
+ className={TRIGGER_CLASS}
+ aria-label={localize('com_ui_quote_selections', { 0: quotes.length })}
+ onClick={() => setFocusOnShow(true)}
+ >
+ <TextQuote className="h-4 w-4 shrink-0 text-cyan-500" aria-hidden="true" />
+ <span className="truncate">
+ {localize('com_ui_quote_selections', { 0: quotes.length })}
+ </span>
+ </Ariakit.PopoverDisclosure>
+ <button
+ type="button"
+ aria-label={localize('com_ui_remove_all_quotes')}
+ onClick={clearAll}
+ className={REMOVE_BTN_CLASS}
+ >
+ <X className="h-3.5 w-3.5" aria-hidden="true" />
+ </button>
+ </span>
+ <Ariakit.Popover
+ store={popover}
+ portal
+ gutter={8}
+ autoFocusOnShow={focusOnShow}
+ data-testid="quote-selections-popup"
+ onPointerEnter={cancelClose}
+ onPointerLeave={scheduleClose}
+ className="z-50 w-80 max-w-[90vw] rounded-xl border border-border-light bg-surface-secondary p-2 text-text-primary shadow-lg outline-none"
+ >
+ <ul className="flex flex-col gap-1" aria-label={localize('com_ui_referenced_quotes')}>
+ {quotes.map((text, index) => (
+ <li
+ key={`${index}-${text.slice(0, 24)}`}
+ className="flex items-start gap-1.5 rounded-xl px-1.5 py-1 hover:bg-surface-tertiary"
+ >
+ <TextQuote
+ className="mt-0.5 h-3.5 w-3.5 shrink-0 text-text-tertiary"
+ aria-hidden="true"
+ />
+ <span className="line-clamp-2 flex-1 whitespace-pre-wrap break-words text-sm text-text-secondary">
+ {text}
+ </span>
+ <button
+ type="button"
+ aria-label={localize('com_ui_remove_quote')}
+ onClick={() => removeAt(index)}
+ className="mt-0.5 shrink-0 rounded-full p-0.5 text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-xheavy"
+ >
+ <X className="h-3.5 w-3.5" aria-hidden="true" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ </Ariakit.Popover>
+ </>
+ )}
+ </div>
+ );
+}
+
+export default memo(PendingQuoteChips);
diff --git a/client/src/components/Chat/Input/QuoteButton.tsx b/client/src/components/Chat/Input/QuoteButton.tsx
new file mode 100644
index 0000000000..e2caef8a4a
--- /dev/null
+++ b/client/src/components/Chat/Input/QuoteButton.tsx
@@ -0,0 +1,168 @@
+import { memo, useRef, useState, useEffect, useCallback, useLayoutEffect } from 'react';
+import { createPortal } from 'react-dom';
+import { TextQuote } from 'lucide-react';
+import { useSetRecoilState } from 'recoil';
+import { mainTextareaId } from '~/common';
+import { useLocalize } from '~/hooks';
+import store from '~/store';
+
+/** Only selections fully inside a rendered chat message get the popup. */
+const MESSAGE_SELECTOR = '.message-render';
+/** Max characters captured per excerpt (backend re-caps as defense-in-depth). */
+const MAX_QUOTE_LENGTH = 1500;
+/** Max excerpts queued at once; mirrors the backend `QUOTE_MAX_COUNT` cap so
+ * the composer never shows more quotes than the model actually receives. */
+const MAX_QUOTE_COUNT = 10;
+/** Vertical gap (px) between the selection and the popup. */
+const POPUP_OFFSET = 8;
+/** Keep the popup this far (px) from the viewport edges. */
+const EDGE_MARGIN = 16;
+
+type SelectionState = {
+ text: string;
+ /** Viewport-relative anchor of the selection (used to place the button). */
+ top: number;
+ bottom: number;
+ centerX: number;
+};
+
+const resolveMessageElement = (node: Node | null): HTMLElement | null => {
+ const element = node instanceof Element ? node : (node?.parentElement ?? null);
+ return (element?.closest(MESSAGE_SELECTOR) as HTMLElement | null) ?? null;
+};
+
+const readSelection = (): SelectionState | null => {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
+ return null;
+ }
+
+ const anchorMessage = resolveMessageElement(selection.anchorNode);
+ const focusMessage = resolveMessageElement(selection.focusNode);
+ if (!anchorMessage || anchorMessage !== focusMessage) {
+ return null;
+ }
+
+ const text = selection
+ .toString()
+ .replace(/\u00a0/g, ' ')
+ .trim();
+ if (text.length === 0) {
+ return null;
+ }
+
+ const rect = selection.getRangeAt(0).getBoundingClientRect();
+ if (rect.width === 0 && rect.height === 0) {
+ return null;
+ }
+
+ return {
+ text: text.slice(0, MAX_QUOTE_LENGTH),
+ top: rect.top,
+ bottom: rect.bottom,
+ centerX: rect.left + rect.width / 2,
+ };
+};
+
+/**
+ * ChatGPT-style floating "Add to chat" button. Watches for text selections
+ * inside chat messages and, on click, appends the selected excerpt to the
+ * conversation's pending-quotes queue so it shows as a removable chip above
+ * the composer and rides along with the next submission.
+ *
+ * Rendered through a portal so the `fixed` positioning stays viewport-relative
+ * regardless of any transformed ancestor in the composer tree. The on-screen
+ * position is computed from the button's measured size (no CSS transform), so it
+ * is clamped accurately to the viewport — flipping below the selection when
+ * there is no room above and keeping its full width within the side margins.
+ */
+function QuoteButton({ conversationId }: { conversationId: string }) {
+ const localize = useLocalize();
+ const [selection, setSelection] = useState<SelectionState | null>(null);
+ const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+ const setQuotes = useSetRecoilState(store.pendingQuotesByConvoId(conversationId));
+
+ useEffect(() => {
+ const updateSelection = () => {
+ setSelection(readSelection());
+ /** Recompute placement from scratch for the new selection. */
+ setPos(null);
+ };
+ const clearSelection = () => setSelection(null);
+
+ document.addEventListener('mouseup', updateSelection);
+ document.addEventListener('keyup', updateSelection);
+ document.addEventListener('scroll', clearSelection, true);
+ window.addEventListener('resize', clearSelection);
+
+ return () => {
+ document.removeEventListener('mouseup', updateSelection);
+ document.removeEventListener('keyup', updateSelection);
+ document.removeEventListener('scroll', clearSelection, true);
+ window.removeEventListener('resize', clearSelection);
+ };
+ }, []);
+
+ /** Clamp using the button's real size so it never lands off-screen. Runs
+ * before paint, so the first visible frame is already in its final spot. */
+ useLayoutEffect(() => {
+ if (!selection || !buttonRef.current) {
+ return;
+ }
+ const { width, height } = buttonRef.current.getBoundingClientRect();
+ const maxLeft = Math.max(EDGE_MARGIN, window.innerWidth - width - EDGE_MARGIN);
+ const left = Math.min(Math.max(selection.centerX - width / 2, EDGE_MARGIN), maxLeft);
+
+ const aboveTop = selection.top - POPUP_OFFSET - height;
+ const belowTop = selection.bottom + POPUP_OFFSET;
+ const maxTop = Math.max(EDGE_MARGIN, window.innerHeight - height - EDGE_MARGIN);
+ const top = aboveTop >= EDGE_MARGIN ? aboveTop : Math.min(belowTop, maxTop);
+
+ setPos({ top: Math.max(top, EDGE_MARGIN), left });
+ }, [selection]);
+
+ const addQuote = useCallback(() => {
+ if (!selection) {
+ return;
+ }
+ setQuotes((prev) =>
+ prev.includes(selection.text) || prev.length >= MAX_QUOTE_COUNT
+ ? prev
+ : [...prev, selection.text],
+ );
+ setSelection(null);
+ setPos(null);
+ window.getSelection()?.removeAllRanges();
+ document.getElementById(mainTextareaId)?.focus();
+ }, [selection, setQuotes]);
+
+ if (!selection) {
+ return null;
+ }
+
+ return createPortal(
+ <button
+ ref={buttonRef}
+ type="button"
+ /** Keep the selection alive while the click lands. */
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={addQuote}
+ aria-label={localize('com_ui_add_to_chat')}
+ data-testid="add-to-chat-button"
+ style={{
+ top: pos?.top ?? 0,
+ left: pos?.left ?? 0,
+ /** Hidden until measured so it never flashes at an unclamped position. */
+ visibility: pos == null ? 'hidden' : 'visible',
+ }}
+ className="fixed z-50 inline-flex items-center gap-1.5 rounded-full border border-border-light bg-surface-secondary px-3 py-1.5 text-sm font-medium text-text-primary shadow-lg transition-colors hover:bg-surface-tertiary"
+ >
+ <TextQuote className="h-4 w-4" aria-hidden="true" />
+ {localize('com_ui_add_to_chat')}
+ </button>,
+ document.body,
+ );
+}
+
+export default memo(QuoteButton);
diff --git a/client/src/components/Chat/Input/__tests__/PendingQuoteChips.test.tsx b/client/src/components/Chat/Input/__tests__/PendingQuoteChips.test.tsx
new file mode 100644
index 0000000000..6e863cf372
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/PendingQuoteChips.test.tsx
@@ -0,0 +1,57 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { render, screen, fireEvent } from '@testing-library/react';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string, params?: Record<string, unknown>) =>
+ `${key}:${params?.[0] ?? ''}`,
+}));
+
+import store from '~/store';
+import PendingQuoteChips from '../PendingQuoteChips';
+
+const CONVO_ID = 'convo-1';
+
+const renderWithQuotes = (quotes: string[]) =>
+ render(
+ <RecoilRoot initializeState={({ set }) => set(store.pendingQuotesByConvoId(CONVO_ID), quotes)}>
+ <PendingQuoteChips conversationId={CONVO_ID} />
+ </RecoilRoot>,
+ );
+
+describe('PendingQuoteChips', () => {
+ it('renders nothing when there are no pending quotes', () => {
+ const { container } = renderWithQuotes([]);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('shows the excerpt text for a single selection', () => {
+ renderWithQuotes(['alpha excerpt']);
+ const chips = screen.getByTestId('pending-quote-chips');
+ expect(chips).toHaveAttribute('data-quote-count', '1');
+ expect(chips).toHaveTextContent('alpha excerpt');
+ });
+
+ it('collapses multiple selections into a single "{n} selections" chip', () => {
+ renderWithQuotes(['alpha excerpt', 'beta excerpt']);
+ const chips = screen.getByTestId('pending-quote-chips');
+ expect(chips).toHaveAttribute('data-quote-count', '2');
+ // Collapsed label (the localize mock renders "<key>:<count>").
+ expect(chips).toHaveTextContent('com_ui_quote_selections:2');
+ // The composer shows ONE chip, not a row of two (the per-excerpt list lives
+ // in the hover popup, which only mounts on hover).
+ expect(screen.getAllByRole('listitem')).toHaveLength(1);
+ });
+
+ it('removes the single selection when its × is clicked', () => {
+ const { container } = renderWithQuotes(['only one']);
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_remove_quote/ }));
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('clears all selections from the collapsed chip', () => {
+ const { container } = renderWithQuotes(['first', 'second']);
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_remove_all_quotes/ }));
+ expect(container.firstChild).toBeNull();
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/Container.tsx b/client/src/components/Chat/Messages/Content/Container.tsx
index 7d5f842511..042dc68c2f 100644
--- a/client/src/components/Chat/Messages/Content/Container.tsx
+++ b/client/src/components/Chat/Messages/Content/Container.tsx
@@ -1,6 +1,7 @@
import { TMessage } from 'librechat-data-provider';
-import Files from './Files';
+import MessageQuotes from './MessageQuotes';
import SkillPills from './SkillPills';
+import Files from './Files';
const Container = ({ children, message }: { children: React.ReactNode; message?: TMessage }) => (
<div
@@ -9,6 +10,7 @@ const Container = ({ children, message }: { children: React.ReactNode; message?:
>
{message?.isCreatedByUser === true && (
<>
+ <MessageQuotes quotes={message.quotes} />
<Files message={message} />
<SkillPills skills={message.alwaysAppliedSkills} source="always-apply" />
<SkillPills skills={message.manualSkills} source="manual" />
diff --git a/client/src/components/Chat/Messages/Content/EditMessage.tsx b/client/src/components/Chat/Messages/Content/EditMessage.tsx
index 53fa4f8800..2030c5ffc9 100644
--- a/client/src/components/Chat/Messages/Content/EditMessage.tsx
+++ b/client/src/components/Chat/Messages/Content/EditMessage.tsx
@@ -1,6 +1,6 @@
import { useRef, useEffect, useCallback } from 'react';
-import { useForm } from 'react-hook-form';
import { useRecoilValue } from 'recoil';
+import { useForm } from 'react-hook-form';
import { TextareaAutosize, TooltipAnchor } from '@librechat/client';
import { useUpdateMessageMutation } from 'librechat-data-provider/react-query';
import type { TEditProps } from '~/common';
@@ -65,6 +65,9 @@ const EditMessage = ({
* carry the picks forward so the new turn primes the same skills
* instead of running unprimed. */
overrideManualSkills: message.manualSkills,
+ /** Carry the edited user message's quoted excerpts forward so the new
+ * turn sends the same referenced context the pills still show. */
+ overrideQuotes: message.quotes,
addedConvo: getAddedConvo() || undefined,
},
);
@@ -88,6 +91,9 @@ const EditMessage = ({
* the same manual skills so the regenerated response is primed
* identically. */
overrideManualSkills: parentMessage.manualSkills,
+ /** Replaying the parent user turn: keep its quoted excerpts so the
+ * regenerated response is sent the same referenced context. */
+ overrideQuotes: parentMessage.quotes,
addedConvo: getAddedConvo() || undefined,
},
);
diff --git a/client/src/components/Chat/Messages/Content/MessageQuotes.tsx b/client/src/components/Chat/Messages/Content/MessageQuotes.tsx
new file mode 100644
index 0000000000..5298c03f5d
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/MessageQuotes.tsx
@@ -0,0 +1,46 @@
+import { memo } from 'react';
+import { TextQuote } from 'lucide-react';
+import { useLocalize } from '~/hooks';
+
+/**
+ * Renders the verbatim excerpts a user quoted on a submitted message as
+ * compact reference blocks above the message text. Presentational — takes
+ * only the scalar `quotes` array (not the full message) so `React.memo`
+ * comparisons on parent wrappers stay shallow.
+ *
+ * The backend persists `message.quotes`, so callers pass
+ * `quotes={message.quotes}` and the references survive reload and history
+ * renders, mirroring how `SkillPills` reads `message.manualSkills`.
+ */
+function MessageQuotes({ quotes }: { quotes?: string[] }) {
+ const localize = useLocalize();
+
+ if (!quotes || quotes.length === 0) {
+ return null;
+ }
+
+ return (
+ <div
+ className="flex w-full flex-col gap-1.5"
+ role="list"
+ aria-label={localize('com_ui_referenced_quotes')}
+ data-testid="message-quotes"
+ >
+ {quotes.map((text, index) => (
+ <div
+ key={`${index}-${text.slice(0, 24)}`}
+ role="listitem"
+ className="flex items-start gap-1.5 rounded-2xl border border-border-light bg-surface-secondary px-2.5 py-1.5 text-sm text-text-secondary"
+ >
+ <TextQuote
+ className="mt-0.5 h-3.5 w-3.5 shrink-0 text-text-tertiary"
+ aria-hidden="true"
+ />
+ <span className="line-clamp-3 whitespace-pre-wrap break-words">{text}</span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export default memo(MessageQuotes);
diff --git a/client/src/components/Chat/Messages/Content/__tests__/MessageQuotes.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/MessageQuotes.test.tsx
new file mode 100644
index 0000000000..7cb2e753cb
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/MessageQuotes.test.tsx
@@ -0,0 +1,38 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+import MessageQuotes from '../MessageQuotes';
+
+describe('MessageQuotes', () => {
+ it('renders nothing when quotes is undefined', () => {
+ const { container } = render(<MessageQuotes />);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('renders nothing when quotes is empty', () => {
+ const { container } = render(<MessageQuotes quotes={[]} />);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('renders one reference block per quote, preserving text', () => {
+ render(<MessageQuotes quotes={['first excerpt', 'second excerpt']} />);
+ const items = screen.getAllByRole('listitem');
+ expect(items).toHaveLength(2);
+ expect(items[0]).toHaveTextContent('first excerpt');
+ expect(items[1]).toHaveTextContent('second excerpt');
+ });
+
+ it('localizes the list aria-label', () => {
+ render(<MessageQuotes quotes={['excerpt']} />);
+ expect(screen.getByRole('list')).toHaveAttribute('aria-label', 'com_ui_referenced_quotes');
+ });
+
+ it('renders duplicate quote strings as separate blocks', () => {
+ render(<MessageQuotes quotes={['same', 'same']} />);
+ expect(screen.getAllByRole('listitem')).toHaveLength(2);
+ });
+});
diff --git a/client/src/components/Chat/Messages/ui/MessageRender.tsx b/client/src/components/Chat/Messages/ui/MessageRender.tsx
index c285d68b27..3fc1879a5b 100644
--- a/client/src/components/Chat/Messages/ui/MessageRender.tsx
+++ b/client/src/components/Chat/Messages/ui/MessageRender.tsx
@@ -82,7 +82,8 @@ function areMessageRenderPropsEqual(prev: MessageRenderProps, next: MessageRende
prevMsg.endpoint === nextMsg.endpoint &&
prevMsg.iconURL === nextMsg.iconURL &&
prevMsg.feedback?.rating === nextMsg.feedback?.rating &&
- (prevMsg.files?.length ?? 0) === (nextMsg.files?.length ?? 0)
+ (prevMsg.files?.length ?? 0) === (nextMsg.files?.length ?? 0) &&
+ (prevMsg.quotes?.length ?? 0) === (nextMsg.quotes?.length ?? 0)
);
}
diff --git a/client/src/components/Messages/ContentRender.tsx b/client/src/components/Messages/ContentRender.tsx
index 7473e2768c..10800aff0f 100644
--- a/client/src/components/Messages/ContentRender.tsx
+++ b/client/src/components/Messages/ContentRender.tsx
@@ -82,7 +82,8 @@ function areContentRenderPropsEqual(prev: ContentRenderProps, next: ContentRende
prevMsg.feedback?.rating === nextMsg.feedback?.rating &&
(prevMsg.attachments?.length ?? 0) === (nextMsg.attachments?.length ?? 0) &&
(prevMsg.manualSkills?.length ?? 0) === (nextMsg.manualSkills?.length ?? 0) &&
- (prevMsg.alwaysAppliedSkills?.length ?? 0) === (nextMsg.alwaysAppliedSkills?.length ?? 0)
+ (prevMsg.alwaysAppliedSkills?.length ?? 0) === (nextMsg.alwaysAppliedSkills?.length ?? 0) &&
+ (prevMsg.quotes?.length ?? 0) === (nextMsg.quotes?.length ?? 0)
);
}
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index e7fda4758f..50578ac428 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -239,6 +239,25 @@ export default function useChatFunctions({
[],
);
+ /**
+ * Atomically read + reset the per-conversation queue of quoted excerpts the
+ * user added via the "Add to chat" selection popup. Mirrors
+ * `drainPendingManualSkills`: a single snapshot read + reset so excerpts
+ * added between here and submission are never lost into a reset atom.
+ */
+ const drainPendingQuotes = useRecoilCallback(
+ ({ snapshot, reset }) =>
+ (convoId: string): string[] => {
+ const loadable = snapshot.getLoadable(store.pendingQuotesByConvoId(convoId));
+ const quotes = loadable.state === 'hasValue' ? (loadable.contents as string[]) : [];
+ if (quotes.length > 0) {
+ reset(store.pendingQuotesByConvoId(convoId));
+ }
+ return quotes;
+ },
+ [],
+ );
+
const ask: TAskFunction = (
{
text,
@@ -258,6 +277,7 @@ export default function useChatFunctions({
overrideFiles,
targetResponseMessageId,
overrideManualSkills,
+ overrideQuotes,
addedConvo,
} = {},
) => {
@@ -314,6 +334,27 @@ export default function useChatFunctions({
? []
: drainPendingManualSkills(conversationId ?? Constants.NEW_CONVO);
}
+ /**
+ * Quoted-excerpt resolution mirrors manual skills, but is skipped entirely
+ * for Assistants endpoints: those bypass the `BaseClient` merge, so the
+ * quote UI is hidden there and a selection queued on another endpoint must
+ * not silently ride along on a fresh submit. The pending atom is left
+ * untouched so the queue survives if the user switches back.
+ * - Explicit `overrideQuotes` wins (regenerate / resubmit replay the
+ * original user message's persisted quotes so the same context is sent).
+ * - Regenerate / continue / edit without an override → empty (those flows
+ * replay a prior turn; the compose-time atom is left untouched).
+ * - Fresh submit → drain the per-convo atom into the message.
+ */
+ const quotesSupported = !isAssistantsEndpoint(endpoint);
+ let quotes: string[] = [];
+ if (quotesSupported) {
+ if (overrideQuotes != null) {
+ quotes = overrideQuotes;
+ } else if (!isRegenerate && !isContinued && !isEdited) {
+ quotes = drainPendingQuotes(conversationId ?? Constants.NEW_CONVO);
+ }
+ }
const isEditOrContinue = isEdited || isContinued;
let currentMessages: TMessage[] = overrideMessages ?? getMessages() ?? [];
@@ -431,6 +472,13 @@ export default function useChatFunctions({
* skill resolution reads the top-level `manualSkills` payload field.
*/
manualSkills: manualSkills.length > 0 ? manualSkills : undefined,
+ /**
+ * Quoted excerpts the user referenced this turn. Persisted on the
+ * message (backend echoes it back on `req.body.quotes`) so `MessageQuotes`
+ * renders the references on the user bubble after reload. The backend
+ * also merges these into the model-facing user text at request time.
+ */
+ quotes: quotes.length > 0 ? quotes : undefined,
};
const submissionFiles = overrideFiles ?? targetParentMessage?.files;
@@ -609,6 +657,9 @@ export default function useChatFunctions({
* this the model sees an unprimed turn even though the pills
* still show on the user bubble. */
overrideManualSkills: parentMessage.manualSkills,
+ /** Carry the original user message's quoted excerpts forward so the
+ * regenerated response is sent the same referenced context. */
+ overrideQuotes: parentMessage.quotes,
},
);
} else {
diff --git a/client/src/hooks/Config/useClearStates.ts b/client/src/hooks/Config/useClearStates.ts
index 2958107194..0303d3b558 100644
--- a/client/src/hooks/Config/useClearStates.ts
+++ b/client/src/hooks/Config/useClearStates.ts
@@ -32,6 +32,18 @@ export default function useClearStates() {
reset(store.showPromptsPopoverFamily(key));
reset(store.showSkillsPopoverFamily(key));
reset(store.pendingManualSkillsByConvoId(key.toString()));
+ reset(store.pendingQuotesByConvoId(key.toString()));
+ /**
+ * Pending skill/quote queues are keyed by the conversation id the
+ * composer wrote under, not this UI index — also clear by the resolved
+ * id so queued-but-unsent selections don't linger in Recoil.
+ */
+ const convoId = (await snapshot.getPromise(store.conversationByIndex(key)))
+ ?.conversationId;
+ if (convoId != null) {
+ reset(store.pendingManualSkillsByConvoId(convoId));
+ reset(store.pendingQuotesByConvoId(convoId));
+ }
reset(store.activePromptByIndex(key));
reset(store.globalAudioURLFamily(key));
reset(store.globalAudioFetchingFamily(key));
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index a01db036c9..2d6a0bb822 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef } from 'react';
import { v4 } from 'uuid';
-import { useSetRecoilState } from 'recoil';
import { useQueryClient } from '@tanstack/react-query';
+import { useSetRecoilState, useRecoilCallback } from 'recoil';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import {
QueryKeys,
@@ -283,6 +283,19 @@ export default function useEventHandlers({
const navigate = useNavigate();
const location = useLocation();
+ /** Re-queue the turn's quoted excerpts when an early abort restores the draft,
+ * so retrying the restored message still sends the references — the pending
+ * queue was already drained on submit. */
+ const restorePendingQuotes = useRecoilCallback(
+ ({ set }) =>
+ (convoId: string, quotes?: string[]) => {
+ if (Array.isArray(quotes) && quotes.length > 0) {
+ set(store.pendingQuotesByConvoId(convoId), quotes);
+ }
+ },
+ [],
+ );
+
const lastAnnouncementTimeRef = useRef(Date.now());
const { conversationId: paramId } = useParams();
const { token } = useAuthContext();
@@ -659,6 +672,7 @@ export default function useEventHandlers({
abortMessages,
);
setDraft({ id: currentConvoId, value: requestMessage?.text });
+ restorePendingQuotes(currentConvoId, requestMessage?.quotes);
return;
}
@@ -670,6 +684,7 @@ export default function useEventHandlers({
setMessages([]);
queryClient.setQueryData<TMessage[]>([QueryKeys.messages, Constants.NEW_CONVO], []);
setDraft({ id: String(Constants.NEW_CONVO), value: requestMessage?.text });
+ restorePendingQuotes(String(Constants.NEW_CONVO), requestMessage?.quotes);
if (location.pathname !== `/c/${Constants.NEW_CONVO}`) {
navigate(`/c/${Constants.NEW_CONVO}`, { replace: true });
}
@@ -734,6 +749,7 @@ export default function useEventHandlers({
setFinalMessages(currentConvoId, isNewChat ? [] : [...messages]);
setDraft({ id: currentConvoId, value: requestMessage?.text });
+ restorePendingQuotes(currentConvoId, requestMessage?.quotes);
if (isNewChat) {
navigate(`/c/${Constants.NEW_CONVO}`, { replace: true, state: { focusChat: true } });
}
@@ -864,6 +880,7 @@ export default function useEventHandlers({
location.pathname,
applyAgentTemplate,
attachmentHandler,
+ restorePendingQuotes,
],
);
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index c39544bc91..27036505c5 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -669,6 +669,7 @@
"com_ui_add_model_preset": "Add a model or preset for an additional response",
"com_ui_add_multi_conversation": "Add multi-conversation",
"com_ui_add_skills": "Add Skills",
+ "com_ui_add_to_chat": "Add to chat",
"com_ui_add_special_variables": "Add Special Variables",
"com_ui_add_web_search_api_keys": "Add Web Search API Keys",
"com_ui_adding_details": "Adding details",
@@ -1433,12 +1434,15 @@
"com_ui_ran_n_agents": "Ran {{0}} agents",
"com_ui_read_aloud": "Read aloud",
"com_ui_read_file": "Read {{0}}",
+ "com_ui_quote_selections": "{{0}} selections",
+ "com_ui_quotes_queued": "Quotes added for your next message",
"com_ui_reading_file": "Reading {{0}}",
"com_ui_redirect_uri": "Redirect URI",
"com_ui_redirect_uri_instructions": "Copy this redirect URI and configure it in your OAuth provider settings.",
"com_ui_redirecting_to_provider": "Redirecting to {{0}}, please wait...",
"com_ui_reference_saved_memories": "Reference saved memories",
"com_ui_reference_saved_memories_description": "Allow the assistant to reference and use your saved memories when responding",
+ "com_ui_referenced_quotes": "Referenced quotes",
"com_ui_refresh": "Refresh",
"com_ui_refresh_link": "Refresh link",
"com_ui_refresh_page": "Refresh page",
@@ -1461,7 +1465,9 @@
"com_ui_remote_agents_allow_share_public": "Allow users to grant API access to agents to all users",
"com_ui_remote_agents_allow_use": "Allow users to create API keys and query agents remotely",
"com_ui_remove_agent_from_chain": "Remove {{0}} from chain",
+ "com_ui_remove_all_quotes": "Remove all selections",
"com_ui_remove_from_project": "Remove from project",
+ "com_ui_remove_quote": "Remove quote",
"com_ui_remove_skill_var": "Remove {{0}}",
"com_ui_remove_user": "Remove {{0}}",
"com_ui_rename": "Rename",
diff --git a/client/src/store/families.ts b/client/src/store/families.ts
index 54a2294fb5..c4ad8221f5 100644
--- a/client/src/store/families.ts
+++ b/client/src/store/families.ts
@@ -1,5 +1,6 @@
import { useEffect } from 'react';
import { createSearchParams } from 'react-router-dom';
+import { LocalStorageKeys, isEphemeralAgentId, Constants } from 'librechat-data-provider';
import {
atom,
selector,
@@ -10,7 +11,6 @@ import {
useSetRecoilState,
useRecoilCallback,
} from 'recoil';
-import { LocalStorageKeys, isEphemeralAgentId, Constants } from 'librechat-data-provider';
import type { EModelEndpoint, TConversation, TSubmission, TPreset } from 'librechat-data-provider';
import type { TOptionSettings, ExtendedFile } from '~/common';
import {
@@ -286,6 +286,20 @@ const pendingManualSkillsByConvoId = atomFamily<string[], string>({
default: [],
});
+/**
+ * Per-conversation queue of verbatim excerpts the user quoted via the
+ * "Add to chat" selection popup for the next submission. The submit pipeline
+ * (`useChatFunctions.ask`) drains this onto the user message's `quotes` field
+ * (which the backend merges into the model-facing text and persists for the
+ * `MessageQuotes` UI), then resets to `[]`. Compose-time chips above the
+ * textarea read this atom directly so users can see and dismiss each quote
+ * before sending.
+ */
+const pendingQuotesByConvoId = atomFamily<string[], string>({
+ key: 'pendingQuotesByConvoId',
+ default: [],
+});
+
const globalAudioURLFamily = atomFamily<string | null, string | number | null>({
key: 'globalAudioURLByIndex',
default: null,
@@ -451,5 +465,6 @@ export default {
showPromptsPopoverFamily,
showSkillsPopoverFamily,
pendingManualSkillsByConvoId,
+ pendingQuotesByConvoId,
updateConversationSelector,
};
diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.js
index c2ce714b56..54b786f3e6 100644
--- a/e2e/setup/fake-model.js
+++ b/e2e/setup/fake-model.js
@@ -20,6 +20,7 @@ const CREATE_SKILL_MARKER = 'E2E_CREATE_SKILL:';
const EDIT_SKILL_MARKER = 'E2E_EDIT_SKILL:';
const ASSERT_MODEL_SPEC_SKILLS_MARKER = 'E2E_ASSERT_MODEL_SPEC_SKILLS';
const ASSERT_PROVIDER_FILE_MARKER = 'E2E_ASSERT_PROVIDER_FILE:';
+const ASSERT_QUOTE_MARKER = 'E2E_ASSERT_QUOTE:';
const REPLY_MARKER = 'E2E_REPLY:';
const COUNTED_REPLY_MARKER = 'E2E_COUNTED_REPLY:';
const SLOW_REPLY_MARKER = 'E2E_SLOW_REPLY:';
@@ -31,6 +32,7 @@ const CREATE_FILE_AUTHORING_FINAL_TEXT = 'E2E file authoring complete';
const EDIT_FILE_AUTHORING_FINAL_TEXT = 'E2E file edit complete';
const MODEL_SPEC_SKILL_ASSERTION_FINAL_TEXT = 'E2E model spec skill assertion passed';
const PROVIDER_FILE_ASSERTION_FINAL_TEXT = 'E2E provider file assertion passed';
+const QUOTE_ASSERTION_FINAL_TEXT = 'E2E quote assertion passed';
const SLOW_CHUNK_DELAY_MS = Number(process.env.MOCK_LLM_SLOW_CHUNK_DELAY_MS) || 35;
const SLOW_REPLY_CHUNKS = 160;
const RESUME_ICON_CHUNK_DELAY_MS = Number(process.env.MOCK_LLM_RESUME_ICON_CHUNK_DELAY_MS) || 60;
@@ -232,6 +234,37 @@ function providerFileAssertionResponses({ messages, text }) {
};
}
+/**
+ * Verifies the quote feature end to end: scans every user message in the prompt
+ * the model actually received for a Markdown blockquote line containing the
+ * expected token. Passing proves the excerpt was merged into the model-facing
+ * turn — covering both the current turn and durable re-merge of a prior quoted
+ * turn from history (the merge runs in `AgentClient.buildMessages`).
+ */
+function quoteAssertionResponses({ messages, text }) {
+ const expected = getMarkerValue(text, ASSERT_QUOTE_MARKER);
+ if (!expected) {
+ return null;
+ }
+
+ const found = (messages ?? []).some((message) => {
+ const type = messageType(message);
+ if (type !== 'human' && type !== 'user') {
+ return false;
+ }
+ return getContentText(message.content)
+ .split('\n')
+ .some((line) => line.startsWith('> ') && line.includes(expected));
+ });
+
+ if (found) {
+ return { responses: [`${QUOTE_ASSERTION_FINAL_TEXT}: ${expected}`] };
+ }
+ return {
+ responses: [`E2E quote assertion failed: no blockquote containing "${expected}" in the prompt`],
+ };
+}
+
function replyResponses(text) {
if (text.includes(MARKDOWN_REPLY_MARKER)) {
return {
@@ -483,6 +516,11 @@ function resolveResponses({ agents, messages, text, toolNames }) {
return providerFileAssertion;
}
+ const quoteAssertion = quoteAssertionResponses({ messages, text });
+ if (quoteAssertion) {
+ return quoteAssertion;
+ }
+
if (text.includes(ASSERT_MODEL_SPEC_SKILLS_MARKER)) {
return modelSpecSkillAssertionResponses({ agents, messages, toolNames });
}
diff --git a/e2e/specs/mock/quotes.spec.ts b/e2e/specs/mock/quotes.spec.ts
new file mode 100644
index 0000000000..25ffe34d60
--- /dev/null
+++ b/e2e/specs/mock/quotes.spec.ts
@@ -0,0 +1,218 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import {
+ MOCK_ENDPOINTS,
+ MOCK_REPLY_TEXT,
+ NEW_CHAT_PATH,
+ messagesView,
+ mockReply,
+ selectMockEndpoint,
+ sendMessage,
+} from './helpers';
+
+/**
+ * Place a real DOM Selection over `needle` inside the most recent
+ * `.message-render` that contains it, then dispatch `mouseup` so the
+ * `QuoteButton` listener fires — the deterministic equivalent of a user
+ * drag-selecting that text to summon the "Add to chat" popup.
+ */
+async function selectMessageText(page: Page, needle: string) {
+ await page.evaluate((text) => {
+ const renders = Array.from(document.querySelectorAll('.message-render'));
+ const host = [...renders].reverse().find((el) => (el.textContent ?? '').includes(text));
+ if (!host) {
+ throw new Error(`No message contains: ${text}`);
+ }
+ const walker = document.createTreeWalker(host, NodeFilter.SHOW_TEXT);
+ let node = walker.nextNode();
+ while (node) {
+ const value = node.nodeValue ?? '';
+ const index = value.indexOf(text);
+ if (index !== -1) {
+ const range = document.createRange();
+ range.setStart(node, index);
+ range.setEnd(node, index + text.length);
+ const selection = window.getSelection();
+ if (!selection) {
+ throw new Error('Selection API unavailable');
+ }
+ selection.removeAllRanges();
+ selection.addRange(range);
+ document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
+ return;
+ }
+ node = walker.nextNode();
+ }
+ throw new Error(`No text node contains: ${text}`);
+ }, needle);
+}
+
+const addToChat = (page: Page) => page.getByTestId('add-to-chat-button');
+const pendingChips = (page: Page) => page.getByTestId('pending-quote-chips');
+const messageQuotes = (page: Page) => messagesView(page).getByTestId('message-quotes');
+
+/** The mock model echoes this when a blockquote containing the token reached the prompt. */
+const QUOTE_ASSERTION_PASSED = 'E2E quote assertion passed: reply';
+
+/**
+ * Select `needle` inside a message and add it as a quote, asserting the pending
+ * chip count reaches `expectedCount`. Retried as a unit: a pending selection is
+ * dismissed on any scroll/layout shift (e.g. auto-scroll after a new message),
+ * which is correct UX but races with a scripted select+click — `toPass` re-runs
+ * the select+click until the chip commits. Dedup keeps re-runs idempotent.
+ */
+async function addQuote(page: Page, needle: string, expectedCount: number) {
+ await expect(async () => {
+ await selectMessageText(page, needle);
+ const button = addToChat(page);
+ await expect(button).toBeVisible({ timeout: 3000 });
+ await button.click();
+ await expect(pendingChips(page)).toHaveAttribute('data-quote-count', String(expectedCount));
+ }).toPass({ timeout: 30000 });
+}
+
+test.describe('quote references', () => {
+ test('merges a quoted excerpt into the model turn, pins it to the message, and persists across reload', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ // Seed an assistant reply to quote.
+ let response = await sendMessage(page, 'seed for quote');
+ expect(response.ok()).toBeTruthy();
+ await expect(mockReply(page)).toBeVisible({ timeout: 20000 });
+
+ // Select the reply text -> popup -> chip above the composer.
+ await addQuote(page, MOCK_REPLY_TEXT, 1);
+ await expect(pendingChips(page)).toContainText(MOCK_REPLY_TEXT);
+
+ // Send a turn that asks the mock model to confirm the quote reached the prompt.
+ response = await sendMessage(page, 'E2E_ASSERT_QUOTE:reply');
+ expect(response.ok()).toBeTruthy();
+
+ // The model received the merged blockquote (verified server-side by the mock).
+ await expect(messagesView(page).getByText(QUOTE_ASSERTION_PASSED)).toBeVisible({
+ timeout: 20000,
+ });
+ // Pending chips drained; the reference is pinned to the sent user message.
+ await expect(pendingChips(page)).toHaveCount(0);
+ await expect(messageQuotes(page)).toContainText(MOCK_REPLY_TEXT);
+
+ // Round-trips through the DB: still pinned after reload.
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+ const conversationUrl = page.url();
+ await page.reload({ timeout: 10000 });
+ await expect(page).toHaveURL(conversationUrl);
+ await expect(messageQuotes(page)).toContainText(MOCK_REPLY_TEXT);
+ });
+
+ test('collapses multiple selections into one chip with a hover popup, and removes one', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const firstMessage = 'quote target alpha';
+ const popup = page.getByTestId('quote-selections-popup');
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ const response = await sendMessage(page, firstMessage);
+ expect(response.ok()).toBeTruthy();
+ await expect(mockReply(page)).toBeVisible({ timeout: 20000 });
+
+ // First the assistant reply, then the user's own message.
+ await addQuote(page, MOCK_REPLY_TEXT, 1);
+ await addQuote(page, firstMessage, 2);
+
+ // Composer shows a single collapsed "2 selections" chip, not a row of two.
+ await expect(pendingChips(page)).toContainText('2 selections');
+
+ // Hovering the collapsed chip reveals a popup listing every excerpt.
+ await pendingChips(page).getByRole('listitem').hover();
+ await expect(popup).toBeVisible({ timeout: 5000 });
+ await expect(popup).toContainText(MOCK_REPLY_TEXT);
+ await expect(popup).toContainText(firstMessage);
+
+ // Remove the reply from the popup; one selection remains and collapses back
+ // to its excerpt text.
+ await popup
+ .getByRole('listitem')
+ .filter({ hasText: MOCK_REPLY_TEXT })
+ .getByRole('button', { name: /remove quote/i })
+ .click();
+ await expect(pendingChips(page)).toHaveAttribute('data-quote-count', '1');
+ await expect(pendingChips(page)).toContainText(firstMessage);
+ await expect(pendingChips(page)).not.toContainText(MOCK_REPLY_TEXT);
+
+ // Send; only the remaining quote pins to the new user message.
+ const followUp = await sendMessage(page, 'expand on this');
+ expect(followUp.ok()).toBeTruthy();
+ await expect(messageQuotes(page)).toContainText(firstMessage);
+ await expect(messageQuotes(page)).not.toContainText(MOCK_REPLY_TEXT);
+ });
+
+ test('opens the selections popup via keyboard and closes on Escape', async ({ page }) => {
+ test.setTimeout(120000);
+ const firstMessage = 'quote target beta';
+ const popup = page.getByTestId('quote-selections-popup');
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ const response = await sendMessage(page, firstMessage);
+ expect(response.ok()).toBeTruthy();
+ await expect(mockReply(page)).toBeVisible({ timeout: 20000 });
+ await addQuote(page, MOCK_REPLY_TEXT, 1);
+ await addQuote(page, firstMessage, 2);
+
+ // The collapsed pill is a focusable disclosure: focus + Enter opens it.
+ const trigger = pendingChips(page).getByRole('button', { name: '2 selections' });
+ await trigger.focus();
+ await expect(trigger).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expect(popup).toBeVisible({ timeout: 5000 });
+ await expect(popup).toContainText(MOCK_REPLY_TEXT);
+ await expect(popup).toContainText(firstMessage);
+
+ // Opening via keyboard moves focus into the popup (first excerpt's remove ×).
+ await expect(popup.getByRole('button').first()).toBeFocused();
+
+ // Escape closes it and returns focus to the composer (NOT the page top, the
+ // bug this guards against). `document.activeElement` must be a real control.
+ await page.keyboard.press('Escape');
+ await expect(popup).toBeHidden();
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeFocused();
+ const focusTag = await page.evaluate(() => document.activeElement?.tagName ?? 'NONE');
+ expect(focusTag).not.toBe('BODY');
+ });
+
+ test('re-merges a persisted quote into later-turn history (durable)', async ({ page }) => {
+ test.setTimeout(120000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ // Turn 1: quote the assistant reply and send a (labeled) message carrying it.
+ let response = await sendMessage(page, 'seed for durable');
+ expect(response.ok()).toBeTruthy();
+ await expect(mockReply(page)).toBeVisible({ timeout: 20000 });
+ await addQuote(page, MOCK_REPLY_TEXT, 1);
+ response = await sendMessage(page, 'E2E_REPLY:carryquote');
+ expect(response.ok()).toBeTruthy();
+ // Wait for turn 1's generation to fully finish before sending again — a new
+ // submit is blocked while the prior turn is still streaming.
+ await expect(messagesView(page).getByText('E2E reply carryquote')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect(messageQuotes(page)).toContainText(MOCK_REPLY_TEXT);
+
+ // Turn 2: no new quote. The prior quoted turn must be re-merged into history,
+ // so the model still receives the blockquote on this later turn.
+ response = await sendMessage(page, 'E2E_ASSERT_QUOTE:reply');
+ expect(response.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(QUOTE_ASSERTION_PASSED)).toBeVisible({
+ timeout: 20000,
+ });
+ });
+});
diff --git a/packages/api/src/agents/client.spec.ts b/packages/api/src/agents/client.spec.ts
index ab2c32ac24..0b77831926 100644
--- a/packages/api/src/agents/client.spec.ts
+++ b/packages/api/src/agents/client.spec.ts
@@ -1,5 +1,5 @@
import { ContentTypes } from 'librechat-data-provider';
-import { prependFileContext, type FormattedMessageWithContent } from './client';
+import { prependFileContext, prependQuotes, type FormattedMessageWithContent } from './client';
describe('prependFileContext', () => {
it('prepends file context to string content', () => {
@@ -52,3 +52,64 @@ describe('prependFileContext', () => {
expect(message.content).toBe('Answer this question.');
});
});
+
+describe('prependQuotes', () => {
+ it('prepends a single quote as a blockquote to string content', () => {
+ const message: FormattedMessageWithContent = { content: 'Explain this.' };
+
+ prependQuotes(message, ['the selected text']);
+
+ expect(message.content).toBe('> the selected text\n\nExplain this.');
+ });
+
+ it('separates multiple quotes with a blank line', () => {
+ const message: FormattedMessageWithContent = { content: 'Compare these.' };
+
+ prependQuotes(message, ['first', 'second']);
+
+ expect(message.content).toBe('> first\n\n> second\n\nCompare these.');
+ });
+
+ it('prepends to the first text part of array content, leaving other parts intact', () => {
+ const message: FormattedMessageWithContent = {
+ content: [
+ { type: ContentTypes.IMAGE_URL, image_url: { url: 'data:image/png;base64,abc' } },
+ { type: ContentTypes.TEXT, text: 'Explain this.' },
+ ],
+ };
+
+ prependQuotes(message, ['excerpt']);
+
+ if (!Array.isArray(message.content)) {
+ throw new Error('Expected array content');
+ }
+ expect(message.content[1].text).toBe('> excerpt\n\nExplain this.');
+ expect(message.content[0]).toEqual({
+ type: ContentTypes.IMAGE_URL,
+ image_url: { url: 'data:image/png;base64,abc' },
+ });
+ });
+
+ it('adds a text part when an array has none', () => {
+ const message: FormattedMessageWithContent = {
+ content: [{ type: ContentTypes.IMAGE_URL, image_url: { url: 'data:image/png;base64,abc' } }],
+ };
+
+ prependQuotes(message, ['excerpt']);
+
+ expect(message.content).toEqual([
+ { type: ContentTypes.TEXT, text: '> excerpt' },
+ { type: ContentTypes.IMAGE_URL, image_url: { url: 'data:image/png;base64,abc' } },
+ ]);
+ });
+
+ it('leaves content unchanged when there are no quotes', () => {
+ const message: FormattedMessageWithContent = { content: 'Explain this.' };
+
+ prependQuotes(message, []);
+ expect(message.content).toBe('Explain this.');
+
+ prependQuotes(message, null);
+ expect(message.content).toBe('Explain this.');
+ });
+});
diff --git a/packages/api/src/agents/client.ts b/packages/api/src/agents/client.ts
index f758df9745..4adf953bfb 100644
--- a/packages/api/src/agents/client.ts
+++ b/packages/api/src/agents/client.ts
@@ -11,8 +11,8 @@ import type { BaseMessage } from '@librechat/agents/langchain/messages';
import type { MessageContentComplex } from '@librechat/agents';
import type { Agent, TMessage } from 'librechat-data-provider';
import type { ServerRequest } from '~/types';
+import { logAxiosError, mergeQuotedText, formatQuotesAsMarkdown } from '~/utils';
import Tokenizer from '~/utils/tokenizer';
-import { logAxiosError } from '~/utils';
export const omitTitleOptions: Set<string> = new Set([
'stream',
@@ -98,6 +98,44 @@ export function prependFileContext(
formattedMessage.content.unshift({ type: ContentTypes.TEXT, text: fileContext });
}
+/**
+ * Prepends quoted excerpts (the "Add to chat" selections persisted on
+ * `message.quotes`) to a formatted message's content as Markdown blockquotes.
+ * Applied to every user message that carries quotes — current and historical —
+ * so the model durably receives the referenced context and the token count
+ * stays consistent with what was persisted. The stored `message.text` is left
+ * clean; the excerpts live on `message.quotes` for the UI.
+ */
+export function prependQuotes(
+ formattedMessage: FormattedMessageWithContent,
+ quotes?: string[] | null,
+): void {
+ if (quotes == null || quotes.length === 0) {
+ return;
+ }
+ const block = formatQuotesAsMarkdown(quotes);
+ if (block.length === 0) {
+ return;
+ }
+
+ if (typeof formattedMessage.content === 'string') {
+ formattedMessage.content = mergeQuotedText(formattedMessage.content, quotes);
+ return;
+ }
+
+ if (!Array.isArray(formattedMessage.content)) {
+ return;
+ }
+
+ const textPart = formattedMessage.content.find((part) => part.type === ContentTypes.TEXT);
+ if (textPart != null && typeof textPart.text === 'string') {
+ textPart.text = mergeQuotedText(textPart.text, quotes);
+ return;
+ }
+
+ formattedMessage.content.unshift({ type: ContentTypes.TEXT, text: block });
+}
+
function estimateImageDataTokens(data: string, isClaude: boolean): number {
const dims = extractImageDimensions(data);
if (dims == null) {
diff --git a/packages/api/src/endpoints/projection.ts b/packages/api/src/endpoints/projection.ts
index 62bc40dfed..365cccc4e8 100644
--- a/packages/api/src/endpoints/projection.ts
+++ b/packages/api/src/endpoints/projection.ts
@@ -2,6 +2,7 @@ import { HumanMessage, AIMessage } from '@langchain/core/messages';
import { Providers, createTokenCounter, projectAgentContextUsage } from '@librechat/agents';
import type { TContextProjectionRequest, TContextUsageEvent } from 'librechat-data-provider';
import type { BaseMessage } from '@langchain/core/messages';
+import { mergeQuotedText } from '~/utils/quotes';
interface ProjectionMessage {
messageId: string;
@@ -9,6 +10,9 @@ interface ProjectionMessage {
tokenCount?: number;
isCreatedByUser?: boolean;
text?: string;
+ /** Quoted excerpts merged into the model-facing text by the live path; must be
+ * included here so the context gauge counts the same prompt the model sees. */
+ quotes?: string[];
/** Compaction marker written by the live path (`agents/usage.ts`); its
* presence means the next call sends the summary + tail, not this raw chain. */
metadata?: { summaryUsedTokens?: number };
@@ -93,7 +97,7 @@ export async function resolveContextProjection(
const stored = await deps.getMessages(
{ conversationId: params.conversationId, user: deps.userId },
- 'messageId parentMessageId tokenCount isCreatedByUser text metadata',
+ 'messageId parentMessageId tokenCount isCreatedByUser text quotes metadata',
);
const branch = resolveBranch(stored, params.messageId);
if (branch.length === 0) {
@@ -118,15 +122,25 @@ export async function resolveContextProjection(
const indexTokenCountMap: Record<string, number> = {};
for (let i = 0; i < branch.length; i++) {
const message = branch[i];
- const text = message.text ?? '';
+ /** Mirror the live path: prepend quoted excerpts into the user text the model
+ * receives so the gauge counts the same prompt. */
+ const hasQuotes =
+ message.isCreatedByUser === true &&
+ Array.isArray(message.quotes) &&
+ message.quotes.length > 0;
+ const text = hasQuotes
+ ? mergeQuotedText(message.text ?? '', message.quotes ?? [])
+ : (message.text ?? '');
const lcMessage =
message.isCreatedByUser === true ? new HumanMessage(text) : new AIMessage(text);
messages.push(lcMessage);
/** Recount messages with no stored count (imported / pre-feature) rather
* than charging 0 — a real 0 and "unknown" must not collapse, or the
- * snapshot-less histories this endpoint targets would under-report. */
+ * snapshot-less histories this endpoint targets would under-report. Also
+ * recount quoted messages: a text-only Save edit leaves a stale text-only
+ * `tokenCount` that omits the quote block, so trust the merged recount. */
indexTokenCountMap[String(i)] =
- message.tokenCount != null && message.tokenCount > 0
+ !hasQuotes && message.tokenCount != null && message.tokenCount > 0
? message.tokenCount
: tokenCounter(lcMessage);
}
diff --git a/packages/api/src/middleware/messageFilterPii.spec.ts b/packages/api/src/middleware/messageFilterPii.spec.ts
index e942886536..c67227ff2d 100644
--- a/packages/api/src/middleware/messageFilterPii.spec.ts
+++ b/packages/api/src/middleware/messageFilterPii.spec.ts
@@ -134,6 +134,52 @@ describe('messageFilterPii middleware', () => {
expect(capturedRes.status).toBe(400);
});
+ it('rejects with 400 when a quoted excerpt contains a blocked token (clean text)', () => {
+ const { capturedRes, nextCalls } = runMiddleware(
+ {},
+ { text: 'explain this', quotes: ['leaked sk-proj-FAKE1234567890ABCDEF here'] },
+ );
+ expect(nextCalls).toBe(0);
+ expect(capturedRes.status).toBe(400);
+ expect(capturedRes.body).toMatchObject({ error: 'message_filter_pii_block' });
+ });
+
+ it('scans quotes even when req.body.text is empty', () => {
+ const { capturedRes, nextCalls } = runMiddleware(
+ {},
+ { text: '', quotes: ['api-key: foo123bar'] },
+ );
+ expect(nextCalls).toBe(0);
+ expect(capturedRes.status).toBe(400);
+ });
+
+ it('rejects a secret split across a quote and the typed text (merged scan)', () => {
+ // Neither piece matches the api-key pattern alone, but the merged
+ // `> api-key:\n\nsecret` the model receives does (the pattern allows whitespace).
+ const { capturedRes, nextCalls } = runMiddleware({}, { text: 'secret', quotes: ['api-key:'] });
+ expect(nextCalls).toBe(0);
+ expect(capturedRes.status).toBe(400);
+ expect(capturedRes.body).toMatchObject({ error: 'message_filter_pii_block' });
+ });
+
+ it('passes through when neither text nor quotes match', () => {
+ const { capturedRes, nextCalls } = runMiddleware(
+ {},
+ { text: 'hello world', quotes: ['a clean excerpt', 'another clean one'] },
+ );
+ expect(nextCalls).toBe(1);
+ expect(capturedRes.status).toBeUndefined();
+ });
+
+ it('ignores non-string quote entries without throwing', () => {
+ const { capturedRes, nextCalls } = runMiddleware(
+ {},
+ { text: 'hello world', quotes: [null, 42, '', 'clean'] },
+ );
+ expect(nextCalls).toBe(1);
+ expect(capturedRes.status).toBeUndefined();
+ });
+
it('returns the same compiled pattern array for repeat calls with the same config (memoization)', () => {
const config: MessageFilterPiiConfig = {
customPatterns: [{ id: 'org', label: 'Org token', regex: '\\bORG-[A-Z0-9]{6,}' }],
diff --git a/packages/api/src/middleware/messageFilterPii.ts b/packages/api/src/middleware/messageFilterPii.ts
index 91c8e6ba66..ff322cba8f 100644
--- a/packages/api/src/middleware/messageFilterPii.ts
+++ b/packages/api/src/middleware/messageFilterPii.ts
@@ -6,6 +6,7 @@ import type {
Response as ServerResponse,
} from 'express';
import type { MessageFilterPiiConfig } from 'librechat-data-provider';
+import { getReferencedQuotes, mergeQuotedText } from '../utils/quotes';
type CompiledPattern = { id: string; label: string; pattern: RegExp };
@@ -122,8 +123,25 @@ export function createMessageFilterPii(options: CreateMessageFilterPiiOptions):
next();
return;
}
- const text = req.body?.text;
- if (typeof text !== 'string' || text.length === 0) {
+ /**
+ * Scan the typed text, each quoted excerpt, and — crucially — the merged
+ * blockquote+text exactly as `AgentClient` sends it to the model. Quotes are
+ * normalized via `getReferencedQuotes` first (matching `BaseClient`). Scanning
+ * the merged string catches a secret split across a quote and the typed text
+ * (each clean alone) that only matches once concatenated; scanning the raw
+ * pieces keeps anchored patterns working against un-prefixed excerpts.
+ */
+ const candidates: string[] = [];
+ const text = typeof req.body?.text === 'string' ? req.body.text : '';
+ if (text.length > 0) {
+ candidates.push(text);
+ }
+ const quotes = getReferencedQuotes(req.body?.quotes);
+ if (quotes != null) {
+ candidates.push(...quotes);
+ candidates.push(mergeQuotedText(text, quotes));
+ }
+ if (candidates.length === 0) {
next();
return;
}
@@ -132,14 +150,16 @@ export function createMessageFilterPii(options: CreateMessageFilterPiiOptions):
next();
return;
}
- const match = findMatch(text, patterns);
- if (match == null) {
- next();
- return;
+ for (const candidate of candidates) {
+ const match = findMatch(candidate, patterns);
+ if (match != null) {
+ res.status(400).json({
+ error: 'message_filter_pii_block',
+ message: `Message contains a ${match.label}. Remove it and try again.`,
+ });
+ return;
+ }
}
- res.status(400).json({
- error: 'message_filter_pii_block',
- message: `Message contains a ${match.label}. Remove it and try again.`,
- });
+ next();
};
}
diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.ts
index 4445417c5c..42b396bd30 100644
--- a/packages/api/src/stream/GenerationJobManager.ts
+++ b/packages/api/src/stream/GenerationJobManager.ts
@@ -778,6 +778,7 @@ class GenerationJobManagerClass {
parentMessageId: jobData.userMessage.parentMessageId,
conversationId: jobData.conversationId,
text: jobData.userMessage.text ?? '',
+ quotes: jobData.userMessage.quotes,
isCreatedByUser: true,
}
: null,
@@ -1348,6 +1349,7 @@ class GenerationJobManagerClass {
parentMessageId: message.parentMessageId,
conversationId: message.conversationId,
text: message.text,
+ quotes: message.quotes,
},
};
diff --git a/packages/api/src/stream/interfaces/IJobStore.ts b/packages/api/src/stream/interfaces/IJobStore.ts
index fcb472c7cd..f2e905e4fa 100644
--- a/packages/api/src/stream/interfaces/IJobStore.ts
+++ b/packages/api/src/stream/interfaces/IJobStore.ts
@@ -25,6 +25,9 @@ export interface SerializableJobData {
parentMessageId?: string;
conversationId?: string;
text?: string;
+ /** Quoted excerpts referenced on this turn, carried so resumable/aborted
+ * reconstructions of the user message keep their `MessageQuotes`. */
+ quotes?: string[];
};
/** Response message ID for reconnection */
diff --git a/packages/api/src/types/events.ts b/packages/api/src/types/events.ts
index d068888b17..360929d034 100644
--- a/packages/api/src/types/events.ts
+++ b/packages/api/src/types/events.ts
@@ -14,6 +14,9 @@ export type CreatedEvent = {
text?: string;
sender: string;
isCreatedByUser: boolean;
+ /** Quoted excerpts referenced on this turn, carried through resumable job
+ * metadata so reconstructed user messages keep their `MessageQuotes`. */
+ quotes?: string[];
};
streamId: string;
};
diff --git a/packages/api/src/utils/__tests__/quotes.test.ts b/packages/api/src/utils/__tests__/quotes.test.ts
new file mode 100644
index 0000000000..54d8e9dcdb
--- /dev/null
+++ b/packages/api/src/utils/__tests__/quotes.test.ts
@@ -0,0 +1,63 @@
+import { QUOTE_MAX_COUNT, QUOTE_MAX_LENGTH, mergeQuotedText, getReferencedQuotes } from '../quotes';
+
+describe('getReferencedQuotes', () => {
+ it('returns null for non-array input', () => {
+ expect(getReferencedQuotes(undefined)).toBeNull();
+ expect(getReferencedQuotes(null)).toBeNull();
+ expect(getReferencedQuotes('quote')).toBeNull();
+ expect(getReferencedQuotes({ 0: 'quote' })).toBeNull();
+ });
+
+ it('returns null when nothing usable remains', () => {
+ expect(getReferencedQuotes([])).toBeNull();
+ expect(getReferencedQuotes(['', ' ', 42, null])).toBeNull();
+ });
+
+ it('trims, drops empties/non-strings, and keeps order', () => {
+ expect(getReferencedQuotes([' hello ', '', 7, 'world'])).toEqual(['hello', 'world']);
+ });
+
+ it('caps each excerpt to QUOTE_MAX_LENGTH', () => {
+ const long = 'a'.repeat(QUOTE_MAX_LENGTH + 50);
+ const result = getReferencedQuotes([long]);
+ expect(result).not.toBeNull();
+ expect(result?.[0]).toHaveLength(QUOTE_MAX_LENGTH);
+ });
+
+ it('caps the number of excerpts to QUOTE_MAX_COUNT', () => {
+ const many = Array.from({ length: QUOTE_MAX_COUNT + 5 }, (_, i) => `q${i}`);
+ expect(getReferencedQuotes(many)).toHaveLength(QUOTE_MAX_COUNT);
+ });
+});
+
+describe('mergeQuotedText', () => {
+ it('returns the original text when there are no quotes', () => {
+ expect(mergeQuotedText('hello', [])).toBe('hello');
+ });
+
+ it('prepends a single quote as a Markdown blockquote', () => {
+ expect(mergeQuotedText('What does this mean?', ['the selected text'])).toBe(
+ '> the selected text\n\nWhat does this mean?',
+ );
+ });
+
+ it('prefixes every line of a multi-line excerpt', () => {
+ expect(mergeQuotedText('explain', ['line one\nline two'])).toBe(
+ '> line one\n> line two\n\nexplain',
+ );
+ });
+
+ it('renders empty lines within an excerpt as bare blockquote markers', () => {
+ expect(mergeQuotedText('explain', ['a\n\nb'])).toBe('> a\n>\n> b\n\nexplain');
+ });
+
+ it('separates multiple excerpts with a blank line', () => {
+ expect(mergeQuotedText('compare these', ['first', 'second'])).toBe(
+ '> first\n\n> second\n\ncompare these',
+ );
+ });
+
+ it('returns just the blockquote when the user text is empty', () => {
+ expect(mergeQuotedText('', ['only quote'])).toBe('> only quote');
+ });
+});
diff --git a/packages/api/src/utils/index.ts b/packages/api/src/utils/index.ts
index f801ec236d..a0bc2510b3 100644
--- a/packages/api/src/utils/index.ts
+++ b/packages/api/src/utils/index.ts
@@ -29,4 +29,5 @@ export * from './tokens';
export * from './tokenMap';
export * from './url';
export * from './message';
+export * from './quotes';
export * from './tracing';
diff --git a/packages/api/src/utils/quotes.ts b/packages/api/src/utils/quotes.ts
new file mode 100644
index 0000000000..877ff5aafe
--- /dev/null
+++ b/packages/api/src/utils/quotes.ts
@@ -0,0 +1,69 @@
+/** Max characters kept per quoted excerpt (defense-in-depth over the client cap). */
+export const QUOTE_MAX_LENGTH = 1500;
+
+/** Max number of quoted excerpts merged into a single user turn. */
+export const QUOTE_MAX_COUNT = 10;
+
+/**
+ * Normalizes the `quotes` field off a request body into a clean string array.
+ * Trims, drops empties/non-strings, caps each excerpt length and the overall
+ * count. Returns `null` when there is nothing usable so callers can skip the
+ * merge entirely.
+ */
+export function getReferencedQuotes(raw: unknown): string[] | null {
+ if (!Array.isArray(raw)) {
+ return null;
+ }
+
+ const quotes: string[] = [];
+ for (const item of raw) {
+ if (typeof item !== 'string') {
+ continue;
+ }
+ const trimmed = item.trim();
+ if (trimmed.length === 0) {
+ continue;
+ }
+ quotes.push(trimmed.slice(0, QUOTE_MAX_LENGTH));
+ if (quotes.length >= QUOTE_MAX_COUNT) {
+ break;
+ }
+ }
+
+ return quotes.length > 0 ? quotes : null;
+}
+
+/** Formats one excerpt as a Markdown blockquote, prefixing every line. */
+function toBlockquote(quote: string): string {
+ return quote
+ .split('\n')
+ .map((line) => (line.length > 0 ? `> ${line}` : '>'))
+ .join('\n');
+}
+
+/**
+ * Renders quoted excerpts as Markdown blockquote blocks, one block per excerpt
+ * separated by a blank line. Provider-agnostic (no bespoke tags). Returns an
+ * empty string when there are no quotes.
+ */
+export function formatQuotesAsMarkdown(quotes: string[]): string {
+ return quotes.map(toBlockquote).join('\n\n');
+}
+
+/**
+ * Merges quoted excerpts into a body of text as Markdown blockquotes, prepended
+ * before the text so the excerpts read as part of the user turn. Returns the
+ * original text unchanged when there are no quotes.
+ */
+export function mergeQuotedText(text: string, quotes: string[]): string {
+ if (quotes.length === 0) {
+ return text;
+ }
+
+ const block = formatQuotesAsMarkdown(quotes);
+ if (block.length === 0) {
+ return text;
+ }
+ const body = text ?? '';
+ return body.length > 0 ? `${block}\n\n${body}` : block;
+}
diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts
index 108968d350..3fafe292d8 100644
--- a/packages/data-provider/src/schemas.ts
+++ b/packages/data-provider/src/schemas.ts
@@ -813,6 +813,14 @@ export const tMessageSchema = z.object({
* what actually ran, not the current catalog).
*/
alwaysAppliedSkills: z.array(z.string()).optional(),
+ /**
+ * Verbatim excerpts the user quoted (via the "Add to chat" selection
+ * popup) to reference on this turn. UI metadata that `MessageQuotes`
+ * renders above the user bubble so the references persist on reload. The
+ * excerpts are merged into the user message text sent to the model at
+ * request time and counted in the user message token count.
+ */
+ quotes: z.array(z.string()).optional(),
});
export type MemoryArtifact = {
diff --git a/packages/data-schemas/src/methods/share.test.ts b/packages/data-schemas/src/methods/share.test.ts
index 63b1ba207c..5f092fc26a 100644
--- a/packages/data-schemas/src/methods/share.test.ts
+++ b/packages/data-schemas/src/methods/share.test.ts
@@ -73,6 +73,7 @@ describe('Share Methods', () => {
feedback: mongoose.Schema.Types.Mixed,
manualSkills: [String],
alwaysAppliedSkills: [String],
+ quotes: [String],
parentMessageId: String,
attachments: [mongoose.Schema.Types.Mixed],
files: [mongoose.Schema.Types.Mixed],
@@ -458,6 +459,7 @@ describe('Share Methods', () => {
feedback: { rating: 'thumbsDown', tag: { key: 'inaccurate' }, text: 'private note' },
manualSkills: ['research'],
alwaysAppliedSkills: ['brand-voice'],
+ quotes: ['the quoted excerpt'],
files: [
{
file_id: 'file123',
@@ -511,6 +513,8 @@ describe('Share Methods', () => {
// Skill badges are non-sensitive UI metadata and should still render.
expect(shared?.manualSkills).toEqual(['research']);
expect(shared?.alwaysAppliedSkills).toEqual(['brand-voice']);
+ // Quoted excerpts are non-sensitive UI metadata and should still render in the share view.
+ expect(shared?.quotes).toEqual(['the quoted excerpt']);
// Render metadata (filename/type/dims) is kept, storage internals dropped. The
// file isn't snapshotted (no backing File record), so its original render URL is
diff --git a/packages/data-schemas/src/methods/share.ts b/packages/data-schemas/src/methods/share.ts
index 5bb297f197..f76cc0e29f 100644
--- a/packages/data-schemas/src/methods/share.ts
+++ b/packages/data-schemas/src/methods/share.ts
@@ -301,6 +301,7 @@ function anonymizeMessages(
finish_reason: message.finish_reason,
...(message.manualSkills && { manualSkills: message.manualSkills }),
...(message.alwaysAppliedSkills && { alwaysAppliedSkills: message.alwaysAppliedSkills }),
+ ...(message.quotes && { quotes: message.quotes }),
...(files && { files }),
...(attachments && { attachments }),
};
diff --git a/packages/data-schemas/src/schema/message.ts b/packages/data-schemas/src/schema/message.ts
index f4002d076c..d7fd3fafb0 100644
--- a/packages/data-schemas/src/schema/message.ts
+++ b/packages/data-schemas/src/schema/message.ts
@@ -142,6 +142,15 @@ const messageSchema: Schema<IMessage> = new Schema(
* the user bubble to preserve the audit trail of what actually ran.
*/
alwaysAppliedSkills: { type: [String], default: undefined },
+ /**
+ * Verbatim excerpts the user quoted (via the "Add to chat" selection
+ * popup) to reference on this turn. UI metadata only — `MessageQuotes`
+ * renders these on the user bubble so the references persist through
+ * reload and history. The excerpts are merged into the user message text
+ * sent to the model at request time (counted in the user message token
+ * count), so they are not duplicated into the stored `text`.
+ */
+ quotes: { type: [String], default: undefined },
/*
attachments: {
type: [
diff --git a/packages/data-schemas/src/types/message.ts b/packages/data-schemas/src/types/message.ts
index 16ec2a5ffb..96d9c1ff35 100644
--- a/packages/data-schemas/src/types/message.ts
+++ b/packages/data-schemas/src/types/message.ts
@@ -1,5 +1,5 @@
-import type { Document } from 'mongoose';
import type { TFeedbackRating, TFeedbackTag } from 'librechat-data-provider';
+import type { Document } from 'mongoose';
// @ts-ignore
export interface IMessage extends Document {
@@ -54,6 +54,8 @@ export interface IMessage extends Document {
* the current catalog says.
*/
alwaysAppliedSkills?: string[];
+ /** Verbatim excerpts the user quoted to reference on this turn. UI-only metadata for `MessageQuotes`. */
+ quotes?: string[];
expiredAt?: Date | null;
createdAt?: Date;
updatedAt?: Date;
diff --git a/packages/data-schemas/src/types/share.ts b/packages/data-schemas/src/types/share.ts
index 0636ddbf47..a7e9f030a8 100644
--- a/packages/data-schemas/src/types/share.ts
+++ b/packages/data-schemas/src/types/share.ts
@@ -85,6 +85,7 @@ export type SharedMessage = Pick<
| 'finish_reason'
| 'manualSkills'
| 'alwaysAppliedSkills'
+ | 'quotes'
> & {
model?: string;
files?: SharedFile[];