Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🗯️ fix: Give Failed Turns Actionable Guidance (#15896)
Marco Berettaf077e8c9677b
diff --git a/api/server/middleware/limiters/messageLimiters.js b/api/server/middleware/limiters/messageLimiters.jsindex 29d0a5ee14..62957585fc 100644--- a/api/server/middleware/limiters/messageLimiters.js+++ b/api/server/middleware/limiters/messageLimiters.js@@ -1,6 +1,6 @@const rateLimit = require('express-rate-limit');const { ViolationTypes } = require('librechat-data-provider');-const { limiterCache, removePorts } = require('@librechat/api');+const { limiterCache, removePorts, getRateLimitReset } = require('@librechat/api');const denyRequest = require('~/server/middleware/denyRequest');const { logViolation } = require('~/cache');@@ -36,6 +36,7 @@ const createHandler = (ip = true) => {max: ip ? ipMax : userMax,limiter: ip ? 'ip' : 'user',windowInMinutes: ip ? ipWindowInMinutes : userWindowInMinutes,+ ...getRateLimitReset(req.rateLimit, ip ? ipWindowMs : userWindowMs),};await logViolation(req, res, type, errorMessage, score);@@ -88,10 +89,10 @@ const agentEventUserLimiter = (req, res, next) => {windowMs: windowInMinutes * 60 * 1000,max,handler: (limitedReq, limitedRes) => {- const resetAt = limitedReq.rateLimit?.resetTime?.getTime?.();- const retryAfterSeconds = Number.isFinite(resetAt)- ? Math.max(1, Math.ceil((resetAt - Date.now()) / 1000))- : Math.max(1, Math.ceil(windowInMinutes * 60));+ const { retryAfterSeconds } = getRateLimitReset(+ limitedReq.rateLimit,+ windowInMinutes * 60 * 1000,+ );limitedRes.set('Retry-After', String(retryAfterSeconds));return limitedRes.status(429)diff --git a/api/server/middleware/limiters/messageLimiters.spec.js b/api/server/middleware/limiters/messageLimiters.spec.jsindex f177d98d72..28d1d56d32 100644--- a/api/server/middleware/limiters/messageLimiters.spec.js+++ b/api/server/middleware/limiters/messageLimiters.spec.js@@ -8,6 +8,8 @@ jest.mock('express-rate-limit', () => mockRateLimit);jest.mock('@librechat/api', () => ({limiterCache: jest.fn(() => ({})),removePorts: jest.fn(),+ getRateLimitReset: jest.requireActual('../../../../packages/api/src/utils/limiter.ts')+ .getRateLimitReset,}));jest.mock('~/server/middleware/denyRequest', () => jest.fn());jest.mock('~/cache', () => ({ logViolation: jest.fn() }));@@ -73,3 +75,63 @@ describe('agent event rate limiter', () => {expect(denyRequest).not.toHaveBeenCalled();});});++describe('message rate limiter violation payload', () => {+ let originalEnv;++ beforeEach(() => {+ originalEnv = { ...process.env };+ jest.resetModules();+ });++ afterEach(() => {+ process.env = originalEnv;+ jest.useRealTimers();+ jest.clearAllMocks();+ });++ /** The chat client counts down to this timestamp, so the persisted payload has to carry it. */+ it('persists the window reset alongside the limit it hit', async () => {+ jest.useFakeTimers({ now: Date.UTC(2026, 8, 13, 12, 0, 0) });+ process.env.MESSAGE_USER_MAX = '40';+ process.env.MESSAGE_USER_WINDOW = '60';+ require('./messageLimiters');+ const { logViolation } = require('~/cache');+ const denyRequest = require('~/server/middleware/denyRequest');+ const userOptions = mockRateLimit.mock.calls.at(-1)[0];+ const resetTime = new Date(Date.now() + 7 * 60 * 1000);+ const expected = expect.objectContaining({+ type: 'message_limit',+ limiter: 'user',+ windowInMinutes: 60,+ resetAt: resetTime.getTime(),+ retryAfterSeconds: 420,+ });++ await userOptions.handler({ rateLimit: { resetTime }, user: { id: 'user-1' } }, {});++ expect(logViolation.mock.calls.at(-1)[3]).toEqual(expected);+ expect(denyRequest.mock.calls.at(-1)[2]).toEqual(expected);+ });++ /** Without a populated `rateLimit`, the payload still has to name a reachable retry moment. */+ it('falls back to the configured window when the limiter reports no reset time', async () => {+ const now = Date.UTC(2026, 8, 13, 12, 0, 0);+ jest.useFakeTimers({ now });+ process.env.MESSAGE_IP_WINDOW = '1';+ require('./messageLimiters');+ const denyRequest = require('~/server/middleware/denyRequest');+ const ipOptions = mockRateLimit.mock.calls.at(-2)[0];++ await ipOptions.handler({}, {});++ expect(denyRequest.mock.calls.at(-1)[2]).toEqual(+ expect.objectContaining({+ limiter: 'ip',+ windowInMinutes: 1,+ resetAt: now + 60 * 1000,+ retryAfterSeconds: 60,+ }),+ );+ });+});diff --git a/client/src/components/Chat/Messages/Content/MessageContent.tsx b/client/src/components/Chat/Messages/Content/MessageContent.tsxindex a1291c76b1..f7f7545977 100644--- a/client/src/components/Chat/Messages/Content/MessageContent.tsx+++ b/client/src/components/Chat/Messages/Content/MessageContent.tsx@@ -48,7 +48,7 @@ const ErrorBox = ({role="alert"aria-live="assertive"className={cn(- 'rounded-xl border border-status-error-border bg-status-error-subtle px-3 py-2 text-sm text-text-secondary',+ 'rounded-xl border border-status-error-border bg-status-error-subtle p-3 text-sm text-text-secondary',className,)}>@@ -63,7 +63,14 @@ const ConnectionError = ({ message }: { message?: TMessage }) => {<Suspense fallback={<LoadingFallback />}><DelayedRender delay={DELAYED_ERROR_TIMEOUT}><Container message={message}>- <Alert variant="error" icon={false} className="mt-2 shadow-sm transition-all">+ {/* `text-text-secondary` overrides the variant's `text-status-error`: this card sits in+ the transcript beside `ErrorBox`, and every other failure there states itself in the+ ordinary copy color. The red border and fill still mark it as an error. */}+ <Alert+ variant="error"+ icon={false}+ className="mt-2 text-text-secondary shadow-sm transition-all"+ >{localize('com_ui_error_connection')}</Alert></Container>@@ -84,7 +91,7 @@ export const ErrorMessage = ({return (<Container message={message}><ErrorBox className={className}>- <Error text={text} />+ <Error text={text} message={message} /></ErrorBox></Container>);@@ -145,7 +152,16 @@ export const UnfinishedMessage = ({ message }: { message: TMessage }) => {);}- return <ErrorMessage message={message} text={localize('com_ui_response_incomplete')} />;+ /**+ * Copy this app authored, not a persisted failure: it goes straight into the error box. Routing+ * it through `Error` would have the unclassified-text path treat the sentence as provider prose+ * and headline it with "<provider> could not complete this request".+ */+ return (+ <Container message={message}>+ <ErrorBox>{localize('com_ui_response_incomplete')}</ErrorBox>+ </Container>+ );};const MessageContent = ({diff --git a/client/src/components/Chat/Messages/Content/SearchContent.tsx b/client/src/components/Chat/Messages/Content/SearchContent.tsxindex bc68ede95d..82a1a242e8 100644--- a/client/src/components/Chat/Messages/Content/SearchContent.tsx+++ b/client/src/components/Chat/Messages/Content/SearchContent.tsx@@ -10,9 +10,10 @@ import type {TMessageContentParts,} from 'librechat-data-provider';import type { ReactNode, ReactElement } from 'react';-import { UnfinishedMessage } from './MessageContent';+import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';+import { MessageContext, SearchContext, useMessageContext } from '~/Providers';+import { ErrorMessage, UnfinishedMessage } from './MessageContent';import { cn, mapAttachments } from '~/utils';-import { SearchContext } from '~/Providers';import MarkdownLite from './MarkdownLite';import { AgentUpdate } from './Parts';import store from '~/store';@@ -24,7 +25,7 @@ import Part from './Part';* `enableUserMsgMarkdown`. Callers that copy the message need the same answer.*/export const rendersMarkdownLite = (message: TMessage): boolean =>- !Array.isArray(message.content) || message.content.length === 0;+ message.error !== true && (!Array.isArray(message.content) || message.content.length === 0);const SearchContent = ({message,@@ -39,6 +40,7 @@ const SearchContent = ({authorHeader?: ReactNode;}) => {const enableUserMsgMarkdown = useRecoilValue(store.enableUserMsgMarkdown);+ const messageContext = useMessageContext();const { messageId } = message;const attachmentMap = useMemo(() => mapAttachments(attachments ?? []), [attachments]);@@ -51,55 +53,76 @@ const SearchContent = ({* `ContentParts`' `postSteerAuthors` scan. */let activeAgentId: string | undefined;return (- <SearchContext.Provider value={{ searchResults }}>- {parts.map((part: TMessageContentParts, idx: number) => {- const toolCallId =- (part?.[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined)?.id ?? '';- const partAttachments = attachmentMap[toolCallId];- const resumesAfterSteer =- authorHeader != null &&- idx > 0 &&- parts[idx - 1].type === ContentTypes.STEER &&- part.type !== ContentTypes.STEER;- const resumeAgentId = resumesAfterSteer ? activeAgentId : undefined;- if (part.type === ContentTypes.AGENT_UPDATE) {- activeAgentId = part[ContentTypes.AGENT_UPDATE]?.agentId || undefined;- }- const rendered: ReactElement = (- <Part- key={`display-${messageId}-${idx}`}- showCursor={false}- isSubmitting={false}- isCreatedByUser={message.isCreatedByUser}- attachments={partAttachments}- part={part}- />- );- if (!resumesAfterSteer) {- return rendered;- }- return (- <Fragment key={`display-${messageId}-${idx}`}>- {resumeAgentId != null ? (- <AgentUpdate currentAgentId={resumeAgentId} />+ <ErrorSourceProvider message={message}>+ <SearchContext.Provider value={{ searchResults }}>+ {parts.map((part: TMessageContentParts, idx: number) => {+ const toolCallId =+ (part?.[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined)?.id ?? '';+ const partAttachments = attachmentMap[toolCallId];+ const resumesAfterSteer =+ authorHeader != null &&+ idx > 0 &&+ parts[idx - 1].type === ContentTypes.STEER &&+ part.type !== ContentTypes.STEER;+ const resumeAgentId = resumesAfterSteer ? activeAgentId : undefined;+ if (part.type === ContentTypes.AGENT_UPDATE) {+ activeAgentId = part[ContentTypes.AGENT_UPDATE]?.agentId || undefined;+ }+ const partElement: ReactElement = (+ <Part+ key={`display-${messageId}-${idx}`}+ showCursor={false}+ isSubmitting={false}+ isCreatedByUser={message.isCreatedByUser}+ attachments={partAttachments}+ part={part}+ />+ );+ /** An error part resolves the agent a handoff made active from its own position,+ * which it reads from `MessageContext`; persisted content is compacted, so `idx` is+ * that position in `message.content`. */+ const rendered: ReactElement =+ part.type === ContentTypes.ERROR ? (+ <MessageContext.Provider+ key={`display-${messageId}-${idx}`}+ value={{ ...messageContext, partIndex: idx }}+ >+ {partElement}+ </MessageContext.Provider>) : (- authorHeader- )}- {rendered}- </Fragment>- );- })}- {message.unfinished === true && (- <Suspense>- <DelayedRender delay={250}>- <UnfinishedMessage message={message} key={`unfinished-${messageId}`} />- </DelayedRender>- </Suspense>- )}- </SearchContext.Provider>+ partElement+ );+ if (!resumesAfterSteer) {+ return rendered;+ }+ return (+ <Fragment key={`display-${messageId}-${idx}`}>+ {resumeAgentId != null ? (+ <AgentUpdate currentAgentId={resumeAgentId} />+ ) : (+ authorHeader+ )}+ {rendered}+ </Fragment>+ );+ })}+ {message.unfinished === true && (+ <Suspense>+ <DelayedRender delay={250}>+ <UnfinishedMessage message={message} key={`unfinished-${messageId}`} />+ </DelayedRender>+ </Suspense>+ )}+ </SearchContext.Provider>+ </ErrorSourceProvider>);}+ /** A failed row persists its failure as text, which only the error dispatcher can read. */+ if (message.error === true) {+ return <ErrorMessage message={message} text={message.text ?? ''} />;+ }+return (<divclassName={cn(diff --git a/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx b/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsxindex b4aeaca9a2..fe1c6234e6 100644--- a/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx+++ b/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx@@ -1,5 +1,5 @@import { useContext, useId, useState } from 'react';-import { Button } from '@librechat/client';+import { Button, TooltipAnchor } from '@librechat/client';import { FastForward, Gauge, MessageSquareText, X } from 'lucide-react';import type { TMessage } from 'librechat-data-provider';import { ChatContext } from '~/Providers/ChatContext';@@ -68,16 +68,22 @@ export default function ToolCallLimitNotice({ message }: { message: TMessage })aria-labelledby={titleId}className="relative my-2 flex w-full flex-col rounded-xl border border-border-light bg-surface-secondary p-3">- <Button- type="button"- variant="ghost"- size="icon-xs"- aria-label={localize('com_ui_dismiss')}- className="absolute right-1.5 top-1.5 text-text-secondary focus-visible:ring-inset focus-visible:ring-offset-0"- onClick={() => setDismissed(true)}- >- <X className="h-4 w-4" aria-hidden="true" />- </Button>+ <TooltipAnchor+ description={localize('com_ui_tool_call_limit_dismiss')}+ side="left"+ render={+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={localize('com_ui_tool_call_limit_dismiss')}+ className="absolute right-1.5 top-1.5 text-text-secondary focus-visible:ring-inset focus-visible:ring-offset-0"+ onClick={() => setDismissed(true)}+ >+ <X className="h-4 w-4" aria-hidden="true" />+ </Button>+ }+ /><pid={titleId}className="flex min-w-0 items-center gap-2 pr-8 text-sm font-medium text-text-primary"diff --git a/client/src/components/Chat/Messages/Content/__tests__/SearchContent.spec.tsx b/client/src/components/Chat/Messages/Content/__tests__/SearchContent.spec.tsxindex b342b65e9b..816c29b396 100644--- a/client/src/components/Chat/Messages/Content/__tests__/SearchContent.spec.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/SearchContent.spec.tsx@@ -1,21 +1,143 @@-import { ContentTypes } from 'librechat-data-provider';+import React from 'react';+import { RecoilRoot } from 'recoil';+import { render, screen } from '@testing-library/react';+import { ContentTypes, ErrorTypes, ViolationTypes } from 'librechat-data-provider';import type { TMessage, TMessageContentParts } from 'librechat-data-provider';-import { rendersMarkdownLite } from '~/components/Chat/Messages/Content/SearchContent';+import SearchContent, {+ rendersMarkdownLite,+} from '~/components/Chat/Messages/Content/SearchContent';-describe('rendersMarkdownLite', () => {- const message = (content?: TMessageContentParts[]): TMessage =>- ({ messageId: 'm', text: 'hi', content }) as TMessage;+jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++/** `Container` reads message context for sequential-agent layout; not under test. */+jest.mock('../Container', () => ({+ __esModule: true,+ default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+}));++/**+ * Stands in for the dispatcher so this spec asserts routing; its copy is `Error.spec.tsx`'s. It+ * reports both identities it could render with: the row it was handed and the surrounding source.+ */+jest.mock('~/components/Messages/Content/Error', () => {+ const { useErrorSource } = jest.requireActual('~/components/Messages/Content/Error/source');+ return {+ __esModule: true,+ default: function ErrorDispatcher({ text, message }: { text: string; message?: TMessage }) {+ const source = useErrorSource();+ return (+ <span+ data-testid="error-dispatcher"+ data-endpoint={message?.endpoint}+ data-source-endpoint={source?.endpoint}+ data-source-agent={source?.partAgentId}+ >+ {text}+ </span>+ );+ },+ };+});++jest.mock('../MarkdownLite', () => ({+ __esModule: true,+ default: ({ content }: { content: string }) => <div data-testid="markdown-lite">{content}</div>,+}));++const message = (overrides: Partial<TMessage> = {}): TMessage =>+ ({ messageId: 'm', text: 'hi', ...overrides }) as TMessage;+describe('rendersMarkdownLite', () => {it('is true when there are no content parts to render', () => {expect(rendersMarkdownLite(message())).toBe(true);- expect(rendersMarkdownLite(message([]))).toBe(true);+ expect(rendersMarkdownLite(message({ content: [] }))).toBe(true);});it('is false once content parts drive the rendering', () => {expect(rendersMarkdownLite(- message([{ type: ContentTypes.TEXT, text: 'hi' } as TMessageContentParts]),+ message({ content: [{ type: ContentTypes.TEXT, text: 'hi' } as TMessageContentParts] }),),).toBe(false);});++ it('is false for a failed row, which renders through the error dispatcher', () => {+ expect(rendersMarkdownLite(message({ error: true }))).toBe(false);+ });+});++describe('SearchContent', () => {+ /** Search and shared views persist no content parts for a failed turn, only its payload. */+ it('routes a failed row to the error dispatcher instead of rendering its payload', () => {+ const text = JSON.stringify({ type: ErrorTypes.NO_USER_KEY });+ render(+ <RecoilRoot>+ <SearchContent message={message({ error: true, text, endpoint: 'openAI' })} />+ </RecoilRoot>,+ );++ expect(screen.getByRole('alert')).toBeInTheDocument();+ expect(screen.getByTestId('error-dispatcher')).toHaveAttribute('data-endpoint', 'openAI');+ expect(screen.queryByTestId('markdown-lite')).not.toBeInTheDocument();+ });++ it('keeps rendering an ordinary text-only row as markdown', () => {+ render(+ <RecoilRoot>+ <SearchContent message={message({ text: 'A plain answer.' })} />+ </RecoilRoot>,+ );++ expect(screen.getByTestId('markdown-lite')).toHaveTextContent('A plain answer.');+ expect(screen.queryByTestId('error-dispatcher')).not.toBeInTheDocument();+ });++ /** `Part` renders an error part without its message, so the row has to supply its identity. */+ it("gives an error part its row's identity", () => {+ const text = JSON.stringify({ type: ViolationTypes.MESSAGE_LIMIT });+ render(+ <RecoilRoot>+ <SearchContent+ message={message({+ endpoint: 'anthropic',+ content: [{ type: ContentTypes.ERROR, error: text } as TMessageContentParts],+ })}+ />+ </RecoilRoot>,+ );++ const dispatcher = screen.getByTestId('error-dispatcher');+ expect(dispatcher).toHaveTextContent(text);+ expect(dispatcher).not.toHaveAttribute('data-endpoint');+ expect(dispatcher).toHaveAttribute('data-source-endpoint', 'anthropic');+ });++ it('resolves an error part after a handoff to the agent the run was handed to', () => {+ const text = JSON.stringify({ type: ViolationTypes.MESSAGE_LIMIT });+ render(+ <RecoilRoot>+ <SearchContent+ message={message({+ endpoint: 'agents',+ model: 'agent_root',+ content: [+ { type: ContentTypes.TEXT, text: 'Drafting the outline.' },+ {+ type: ContentTypes.AGENT_UPDATE,+ agent_update: { agentId: 'agent_writer', index: 1 },+ } as TMessageContentParts,+ { type: ContentTypes.ERROR, error: text } as TMessageContentParts,+ ] as TMessageContentParts[],+ })}+ />+ </RecoilRoot>,+ );++ expect(screen.getByTestId('error-dispatcher')).toHaveAttribute(+ 'data-source-agent',+ 'agent_writer',+ );+ });});diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallLimitNotice.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallLimitNotice.test.tsxindex 5deb83ef7b..8b983f6a08 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallLimitNotice.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallLimitNotice.test.tsx@@ -11,7 +11,7 @@ const TRANSLATIONS: Record<string, string> = {com_ui_tool_call_limit_continue_prompt: 'Keep going from where you stopped.',com_ui_tool_call_limit_answer: 'Answer now',com_ui_tool_call_limit_answer_prompt: 'Stop using tools and answer now.',- com_ui_dismiss: 'Dismiss',+ com_ui_tool_call_limit_dismiss: 'Dismiss',};jest.mock('~/hooks', () => ({@@ -100,7 +100,9 @@ describe('ToolCallLimitNotice', () => {).not.toBeInTheDocument();/** The explanation and the way to hide it must survive. */expect(screen.getByText(TRANSLATIONS.com_ui_tool_call_limit_body)).toBeInTheDocument();- expect(screen.getByRole('button', { name: 'Dismiss' })).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: TRANSLATIONS.com_ui_tool_call_limit_dismiss }),+ ).toBeInTheDocument();});it('offers no actions on a message that is not the branch tail', () => {@@ -124,7 +126,9 @@ describe('ToolCallLimitNotice', () => {it('can be dismissed', () => {renderNotice({ ask: jest.fn(), isSubmitting: false, latestMessageId: 'response-1' });- fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ fireEvent.click(+ screen.getByRole('button', { name: TRANSLATIONS.com_ui_tool_call_limit_dismiss }),+ );expect(screen.queryByText(TRANSLATIONS.com_ui_tool_call_limit_title)).not.toBeInTheDocument();});@@ -137,7 +141,9 @@ describe('ToolCallLimitNotice', () => {latestMessageId: 'response-1',});- fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ fireEvent.click(+ screen.getByRole('button', { name: TRANSLATIONS.com_ui_tool_call_limit_dismiss }),+ );expect(screen.queryByText(TRANSLATIONS.com_ui_tool_call_limit_title)).not.toBeInTheDocument();rerender(diff --git a/client/src/components/Chat/Messages/MessageParts.tsx b/client/src/components/Chat/Messages/MessageParts.tsxindex c3d4393455..eaacbc8d88 100644--- a/client/src/components/Chat/Messages/MessageParts.tsx+++ b/client/src/components/Chat/Messages/MessageParts.tsx@@ -11,6 +11,7 @@ import {} from '~/utils';import { useLocalize, useAttachments, useMessageHelpers, useContentMetadata } from '~/hooks';import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';+import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';import { getHeaderHoverLabel } from '~/components/Chat/Messages/ui/HeaderLabel';import { revealOnRowHoverClasses, messageFooterClasses } from './styles';import MessageRow from '~/components/Chat/Messages/ui/MessageRow';@@ -168,24 +169,26 @@ function MessageParts(props: TMessageProps) {</SubRow>}>- <ContentParts- edit={edit}- isLast={isLast}- enterEdit={enterEdit}- siblingIdx={siblingIdx}- attachments={attachments}- isSubmitting={isSubmitting}- searchResults={searchResults}- manualSkills={message.manualSkills}- messageId={message.messageId}- authorHeader={authorHeader}- setSiblingIdx={setSiblingIdx}- isCreatedByUser={message.isCreatedByUser}- conversationId={conversation?.conversationId}- showThinking={showThinking}- isLatestMessage={messageId === latestMessageId}- content={message.content as Array<TMessageContentParts | undefined>}- />+ <ErrorSourceProvider message={message}>+ <ContentParts+ edit={edit}+ isLast={isLast}+ enterEdit={enterEdit}+ siblingIdx={siblingIdx}+ attachments={attachments}+ isSubmitting={isSubmitting}+ searchResults={searchResults}+ manualSkills={message.manualSkills}+ messageId={message.messageId}+ authorHeader={authorHeader}+ setSiblingIdx={setSiblingIdx}+ isCreatedByUser={message.isCreatedByUser}+ conversationId={conversation?.conversationId}+ showThinking={showThinking}+ isLatestMessage={messageId === latestMessageId}+ content={message.content as Array<TMessageContentParts | undefined>}+ />+ </ErrorSourceProvider></MessageRow></div></div>diff --git a/client/src/components/Chat/Messages/SearchMessage.tsx b/client/src/components/Chat/Messages/SearchMessage.tsxindex 6561dfd067..12f57860e7 100644--- a/client/src/components/Chat/Messages/SearchMessage.tsx+++ b/client/src/components/Chat/Messages/SearchMessage.tsx@@ -58,6 +58,8 @@ export function areSearchMessagePropsEqual(a.iconURL === b.iconURL &&/** `SearchContent` renders an incomplete-response notice on `unfinished`. */a.unfinished === b.unfinished &&+ /** `SearchContent` renders a failed row through the error dispatcher, not as markdown. */+ a.error === b.error &&/** `SearchButtons` renders `title` and navigates by `conversationId`, so a* rename/refetch that leaves the text and id intact must still re-render. */a.title === b.title &&diff --git a/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx b/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsxindex 5cfbc3a95d..3bbe1b48fc 100644--- a/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx+++ b/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx@@ -31,13 +31,21 @@ jest.mock('~/components/Chat/Messages/Content/MessageContent', () => ({},}));-jest.mock('~/components/Chat/Messages/Content/ContentParts', () => ({- __esModule: true,- default: ({ content }: { content?: TMessage['content'] }) => {- mockContentRenderCount += 1;- return <div data-testid="structured-message-content">{JSON.stringify(content ?? [])}</div>;- },-}));+jest.mock('~/components/Chat/Messages/Content/ContentParts', () => {+ const { useErrorSource } = jest.requireActual('~/components/Messages/Content/Error/source');+ return {+ __esModule: true,+ default: function ContentParts({ content }: { content?: TMessage['content'] }) {+ mockContentRenderCount += 1;+ const errorSource = useErrorSource();+ return (+ <div data-testid="structured-message-content" data-error-source-model={errorSource?.model}>+ {JSON.stringify(content ?? [])}+ </div>+ );+ },+ };+});jest.mock('~/components/Chat/Messages/Content/Parts/AuthorHeader', () => ({__esModule: true,@@ -212,11 +220,16 @@ function renderStreamingRow(submitting = true,siblingIdx = 1,row?: RowComponent,+ assistantMessage?: TMessage,) {const queryClient = createQueryClient();queryClient.setQueryData<TMessage[]>([QueryKeys.messages, conversation.conversationId],- [userMessage, structured ? optimisticStructuredAssistantMessage : optimisticAssistantMessage],+ [+ userMessage,+ assistantMessage ??+ (structured ? optimisticStructuredAssistantMessage : optimisticAssistantMessage),+ ],);const initializeState = ({ set }: MutableSnapshot) => {@@ -349,6 +362,23 @@ describe('streaming hover actions', () => {expect(footer?.firstElementChild).toContainElement(timer);});+ /** An error content part renders without its message, so its row supplies the identity. */+ it.each([+ ['a structured', StructuredMessage],+ ['a flat-thread', MessageParts],+ ])("hands the error parts of %s row that row's model", (_label, row) => {+ renderStreamingRow(true, true, 1, row, {+ ...optimisticStructuredAssistantMessage,+ endpoint: 'anthropic',+ model: 'claude-sonnet-4-5',+ });++ expect(screen.getByTestId('structured-message-content')).toHaveAttribute(+ 'data-error-source-model',+ 'claude-sonnet-4-5',+ );+ });+it('renders no elapsed timer once the row is not submitting', () => {renderStreamingRow(false, false);diff --git a/client/src/components/Chat/Messages/__tests__/SearchMessage.comparator.spec.ts b/client/src/components/Chat/Messages/__tests__/SearchMessage.comparator.spec.tsindex 107d1021a4..dfa0c9a6a1 100644--- a/client/src/components/Chat/Messages/__tests__/SearchMessage.comparator.spec.ts+++ b/client/src/components/Chat/Messages/__tests__/SearchMessage.comparator.spec.ts@@ -32,6 +32,12 @@ describe('areSearchMessagePropsEqual', () => {).toBe(false);});+ it('is false when the error flag changes, which switches the row to the error renderer', () => {+ expect(areSearchMessagePropsEqual({ message: msg() }, { message: msg({ error: true }) })).toBe(+ false,+ );+ });+it('is false when the messageId changes', () => {expect(areSearchMessagePropsEqual({ message: msg() }, { message: msg({ messageId: 'm2' }) }),diff --git a/client/src/components/Messages/Content/Error.tsx b/client/src/components/Messages/Content/Error.tsxdeleted file mode 100644index 0d5edf0cb3..0000000000--- a/client/src/components/Messages/Content/Error.tsx+++ /dev/null@@ -1,275 +0,0 @@-// file deepcode ignore HardcodedNonCryptoSecret: No hardcoded secrets-import {- ErrorTypes,- alternateName,- ViolationTypes,- isCodeWorkspaceSelectionErrorReason,- parseLangChainErrorCode,- stripLangChainTroubleshootingUrl,-} from 'librechat-data-provider';-import type { LocalizeFunction } from '~/common';-import type { TranslationKeys } from '~/hooks';-import { formatJSON, extractJson, isJson } from '~/utils/json';-import { codeWorkspaceErrorKeys } from '~/utils/errors';-import { useLocalize } from '~/hooks';-import CodeBlock from './CodeBlock';--const localizedErrorPrefix = 'com_error';--/**- * The server converts classified LangChain failures into typed payloads, but messages persisted- * before it did still carry the docs URL, so the code is read back out of the text to localize- * those the same way. Codes without copy fall through to the provider text, stripped of the URL.- */-const langChainErrorKeys: Record<string, TranslationKeys> = {- MODEL_NOT_FOUND: 'com_error_model_not_found',- MODEL_RATE_LIMIT: 'com_error_model_rate_limit',-};--function getLangChainErrorKey(text: string): TranslationKeys | undefined {- const code = parseLangChainErrorCode(text);- return code == null ? undefined : langChainErrorKeys[code];-}--type TConcurrent = {- limit: number;-};--type TMessageLimit = {- max: number;- windowInMinutes: number;-};--type TTokenBalance = {- type: ViolationTypes | ErrorTypes;- balance: number;- tokenCost: number;- promptTokens: number;- prev_count: number;- violation_count: number;- date: Date;- generations?: unknown[];-};--type TExpiredKey = {- expiredAt: string;- endpoint: string;-};--type TGenericError = {- info: string;-};--type TContextOverflow = {- info?: string;- provider?: string;- projectedMessageTokens?: number;- availableMessageTokens?: number;-};--type TCompactionSkipped = {- reason?: string;-};--type TCodeWorkspaceError = {- reason?: string;-};--type TUpstreamModelError = {- status?: number;-};--/** Why a manual compaction could not run, keyed by the SDK's skip reason. */-const compactionSkippedKeys: Record<string, TranslationKeys> = {- disabled: 'com_error_compaction_disabled',- instructions_exceed_budget: 'com_error_compaction_budget',- nothing_to_summarize: 'com_error_compaction_nothing',-};--/**- * SDK boilerplate already covered by the localized headline; whatever remains- * (specific guidance and the token budget breakdown) renders as details.- */-const emptyMessagesBoilerplate = [- 'Message pruning removed all messages as none fit in the context window.',- 'Please increase the context window size or make your message shorter.',-];--const errorMessages = {- [ErrorTypes.MODERATION]: 'com_error_moderation',- [ErrorTypes.NO_USER_KEY]: 'com_error_no_user_key',- [ErrorTypes.INVALID_USER_KEY]: 'com_error_invalid_user_key',- [ErrorTypes.NO_BASE_URL]: 'com_error_no_base_url',- [ErrorTypes.INVALID_BASE_URL]: 'com_error_invalid_base_url',- [ErrorTypes.INVALID_ACTION]: `com_error_${ErrorTypes.INVALID_ACTION}`,- [ErrorTypes.INVALID_REQUEST]: `com_error_${ErrorTypes.INVALID_REQUEST}`,- [ErrorTypes.REFUSAL]: 'com_error_refusal',- [ErrorTypes.MISSING_MODEL]: (json: TGenericError, localize: LocalizeFunction) => {- const { info: endpoint } = json;- const provider = (alternateName[endpoint ?? ''] as string | undefined) ?? endpoint ?? 'unknown';- return localize('com_error_missing_model', { 0: provider });- },- [ErrorTypes.MODELS_NOT_LOADED]: 'com_error_models_not_loaded',- [ErrorTypes.ENDPOINT_MODELS_NOT_LOADED]: (json: TGenericError, localize: LocalizeFunction) => {- const { info: endpoint } = json;- const provider = (alternateName[endpoint ?? ''] as string | undefined) ?? endpoint ?? 'unknown';- return localize('com_error_endpoint_models_not_loaded', { 0: provider });- },- [ErrorTypes.NO_SYSTEM_MESSAGES]: `com_error_${ErrorTypes.NO_SYSTEM_MESSAGES}`,- [ErrorTypes.EXPIRED_USER_KEY]: (json: TExpiredKey, localize: LocalizeFunction) => {- const { expiredAt, endpoint } = json;- return localize('com_error_expired_user_key', { 0: endpoint, 1: expiredAt });- },- [ErrorTypes.INPUT_LENGTH]: (json: TGenericError, localize: LocalizeFunction) => {- const { info } = json;- return localize('com_error_input_length', { 0: info });- },- [ErrorTypes.INVALID_AGENT_PROVIDER]: (json: TGenericError, localize: LocalizeFunction) => {- const { info } = json;- const provider = (alternateName[info] as string | undefined) ?? info;- return localize('com_error_invalid_agent_provider', { 0: provider });- },- [ErrorTypes.GOOGLE_ERROR]: (json: TGenericError) => {- const { info } = json;- return info;- },- [ErrorTypes.GOOGLE_TOOL_CONFLICT]: 'com_error_google_tool_conflict',- [ErrorTypes.GOOGLE_VIDEO_UNPROCESSABLE]: 'com_error_google_video_unprocessable',- [ErrorTypes.RESOURCE_RECOVERY_REQUIRED]: 'com_error_resource_recovery_required',- [ErrorTypes.CODE_WORKSPACE_UNAVAILABLE]: (- json: TCodeWorkspaceError,- localize: LocalizeFunction,- ) => {- if (!isCodeWorkspaceSelectionErrorReason(json.reason)) {- return localize('com_error_code_workspace_unavailable');- }- return localize(codeWorkspaceErrorKeys[json.reason]);- },- [ErrorTypes.STREAM_EXPIRED]: 'com_error_stream_expired',- [ErrorTypes.MODEL_NOT_FOUND]: langChainErrorKeys.MODEL_NOT_FOUND,- [ErrorTypes.MODEL_RATE_LIMIT]: langChainErrorKeys.MODEL_RATE_LIMIT,- [ErrorTypes.UPSTREAM_MODEL_ERROR]: (json: TUpstreamModelError, localize: LocalizeFunction) =>- typeof json.status === 'number'- ? localize('com_error_upstream_model_status', { 0: json.status })- : localize('com_error_upstream_model'),- [ErrorTypes.COMPACTION_FAILED]: 'com_error_compaction_failed',- [ErrorTypes.COMPACTION_SKIPPED]: (json: TCompactionSkipped, localize: LocalizeFunction) =>- localize(compactionSkippedKeys[json.reason ?? ''] ?? 'com_error_compaction_failed'),- [ErrorTypes.EMPTY_MESSAGES]: (json: TGenericError, localize: LocalizeFunction) => {- const detail = emptyMessagesBoilerplate- .reduce((info, sentence) => info.replace(sentence, ''), json.info ?? '')- .trim();- return (- <>- {localize('com_error_empty_messages')}- {detail && (- <>- <br />- <br />- <CodeBlock- lang={localize('com_ui_details')}- error={true}- allowExecution={false}- codeChildren={detail}- />- </>- )}- </>- );- },- [ErrorTypes.FINAL_CONTEXT_OVERFLOW]: (json: TContextOverflow, localize: LocalizeFunction) => {- const { projectedMessageTokens: projected, availableMessageTokens: available } = json;- const message = localize('com_error_final_context_overflow');- if (typeof projected !== 'number' || typeof available !== 'number') {- return message;- }- return `${message} ${localize('com_error_context_tokens_detail', {- 0: projected,- 1: available,- })}`;- },- [ViolationTypes.BAN]:- 'Your account has been temporarily banned due to violations of our service.',- [ViolationTypes.ILLEGAL_MODEL_REQUEST]: (json: TGenericError, localize: LocalizeFunction) => {- const { info } = json;- const [endpoint, model = 'unknown'] = info?.split('|') ?? [];- const provider = (alternateName[endpoint ?? ''] as string | undefined) ?? endpoint ?? 'unknown';- return localize('com_error_illegal_model_request', { 0: model, 1: provider });- },- invalid_api_key:- 'Invalid API key. Please check your API key and try again. You can do this by clicking on the model logo in the left corner of the textbox and selecting "Set Token" for the current selected endpoint. Thank you for your understanding.',- insufficient_quota:- 'We apologize for any inconvenience caused. The default API key has reached its limit. To continue using this service, please set up your own API key. You can do this by clicking on the model logo in the left corner of the textbox and selecting "Set Token" for the current selected endpoint. Thank you for your understanding.',- concurrent: (json: TConcurrent) => {- const { limit } = json;- const plural = limit > 1 ? 's' : '';- return `Only ${limit} message${plural} at a time. Please allow any other responses to complete before sending another message, or wait one minute.`;- },- message_limit: (json: TMessageLimit) => {- const { max, windowInMinutes } = json;- const plural = max > 1 ? 's' : '';- return `You hit the message limit. You have a cap of ${max} message${plural} per ${- windowInMinutes > 1 ? `${windowInMinutes} minutes` : 'minute'- }.`;- },- token_balance: (json: TTokenBalance, localize: LocalizeFunction) => {- const { balance, tokenCost, promptTokens, generations } = json;- const message = localize('com_error_token_balance', {- 0: balance,- 1: promptTokens,- 2: tokenCost,- });- return (- <>- {message}- {generations && (- <>- <br />- <br />- </>- )}- {generations && (- <CodeBlock- lang="Generations"- error={true}- codeChildren={formatJSON(JSON.stringify(generations))}- />- )}- </>- );- },-};--const Error = ({ text }: { text: string }) => {- const localize = useLocalize();- const jsonString = extractJson(text);- const providerText = stripLangChainTroubleshootingUrl(text);- const errorMessage =- providerText.length > 512 && !jsonString ? providerText.slice(0, 512) + '...' : providerText;- const defaultResponse = `Something went wrong. Here's the specific error message we encountered: ${errorMessage}`;-- const langChainErrorKey = getLangChainErrorKey(text);- if (langChainErrorKey != null) {- return localize(langChainErrorKey);- }-- if (!isJson(jsonString)) {- return defaultResponse;- }-- const json = JSON.parse(jsonString);- const errorKey = json.code || json.type;- const mappedError = errorKey && errorMessages[errorKey];-- if (typeof mappedError === 'function') {- return mappedError(json, localize);- } else if (mappedError && mappedError.startsWith(localizedErrorPrefix)) {- return localize(mappedError);- } else if (mappedError) {- return mappedError;- } else {- return defaultResponse;- }-};--export default Error;diff --git a/client/src/components/Messages/Content/Error/AgentError.tsx b/client/src/components/Messages/Content/Error/AgentError.tsxnew file mode 100644index 0000000000..d6f28aae19--- /dev/null+++ b/client/src/components/Messages/Content/Error/AgentError.tsx@@ -0,0 +1,69 @@+import { useContext } from 'react';+import { Permissions, SystemRoles, EModelEndpoint, PermissionTypes } from 'librechat-data-provider';+import type { ErrorRendererProps } from './parts';+import type { TranslationKeys } from '~/hooks';+import { ErrorActions, ErrorBody, getProviderName, readString, useErrorEndpoint } from './parts';+import { useHasAccess, useLocalize } from '~/hooks';+import { AuthContext } from '~/hooks/AuthContext';++export default function AgentError({ json, message }: ErrorRendererProps) {+ const localize = useLocalize();+ const { agent, provider: endpointProvider, endpointsConfig } = useErrorEndpoint(message);+ const user = useContext(AuthContext)?.user;+ const canUseAgents = useHasAccess({+ permissionType: PermissionTypes.AGENTS,+ permission: Permissions.USE,+ });+ const canCreateAgents = useHasAccess({+ permissionType: PermissionTypes.AGENTS,+ permission: Permissions.CREATE,+ });++ const info = readString(json, 'info');+ const providerName = info != null ? getProviderName(info) : endpointProvider;++ /**+ * "Open the agent builder" has to be something this reader can do. The side panel offers the+ * builder only while agents are configured, the builder is not disabled, and the reader holds both+ * USE and CREATE; inside it, an agent is editable with an EDIT grant or by an administrator, the+ * same checks the builder applies. An absent agent is also the expected state on shared links and+ * search results, so editability is never claimed without the map identifying the agent.+ */+ const agentsConfig = endpointsConfig?.[EModelEndpoint.agents];+ const builderAvailable =+ agentsConfig != null && agentsConfig.disableBuilder !== true && canUseAgents && canCreateAgents;+ const canEdit =+ agent != null &&+ builderAvailable &&+ (agent.isEditable !== false || user?.role === SystemRoles.ADMIN);++ const supportName = agent?.support_contact?.name?.trim() ?? '';+ const supportEmail = agent?.support_contact?.email?.trim() ?? '';+ const ownerName = agent?.owner_contact?.name?.trim() ?? '';+ const hasSupportContact = supportName !== '' || supportEmail !== '';+ const contactName = hasSupportContact ? supportName : ownerName;++ const guidanceKey: TranslationKeys = canEdit+ ? 'com_error_invalid_agent_provider_editable'+ : 'com_error_invalid_agent_provider_admin';+ const guidance =+ !canEdit && contactName !== ''+ ? localize('com_error_invalid_agent_provider_owner', { 0: contactName })+ : localize(guidanceKey);++ return (+ <ErrorBody>+ {providerName ? (+ <div>{localize('com_error_invalid_agent_provider', { 0: providerName })}</div>+ ) : null}+ <div>{guidance}</div>+ {supportEmail ? (+ <ErrorActions>+ <a href={`mailto:${supportEmail}`} className="text-link hover:underline">+ {localize('com_error_agent_contact_email', { 0: supportEmail })}+ </a>+ </ErrorActions>+ ) : null}+ </ErrorBody>+ );+}diff --git a/client/src/components/Messages/Content/Error/BalanceError.tsx b/client/src/components/Messages/Content/Error/BalanceError.tsxnew file mode 100644index 0000000000..cab3eeb5a9--- /dev/null+++ b/client/src/components/Messages/Content/Error/BalanceError.tsx@@ -0,0 +1,85 @@+import type { ErrorRendererProps, JsonValue } from './parts';+import {+ ErrorBody,+ ErrorDetails,+ formatCredits,+ formatNumber,+ readNumber,+ readString,+} from './parts';+import { useLocalize } from '~/hooks';++type GenerationRow = {+ model: string;+ promptTokens: string;+ completionTokens: string;+};++function readGeneration(generation: JsonValue): GenerationRow | null {+ if (typeof generation !== 'object' || generation === null || Array.isArray(generation)) {+ return null;+ }++ const model = readString(generation, 'model');+ const promptTokens = readNumber(generation, 'promptTokens');+ const completionTokens = readNumber(generation, 'completionTokens');++ if (model == null && promptTokens == null && completionTokens == null) {+ return null;+ }++ const availableTokens = [+ promptTokens != null ? formatNumber(promptTokens) : null,+ completionTokens != null ? formatNumber(completionTokens) : null,+ ].filter((token): token is string => token != null);++ return {+ model: model ?? availableTokens.join(', '),+ promptTokens: promptTokens != null ? formatNumber(promptTokens) : '—',+ completionTokens: completionTokens != null ? formatNumber(completionTokens) : '—',+ };+}++export default function BalanceError({ json }: ErrorRendererProps) {+ const localize = useLocalize();+ const balance = readNumber(json, 'balance');+ const tokenCost = readNumber(json, 'tokenCost');+ const promptTokens = readNumber(json, 'promptTokens');+ const generations = Array.isArray(json.generations)+ ? json.generations.map(readGeneration).filter((row): row is GenerationRow => row != null)+ : [];++ const summary =+ tokenCost != null && balance != null+ ? localize('com_error_token_balance', {+ 0: formatCredits(tokenCost),+ 1: formatCredits(balance),+ })+ : localize('com_error_limit_reached');++ return (+ <ErrorBody>+ <p>{summary}</p>+ {promptTokens != null ? (+ <p className="text-text-secondary">+ {localize('com_error_token_balance_prompt', { 0: formatNumber(promptTokens) })}+ </p>+ ) : null}+ {generations.length > 0 ? (+ <ErrorDetails label={localize('com_error_token_balance_generations')}>+ <ul className="list-none space-y-0.5">+ {generations.map((generation, index) => (+ <li key={index}>+ {localize('com_error_token_balance_generation', {+ 0: generation.model,+ 1: generation.promptTokens,+ 2: generation.completionTokens,+ })}+ </li>+ ))}+ </ul>+ </ErrorDetails>+ ) : null}+ </ErrorBody>+ );+}diff --git a/client/src/components/Messages/Content/Error/ContextError.tsx b/client/src/components/Messages/Content/Error/ContextError.tsxnew file mode 100644index 0000000000..761ead140f--- /dev/null+++ b/client/src/components/Messages/Content/Error/ContextError.tsx@@ -0,0 +1,166 @@+import { ErrorTypes } from 'librechat-data-provider';+import type { ErrorRendererProps } from './parts';+import type { TranslationKeys } from '~/hooks';+import {+ ErrorBody,+ ErrorDetails,+ formatNumber,+ readNumber,+ readString,+ useErrorEndpoint,+} from './parts';+import { useLocalize } from '~/hooks';++const emptyMessagesBoilerplate = [+ 'Message pruning removed all messages as none fit in the context window.',+ 'Please increase the context window size or make your message shorter.',+];++const compactionSkippedKeys: Record<string, TranslationKeys> = {+ disabled: 'com_error_compaction_disabled',+ instructions_exceed_budget: 'com_error_compaction_budget',+ nothing_to_summarize: 'com_error_compaction_nothing',+};++function parseInputLength(info: string | undefined): [number, number] | undefined {+ if (info == null) {+ return undefined;+ }++ const values = info.split('/').map((part) => part.trim());+ if (values.length !== 2 || values.some((value) => value === '')) {+ return undefined;+ }++ const numbers = values.map(Number);+ return numbers.every((value) => Number.isFinite(value) && Number.isInteger(value))+ ? (numbers as [number, number])+ : undefined;+}++function formatDetailNumbers(detail: string): string {+ return detail.replace(/\b\d+(?:\.\d+)?\b/g, (value) => {+ const number = Number(value);+ return Number.isFinite(number) ? formatNumber(number) : value;+ });+}++function formatEmptyMessagesDetail(detail: string) {+ const entries = detail+ .split(',')+ .map((entry) => entry.trim())+ .filter((entry) => entry.length > 0);+ const isBudgetSentence =+ entries.length > 1 &&+ /^Token budget\s*:/i.test(entries[0]) &&+ entries.every((entry) => /\b\d+(?:\.\d+)?\b/.test(entry));++ if (!isBudgetSentence) {+ return formatDetailNumbers(detail);+ }++ return (+ <ul className="list-none space-y-0.5">+ {entries.map((entry, index) => (+ <li key={`${index}-${entry}`}>{formatDetailNumbers(entry)}</li>+ ))}+ </ul>+ );+}++function hasTextBeyondNumbers(+ info: string | undefined,+ projected: number | undefined,+ available: number | undefined,+): boolean {+ if (info == null || info.trim() === '') {+ return false;+ }+ if (projected == null || available == null) {+ return true;+ }++ const parsed = parseInputLength(info);+ return parsed == null || parsed[0] !== projected || parsed[1] !== available;+}++export default function ContextError({ json, message }: ErrorRendererProps) {+ const localize = useLocalize();+ const { compactionAvailable } = useErrorEndpoint(message);+ const errorType = readString(json, 'type');+ const nextSteps = localize(+ compactionAvailable ? 'com_error_context_next_steps_compact' : 'com_error_context_next_steps',+ );++ if (errorType === ErrorTypes.INPUT_LENGTH) {+ const info = readString(json, 'info');+ const parsed = parseInputLength(info);+ const headline =+ parsed == null+ ? localize('com_error_input_length_unknown')+ : localize('com_error_input_length', {+ 0: formatNumber(parsed[0]),+ 1: formatNumber(parsed[1]),+ });++ /** The latest message alone exceeds the limit; compacting earlier history cannot make it fit. */+ return (+ <ErrorBody>+ <p>{headline}</p>+ <p className="text-text-secondary">{localize('com_error_context_next_steps')}</p>+ {info != null && parsed == null && (+ <ErrorDetails label={localize('com_error_context_token_budget')}>{info}</ErrorDetails>+ )}+ </ErrorBody>+ );+ }++ if (errorType === ErrorTypes.FINAL_CONTEXT_OVERFLOW) {+ const projected = readNumber(json, 'projectedMessageTokens');+ const available = readNumber(json, 'availableMessageTokens');+ const info = readString(json, 'info');+ const headline =+ projected != null && available != null+ ? localize('com_error_final_context_overflow', {+ 0: formatNumber(projected),+ 1: formatNumber(available),+ })+ : localize('com_error_final_context_overflow_unknown');++ return (+ <ErrorBody>+ <p>{headline}</p>+ <p className="text-text-secondary">{nextSteps}</p>+ {hasTextBeyondNumbers(info, projected, available) && (+ <ErrorDetails label={localize('com_error_context_token_budget')}>{info}</ErrorDetails>+ )}+ </ErrorBody>+ );+ }++ if (errorType === ErrorTypes.EMPTY_MESSAGES) {+ const info = readString(json, 'info');+ const detail = emptyMessagesBoilerplate+ .reduce((remaining, sentence) => remaining.replace(sentence, ''), info ?? '')+ .trim();++ return (+ <ErrorBody>+ <p>{localize('com_error_empty_messages')}</p>+ <p className="text-text-secondary">{nextSteps}</p>+ {detail && (+ <ErrorDetails label={localize('com_error_context_token_budget')}>+ {formatEmptyMessagesDetail(detail)}+ </ErrorDetails>+ )}+ </ErrorBody>+ );+ }++ if (errorType === ErrorTypes.COMPACTION_SKIPPED) {+ const reason = readString(json, 'reason');+ return localize(compactionSkippedKeys[reason ?? ''] ?? 'com_error_compaction_failed');+ }++ return localize('com_error_unknown');+}diff --git a/client/src/components/Messages/Content/Error/LimitError.tsx b/client/src/components/Messages/Content/Error/LimitError.tsxnew file mode 100644index 0000000000..8806a36af7--- /dev/null+++ b/client/src/components/Messages/Content/Error/LimitError.tsx@@ -0,0 +1,199 @@+import { useEffect, useState } from 'react';+import { ViolationTypes } from 'librechat-data-provider';+import type { ErrorRendererProps } from './parts';+import {+ ErrorBody,+ readNumber,+ readString,+ formatNumber,+ formatDuration,+ useWindowLabel,+ formatTimestamp,+} from './parts';+import { useLocalize } from '~/hooks';++type RetryTargetInput = {+ type: string | undefined;+ resetAt?: number;+ retryAfterSeconds?: number;+ createdAt?: string | Date;+ windowInMinutes?: number;+};++function getCreatedAtMs(createdAt?: string | Date): number | undefined {+ if (createdAt == null) {+ return undefined;+ }+ const timestamp = createdAt instanceof Date ? createdAt.getTime() : new Date(createdAt).getTime();+ return Number.isNaN(timestamp) ? undefined : timestamp;+}++/**+ * The moment the limiter's window reopens. A reset already in the past still resolves, and reads as+ * "you can send another message now". A future one is bounded by the limiter's own window, which is+ * as far ahead as a reset can lie, rather than by a fixed horizon an operator's window may exceed.+ * The window is measured from the row's own timestamp when it has one, the clock the target is+ * counted in, so a device clock that disagrees with the server's cannot push a valid reset out of+ * range.+ */+function resolveRetryTarget({+ type,+ resetAt,+ retryAfterSeconds,+ createdAt,+ windowInMinutes,+}: RetryTargetInput): number | undefined {+ if (type !== ViolationTypes.MESSAGE_LIMIT) {+ return undefined;+ }++ /**+ * `retryAfterSeconds` is relative, so counted from the row's own timestamp it holds up against a+ * device clock that disagrees with the server's: a row received live is stamped by this device+ * as it arrives, and a restored row by the server that also stamped `resetAt`. The absolute+ * `resetAt` is the fallback for a row missing either.+ */+ const rowTime = getCreatedAtMs(createdAt);+ const target =+ retryAfterSeconds != null && rowTime != null ? rowTime + retryAfterSeconds * 1000 : resetAt;+ if (target == null || !Number.isFinite(target)) {+ return undefined;+ }++ const violatedAt = rowTime ?? Date.now();+ if (windowInMinutes != null && target > violatedAt + windowInMinutes * 60 * 1000) {+ return undefined;+ }+ return target;+}++/** Keeps a rate-limit countdown local to the rendered error row. */+function useRetryCountdown(target?: number): number | undefined {+ const [remaining, setRemaining] = useState<number | undefined>(() =>+ target == null ? undefined : Math.max(0, target - Date.now()),+ );++ useEffect(() => {+ if (target == null) {+ setRemaining(undefined);+ return;+ }++ const tick = () => {+ const next = target - Date.now();+ setRemaining(Math.max(0, next));+ return next;+ };++ if (tick() <= 0) {+ return;+ }++ const timer = setInterval(() => {+ if (tick() <= 0) {+ clearInterval(timer);+ }+ }, 1000);++ return () => clearInterval(timer);+ }, [target]);++ if (target == null) {+ return undefined;+ }+ return remaining ?? Math.max(0, target - Date.now());+}++export default function LimitError({ json, message }: ErrorRendererProps) {+ const localize = useLocalize();+ const type = readString(json, 'type');+ const createdAt = message?.createdAt as string | Date | undefined;+ const max = readNumber(json, 'max');+ const limit = readNumber(json, 'limit');+ const windowInMinutes = readNumber(json, 'windowInMinutes');+ const windowLabel = useWindowLabel(windowInMinutes);+ const resetAt = readNumber(json, 'resetAt');+ const retryAfterSeconds = readNumber(json, 'retryAfterSeconds');+ const retryTarget = resolveRetryTarget({+ type,+ resetAt,+ retryAfterSeconds,+ createdAt,+ windowInMinutes,+ });+ const remaining = useRetryCountdown(retryTarget);++ let headline: string;+ switch (type) {+ case ViolationTypes.MESSAGE_LIMIT:+ if (windowLabel == null) {+ headline = localize('com_error_limit_reached');+ } else if (max === 1) {+ headline = localize('com_error_message_limit_one', { 0: windowLabel });+ } else if (max != null) {+ headline = localize('com_error_message_limit', {+ 0: formatNumber(max),+ 1: windowLabel,+ });+ } else {+ headline = localize('com_error_limit_reached');+ }+ break;+ case ViolationTypes.CONCURRENT:+ headline =+ limit != null && limit > 1+ ? localize('com_error_concurrent', { 0: formatNumber(limit) })+ : localize('com_error_concurrent_one');+ break;+ case ViolationTypes.FILE_UPLOAD_LIMIT:+ headline =+ max != null && windowLabel != null+ ? localize('com_error_file_upload_limit', {+ 0: formatNumber(max),+ 1: windowLabel,+ })+ : localize('com_error_limit_reached');+ break;+ case ViolationTypes.TTS_LIMIT:+ headline =+ max != null && windowLabel != null+ ? localize('com_error_tts_limit', { 0: formatNumber(max), 1: windowLabel })+ : localize('com_error_limit_reached');+ break;+ case ViolationTypes.STT_LIMIT:+ headline =+ max != null && windowLabel != null+ ? localize('com_error_stt_limit', { 0: formatNumber(max), 1: windowLabel })+ : localize('com_error_limit_reached');+ break;+ default:+ headline = localize('com_error_limit_reached');+ }++ /**+ * The error box is an assertive live region, so a line that changes every second would be+ * announced every second. The ticking countdown is hidden from assistive technology, which reads+ * the moment the window reopens instead; that sentence changes once, when sending is allowed again.+ */+ return (+ <ErrorBody>+ <p>{headline}</p>+ {retryTarget != null && remaining != null && (+ <p className="text-text-secondary">+ {remaining > 0 ? (+ <>+ <span aria-hidden="true">+ {localize('com_error_retry_countdown', { 0: formatDuration(remaining) })}+ </span>+ <span className="sr-only">+ {localize('com_error_retry_at', { 0: formatTimestamp(retryTarget) })}+ </span>+ </>+ ) : (+ localize('com_error_retry_available')+ )}+ </p>+ )}+ </ErrorBody>+ );+}diff --git a/client/src/components/Messages/Content/Error/ModelError.tsx b/client/src/components/Messages/Content/Error/ModelError.tsxnew file mode 100644index 0000000000..e167b5d600--- /dev/null+++ b/client/src/components/Messages/Content/Error/ModelError.tsx@@ -0,0 +1,58 @@+import {+ ErrorTypes,+ ViolationTypes,+ isCodeWorkspaceSelectionErrorReason,+} from 'librechat-data-provider';+import type { ErrorRendererProps } from './parts';+import { getProviderName, readNumber, readString, useErrorEndpoint } from './parts';+import { codeWorkspaceErrorKeys } from '~/utils/errors';+import { useLocalize } from '~/hooks';++/**+ * Failures naming a provider, a model or a workspace selection. Each payload carries the identity+ * it is about (`info`, `reason`, `status`), so the only resolution done here is turning an+ * endpoint id into the name a reader recognizes.+ */+export default function ModelError({ json, message }: ErrorRendererProps) {+ const localize = useLocalize();+ const { provider: conversationProvider } = useErrorEndpoint(message);+ const errorKey = readString(json, 'code') ?? readString(json, 'type');+ const info = readString(json, 'info');+ /** `info` is an endpoint id on these payloads; the conversation's own provider is the fallback. */+ const provider = info != null ? getProviderName(info) : conversationProvider;++ if (errorKey === ErrorTypes.MISSING_MODEL) {+ return provider != null+ ? localize('com_error_missing_model', { 0: provider })+ : localize('com_error_models_not_loaded');+ }++ if (errorKey === ErrorTypes.ENDPOINT_MODELS_NOT_LOADED) {+ return provider != null+ ? localize('com_error_endpoint_models_not_loaded', { 0: provider })+ : localize('com_error_models_not_loaded');+ }++ if (errorKey === ViolationTypes.ILLEGAL_MODEL_REQUEST) {+ const [endpoint, model] = info?.split('|') ?? [];+ const requestedProvider =+ endpoint != null && endpoint !== '' ? getProviderName(endpoint) : conversationProvider;+ if (model == null || model === '' || requestedProvider == null) {+ return localize('com_error_model_not_found');+ }+ return localize('com_error_illegal_model_request', { 0: model, 1: requestedProvider });+ }++ if (errorKey === ErrorTypes.CODE_WORKSPACE_UNAVAILABLE) {+ const reason = readString(json, 'reason');+ return isCodeWorkspaceSelectionErrorReason(reason)+ ? localize(codeWorkspaceErrorKeys[reason])+ : localize('com_error_code_workspace_unavailable');+ }++ /** Provider-neutral, matching the sentence the server persists as the failure's own text. */+ const status = readNumber(json, 'status');+ return status != null+ ? localize('com_error_upstream_model_status', { 0: status })+ : localize('com_error_upstream_model');+}diff --git a/client/src/components/Messages/Content/Error/ProviderError.tsx b/client/src/components/Messages/Content/Error/ProviderError.tsxnew file mode 100644index 0000000000..08353a7cee--- /dev/null+++ b/client/src/components/Messages/Content/Error/ProviderError.tsx@@ -0,0 +1,135 @@+import { ErrorTypes, stripLangChainTroubleshootingUrl } from 'librechat-data-provider';+import type { ErrorPayload, ErrorRendererProps, UnclassifiedErrorProps } from './parts';+import { ErrorBody, ErrorDetails, readObject, readString, useErrorEndpoint } from './parts';+import { extractJson } from '~/utils/json';+import { useLocalize } from '~/hooks';++function withHeadline(+ headline: string,+ detail?: { label: string; value: string },+): JSX.Element | string {+ if (detail == null) {+ return headline;+ }++ return (+ <ErrorBody>+ <div>{headline}</div>+ <ErrorDetails label={detail.label}>{detail.value}</ErrorDetails>+ </ErrorBody>+ );+}++/**+ * A refusal's explanation. Anthropic reports one under `stop_details`, which the server persists+ * inside `info` with the rest of the stop metadata; a Bedrock content filter reports none. A plain+ * string `info` is read as the explanation too.+ */+function readRefusalExplanation(json: ErrorPayload): string | undefined {+ return (+ readString(json, 'info') ??+ readString(readObject(readObject(json, 'info'), 'stop_details'), 'explanation')+ );+}++/** A provider's own message, flat or nested under `error` the way OpenAI-style bodies carry it. */+function readProviderError(json: ErrorPayload | undefined): string | undefined {+ return readString(json, 'error') ?? readString(readObject(json, 'error'), 'message');+}++/** Renders provider-produced failures with identity-aware copy and readable provider details. */+export default function ProviderError({ json, message }: ErrorRendererProps) {+ const localize = useLocalize();+ const { provider, model } = useErrorEndpoint(message);+ const errorKey = readString(json, 'code') ?? readString(json, 'type');++ if (errorKey === ErrorTypes.REFUSAL) {+ const headline =+ model != null+ ? localize('com_error_refusal', { 0: model })+ : localize('com_error_refusal_unknown');+ const explanation = readRefusalExplanation(json);+ return explanation == null+ ? headline+ : withHeadline(headline, {+ label: localize('com_error_refusal_reason'),+ value: explanation,+ });+ }++ if (errorKey === ErrorTypes.GOOGLE_ERROR) {+ const headline = localize('com_error_google_error');+ const info = readString(json, 'info');+ return info == null+ ? headline+ : withHeadline(headline, {+ label: localize('com_error_details_provider'),+ value: info,+ });+ }++ if (errorKey === ErrorTypes.INVALID_REQUEST) {+ const headline =+ provider != null+ ? localize('com_error_invalid_request_error', { 0: provider })+ : localize('com_error_invalid_request_error_unknown');+ const detail =+ [readProviderError(json), readString(json, 'message'), readString(json, 'info')]+ .filter((value): value is string => value != null)+ .join('\n\n') || undefined;+ return detail == null+ ? headline+ : withHeadline(headline, {+ label: localize('com_error_details_provider'),+ value: detail,+ });+ }++ if (errorKey === ErrorTypes.NO_SYSTEM_MESSAGES) {+ return provider != null+ ? localize('com_error_no_system_messages', { 0: provider })+ : localize('com_error_no_system_messages_unknown');+ }++ return <UnclassifiedError json={json} text="" message={message} />;+}++/** Fallback for provider prose and payloads whose error code has no localized renderer. */+export function UnclassifiedError({ json, text, message }: UnclassifiedErrorProps) {+ const localize = useLocalize();+ const { provider } = useErrorEndpoint(message);+ const jsonString = extractJson(text);+ const payloadProse =+ readProviderError(json) ?? readString(json, 'message') ?? readString(json, 'info');+ /**+ * The payload is swapped for its own message rather than dropped: a failed run persists a+ * provider error as `<base message>: <status> <body>`, and the body is where the reason is.+ */+ const withoutPayload =+ jsonString !== '' ? text.replace(jsonString, () => payloadProse ?? '') : text;+ const prose = stripLangChainTroubleshootingUrl(withoutPayload).trim() || payloadProse;+ /** A payload that told us nothing usable is its own statement; otherwise name who failed. */+ const providerHeadline =+ provider != null+ ? localize('com_error_provider_failed', { 0: provider })+ : localize('com_error_upstream_model');+ const headline = prose == null && json != null ? localize('com_error_unknown') : providerHeadline;++ if (prose == null) {+ return headline;+ }++ if (prose.length <= 240 && !/[\r\n]/.test(prose)) {+ return (+ <ErrorBody>+ <div>{headline}</div>+ <div className="text-text-secondary">{prose}</div>+ </ErrorBody>+ );+ }++ return withHeadline(headline, {+ label: localize('com_error_details_provider'),+ value: prose,+ });+}diff --git a/client/src/components/Messages/Content/Error/UserKeyError.tsx b/client/src/components/Messages/Content/Error/UserKeyError.tsxnew file mode 100644index 0000000000..4145362cc6--- /dev/null+++ b/client/src/components/Messages/Content/Error/UserKeyError.tsx@@ -0,0 +1,164 @@+import { useState } from 'react';+import { ErrorTypes, getEndpointField } from 'librechat-data-provider';+import type { ErrorRendererProps } from './parts';+import type { TranslationKeys } from '~/hooks';+import {+ ErrorBody,+ readString,+ ErrorAction,+ ErrorActions,+ formatTimestamp,+ useErrorEndpoint,+ ProviderErrorCodes,+} from './parts';+import { SetKeyDialog } from '~/components/Input/SetKeyDialog';+import { useLocalize } from '~/hooks';++type UserKeyErrorCode =+ | ErrorTypes.NO_USER_KEY+ | ErrorTypes.EXPIRED_USER_KEY+ | ErrorTypes.INVALID_USER_KEY+ | ErrorTypes.NO_BASE_URL+ | ErrorTypes.INVALID_BASE_URL+ | (typeof ProviderErrorCodes)[keyof typeof ProviderErrorCodes];++/** What the dialog is opened to do; every other code updates a key that is already saved. */+const actionLabels: Partial<Record<UserKeyErrorCode, TranslationKeys>> = {+ [ErrorTypes.NO_USER_KEY]: 'com_error_user_key_add',+ [ErrorTypes.NO_BASE_URL]: 'com_error_user_url_add',+ [ErrorTypes.INVALID_BASE_URL]: 'com_error_user_url_update',+};++export default function UserKeyError({ json, message }: ErrorRendererProps) {+ const localize = useLocalize();+ const [dialogOpen, setDialogOpen] = useState(false);+ const code = (readString(json, 'code') ?? readString(json, 'type')) as+ | UserKeyErrorCode+ | undefined;+ /** An expired key's payload names the endpoint whose key expired, which outranks the row's. */+ const payloadEndpoint =+ code === ErrorTypes.EXPIRED_USER_KEY ? readString(json, 'endpoint') : undefined;+ const { endpoint, endpointType, provider, userProvidesCredentials, endpointsConfig } =+ useErrorEndpoint(message, payloadEndpoint);+ const expiredAt = readString(json, 'expiredAt');++ /**+ * Every one of these codes reads three ways: who owns the key is unknown (a shared link, or any+ * view without the endpoint configuration), the reader owns it and can fix it, or the deployment+ * owns it and only an administrator can.+ */+ const byOwnership = (+ generic: TranslationKeys,+ userProvided: TranslationKeys,+ admin: TranslationKeys,+ ): string => {+ if (provider == null || userProvidesCredentials == null) {+ return localize(generic);+ }+ return localize(userProvidesCredentials ? userProvided : admin, { 0: provider });+ };++ /**+ * These codes can only come from the reader's own saved record (an unparseable key, a missing or+ * rejected user-provided URL), so there is no administrator variant: named copy when that record+ * is still the reader's to edit, the generic sentence otherwise.+ */+ const ownRecord = (generic: TranslationKeys, owned: TranslationKeys): string =>+ userProvidesCredentials === true && provider != null+ ? localize(owned, { 0: provider })+ : localize(generic);++ let errorMessage: string;+ switch (code) {+ case ErrorTypes.NO_USER_KEY:+ errorMessage = byOwnership(+ 'com_error_no_user_key_generic',+ 'com_error_no_user_key',+ 'com_error_no_user_key_admin',+ );+ break;+ case ErrorTypes.EXPIRED_USER_KEY:+ if (expiredAt == null) {+ errorMessage = localize('com_error_invalid_user_key');+ } else if (provider == null) {+ errorMessage = localize('com_error_expired_user_key_generic', {+ 0: formatTimestamp(expiredAt),+ });+ } else {+ errorMessage = localize('com_error_expired_user_key', {+ 0: provider,+ 1: formatTimestamp(expiredAt),+ });+ }+ break;+ case ErrorTypes.INVALID_USER_KEY:+ errorMessage = ownRecord('com_error_invalid_user_key', 'com_error_invalid_user_key_provider');+ break;+ case ErrorTypes.NO_BASE_URL:+ errorMessage = ownRecord('com_error_no_base_url', 'com_error_no_base_url_provider');+ break;+ case ErrorTypes.INVALID_BASE_URL:+ errorMessage = ownRecord('com_error_invalid_base_url', 'com_error_invalid_base_url_provider');+ break;+ case ProviderErrorCodes.INVALID_API_KEY:+ errorMessage = byOwnership(+ 'com_error_invalid_api_key_generic',+ 'com_error_invalid_api_key',+ 'com_error_invalid_api_key_admin',+ );+ break;+ case ProviderErrorCodes.INSUFFICIENT_QUOTA:+ errorMessage = byOwnership(+ 'com_error_insufficient_quota_generic',+ 'com_error_insufficient_quota',+ 'com_error_insufficient_quota_admin',+ );+ break;+ default:+ errorMessage = localize('com_error_invalid_user_key');+ }++ const canEditKey = userProvidesCredentials === true && endpoint != null;+ const updateLabel =+ (code != null ? actionLabels[code] : undefined) ?? 'com_error_user_key_update';++ return (+ <ErrorBody>+ {errorMessage}+ {canEditKey && (+ <ErrorActions>+ <ErrorAction onClick={() => setDialogOpen(true)}>{localize(updateLabel)}</ErrorAction>+ </ErrorActions>+ )}+ {canEditKey && dialogOpen && endpoint != null && (+ <SetKeyDialog+ open={dialogOpen}+ onOpenChange={setDialogOpen}+ endpoint={endpoint}+ endpointType={endpointType}+ userProvideURL={getEndpointField(endpointsConfig, endpoint, 'userProvideURL')}+ userProvideAccessKeyId={getEndpointField(+ endpointsConfig,+ endpoint,+ 'userProvideAccessKeyId',+ )}+ userProvideSecretAccessKey={getEndpointField(+ endpointsConfig,+ endpoint,+ 'userProvideSecretAccessKey',+ )}+ userProvideSessionToken={getEndpointField(+ endpointsConfig,+ endpoint,+ 'userProvideSessionToken',+ )}+ userProvideBearerToken={getEndpointField(+ endpointsConfig,+ endpoint,+ 'userProvideBearerToken',+ )}+ />+ )}+ </ErrorBody>+ );+}diff --git a/client/src/components/Messages/Content/Error/index.tsx b/client/src/components/Messages/Content/Error/index.tsxnew file mode 100644index 0000000000..589742f302--- /dev/null+++ b/client/src/components/Messages/Content/Error/index.tsx@@ -0,0 +1,83 @@+// file deepcode ignore HardcodedNonCryptoSecret: No hardcoded secrets+import { parseLangChainErrorCode } from 'librechat-data-provider';+import type { TranslationKeys } from '~/hooks';+import type { ErrorSource } from './source';+import type { ErrorPayload } from './parts';+import { errorCopy, errorRenderers } from './registry';+import { UnclassifiedError } from './ProviderError';+import { extractJson, isJson } from '~/utils/json';+import { readObject, readString } from './parts';+import { useErrorSource } from './source';+import { useLocalize } from '~/hooks';++/**+ * The server converts classified LangChain failures into typed payloads, but messages persisted+ * before it did still carry the docs URL, so the code is read back out of the text to localize+ * those the same way. Codes without copy fall through to the provider text, stripped of the URL.+ */+const langChainErrorKeys: Record<string, TranslationKeys> = {+ MODEL_NOT_FOUND: 'com_error_model_not_found',+ MODEL_RATE_LIMIT: 'com_error_model_rate_limit',+};++function getLangChainErrorKey(text: string): TranslationKeys | undefined {+ const code = parseLangChainErrorCode(text);+ return code == null ? undefined : langChainErrorKeys[code];+}++/**+ * Renders a failed turn from whatever the server managed to persist.+ *+ * Three kinds of text arrive here: a typed payload this app produced, a provider's own error body,+ * and unclassified prose. A payload with copy wins, because it is the only one written for a+ * reader; everything else is shown through `UnclassifiedError`, which leads with what is known and+ * keeps the raw provider text as a detail rather than as the headline.+ *+ * `message` is the row when the caller has it; an error content part renders without one and reads+ * its row's identity from `ErrorSourceProvider` instead.+ */+const Error = ({ text, message: rowMessage }: { text: string; message?: ErrorSource }) => {+ const localize = useLocalize();+ const contextSource = useErrorSource();+ const message = rowMessage ?? contextSource;++ const langChainErrorKey = getLangChainErrorKey(text);+ if (langChainErrorKey != null) {+ return localize(langChainErrorKey);+ }++ const jsonString = extractJson(text);+ if (!isJson(jsonString)) {+ return <UnclassifiedError text={text} message={message} />;+ }++ const json = JSON.parse(jsonString) as ErrorPayload;+ /**+ * OpenAI-compatible bodies nest their `code` and `type` under `error`. When the top level names+ * neither, that envelope is the payload a renderer reads; a top-level `type`, even a generic one+ * like Anthropic's `"error"`, keeps the body as it is.+ */+ const envelope = readObject(json, 'error');+ const topLevelKey = readString(json, 'code') ?? readString(json, 'type');+ const nestedKey =+ topLevelKey == null+ ? (readString(envelope, 'code') ?? readString(envelope, 'type'))+ : undefined;+ const payload = nestedKey != null && envelope != null ? envelope : json;+ const errorKey = topLevelKey ?? nestedKey;++ if (errorKey != null) {+ const Renderer = errorRenderers[errorKey];+ if (Renderer != null) {+ return <Renderer json={payload} text={text} message={message} />;+ }+ const copyKey = errorCopy[errorKey];+ if (copyKey != null) {+ return localize(copyKey);+ }+ }++ return <UnclassifiedError json={json} text={text} message={message} />;+};++export default Error;diff --git a/client/src/components/Messages/Content/Error/parts.tsx b/client/src/components/Messages/Content/Error/parts.tsxnew file mode 100644index 0000000000..1889161739--- /dev/null+++ b/client/src/components/Messages/Content/Error/parts.tsx@@ -0,0 +1,369 @@+import { useContext, useId, useMemo, useState } from 'react';+import { Button } from '@librechat/client';+import { ChevronRight } from 'lucide-react';+import {+ Constants,+ alternateName,+ getEndpointField,+ isAgentsEndpoint,+ isEphemeralAgentId,+ stripAgentIdSuffix,+ parseEphemeralAgentId,+} from 'librechat-data-provider';+import type {+ Agent,+ TConfig,+ TAgentsMap,+ EModelEndpoint,+ TEndpointsConfig,+} from 'librechat-data-provider';+import type { ErrorSource } from './source';+import { isUserProvidedEndpointConfig } from '~/components/Nav/SettingsTabs/ProviderKeys/utils';+import { useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';+import { supportsCompaction } from '~/hooks/Chat/useCompactConversation';+import { useAgentsMapContext } from '~/Providers/AgentsMapContext';+import { useExpandCollapse, useLocalize } from '~/hooks';+import { ChatContext } from '~/Providers/ChatContext';+import { cn } from '~/utils';++/** A value as `JSON.parse` produces it. */+export type JsonValue = string | number | boolean | null | JsonValue[] | ErrorPayload;++/** A parsed error payload. Producers are free-form, so every field is read defensively. */+export type ErrorPayload = { [key: string]: JsonValue | undefined };++export type ErrorRendererProps = {+ /** The payload parsed out of the message text. */+ json: ErrorPayload;+ /** The message text as persisted, including any prefix around the payload. */+ text: string;+ /** The row this error belongs to; absent only where no row supplies an `ErrorSource`. */+ message?: ErrorSource;+};++/** The fallback renderer also runs when there is no payload at all. */+export type UnclassifiedErrorProps = Omit<ErrorRendererProps, 'json'> & { json?: ErrorPayload };++/**+ * Provider error codes that are not LibreChat's own. They reach the client when a provider's error+ * body is persisted as the message text, which is also why they are plain strings rather than+ * `ErrorTypes` members.+ */+export const ProviderErrorCodes = {+ INVALID_API_KEY: 'invalid_api_key',+ INSUFFICIENT_QUOTA: 'insufficient_quota',+} as const;++export function readString(json: ErrorPayload | undefined, key: string): string | undefined {+ const value = json?.[key];+ return typeof value === 'string' && value.length > 0 ? value : undefined;+}++export function readNumber(json: ErrorPayload | undefined, key: string): number | undefined {+ const value = json?.[key];+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value;+ }+ /** Limiter payloads cross the wire as JSON, but a stored `max` may be a numeric string. */+ if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {+ return Number(value);+ }+ return undefined;+}++export function readObject(json: ErrorPayload | undefined, key: string): ErrorPayload | undefined {+ const value = json?.[key];+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;+}++/** The name a reader recognizes for an endpoint id. */+export const getProviderName = (endpoint: string): string =>+ (alternateName[endpoint] as string | undefined) ?? endpoint;++export type ErrorEndpoint = {+ /** The endpoint the failed request ran against, when it is knowable. */+ endpoint?: string;+ endpointType?: EModelEndpoint;+ /** Display name for the provider; undefined when the endpoint cannot be resolved. */+ provider?: string;+ /** The model that produced the failure. */+ model?: string;+ /** The saved agent that produced the failure, when the agents map can resolve it. */+ agent?: Agent;+ /**+ * The reader, not the deployment, maintains the endpoint's credentials (key, URL or both).+ * Undefined where no endpoint configuration is available to this viewer, as on a shared link.+ */+ userProvidesCredentials?: boolean;+ /**+ * Manual context compaction can be triggered for this conversation. It is only offered from the+ * chat composer's context usage popover, so neither a surface outside the chat (search, a shared+ * link) nor a deployment that hides that indicator has compaction to suggest.+ */+ compactionAvailable: boolean;+ endpointsConfig?: TEndpointsConfig;+};++/** What an agent ran against: its provider (an endpoint id) and model, and the saved agent if any. */+type AgentIdentity = { agent?: Agent; endpoint?: string; model?: string };++/**+ * Resolves an agent id the way the transcript's sibling headers do: a saved agent through the+ * agents map (without the `____N` suffix parallel runs append), an ephemeral agent through the+ * endpoint and model its id encodes.+ */+function resolveAgentId(agentsMap: TAgentsMap | undefined, agentId: string): AgentIdentity {+ const agent = agentsMap?.[stripAgentIdSuffix(agentId)];+ if (agent != null) {+ return { agent, endpoint: agent.provider || undefined, model: agent.model ?? undefined };+ }+ const ephemeral = isEphemeralAgentId(agentId) ? parseEphemeralAgentId(agentId) : undefined;+ return ephemeral == null ? {} : { endpoint: ephemeral.endpoint, model: ephemeral.model };+}++/**+ * Who ran the failing part of an agents row. The part's own agent (its parallel lane's, or the one+ * a handoff made active) comes first. Otherwise the row's `model` says: a saved agent's rows,+ * including the live placeholder the client builds, store the agent id there, and an ephemeral+ * agent's store its encoded id or the model itself. The conversation's agent is read only for an+ * error with no row at all. An id that resolves to nothing names nothing, so neither an agent id+ * nor a placeholder is ever shown as a model, while a plain model name is kept.+ */+function resolveAgentRow(+ agentsMap: TAgentsMap | undefined,+ {+ partAgentId,+ rowModel,+ conversationAgentId,+ }: { partAgentId?: string; rowModel?: string; conversationAgentId?: string },+): AgentIdentity {+ const agentId = partAgentId ?? conversationAgentId;+ if (agentId != null) {+ return resolveAgentId(agentsMap, agentId);+ }+ if (rowModel == null || rowModel === Constants.EPHEMERAL_AGENT_ID) {+ return {};+ }+ const resolved = resolveAgentId(agentsMap, rowModel);+ if (resolved.endpoint != null || !isEphemeralAgentId(rowModel)) {+ return resolved;+ }+ return { model: rowModel };+}++/**+ * Whether the reader maintains an endpoint's credentials. A user-provided base URL counts even with+ * a deployment key: the server then reads both the key and the URL from the reader's own record,+ * so the key dialog, which edits both, is the fix for its failures too.+ */+const readerOwnsCredentials = (config?: TConfig | null): boolean =>+ isUserProvidedEndpointConfig(config) || config?.userProvideURL === true;++/** Without a loaded endpoint configuration, ownership is unknown rather than the deployment's. */+function resolveCredentialOwnership(+ endpointsConfig: TEndpointsConfig | undefined,+ endpoint: string | undefined,+): boolean | undefined {+ if (endpoint == null) {+ return false;+ }+ return endpointsConfig == null ? undefined : readerOwnsCredentials(endpointsConfig[endpoint]);+}++/**+ * Resolves who produced the failure.+ *+ * Error content renders in the chat, in search results and in shared links. Only the chat surface+ * mounts `ChatContext`, and a shared link is read by a viewer whose query client is not+ * authenticated, so the endpoint queries stay disabled outside the chat rather than firing a+ * request that would resolve to a login redirect. Copy therefore has to work without a provider+ * name, which is why `provider` and `model` are optional.+ *+ * A saved agent's row names the `agents` endpoint and carries the agent id as its model, while the+ * request ran against the agent's own provider and model, so those are what identity, key+ * ownership and the key dialog resolve against; after a handoff, that is the agent the handoff+ * made active, and in a parallel run, the agent of the error's own lane. An endpoint named by the+ * payload itself outranks all of them. Compaction is a+ * conversation action, so it stays keyed to the row's endpoint.+ */+export function useErrorEndpoint(source?: ErrorSource, payloadEndpoint?: string): ErrorEndpoint {+ const chat = useContext(ChatContext);+ const agentsMap = useAgentsMapContext();+ const inChat = chat != null;+ const { data: endpointsConfig } = useGetEndpointsQuery({ enabled: inChat });+ const { data: startupConfig } = useGetStartupConfig({ enabled: inChat });++ /**+ * A row's own identity is authoritative even where it lacks a field: borrowing the conversation's+ * current selection, or its current agent, would attribute an old failure to whatever the reader+ * picked since. Only an error rendered with no row at all reads the conversation.+ */+ const identity = source ?? chat?.conversation ?? undefined;+ const rowEndpoint = identity?.endpoint ?? undefined;+ const rowModel = identity?.model ?? undefined;+ const conversationAgentId =+ source == null && chat?.conversation?.agent_id !== Constants.EPHEMERAL_AGENT_ID+ ? (chat?.conversation?.agent_id ?? undefined)+ : undefined;+ const partAgentId = source?.partAgentId;++ return useMemo(() => {+ const agentRow = partAgentId != null || isAgentsEndpoint(rowEndpoint);+ const agentIdentity = agentRow+ ? resolveAgentRow(agentsMap, { partAgentId, rowModel, conversationAgentId })+ : undefined;+ const rowProvider = agentRow ? agentIdentity?.endpoint : rowEndpoint;+ const endpoint = payloadEndpoint ?? rowProvider;+ const endpointType = endpoint+ ? (getEndpointField(endpointsConfig, endpoint, 'type') as EModelEndpoint | undefined)+ : undefined;+ return {+ endpoint,+ endpointType,+ provider: endpoint ? getProviderName(endpoint) : undefined,+ model: agentRow ? agentIdentity?.model : rowModel,+ agent: agentIdentity?.agent,+ userProvidesCredentials: resolveCredentialOwnership(endpointsConfig, endpoint),+ compactionAvailable:+ inChat &&+ startupConfig?.compactionEnabled === true &&+ startupConfig.interface?.contextUsage !== false &&+ supportsCompaction(rowEndpoint),+ endpointsConfig,+ };+ }, [+ inChat,+ rowEndpoint,+ rowModel,+ conversationAgentId,+ partAgentId,+ payloadEndpoint,+ agentsMap,+ endpointsConfig,+ startupConfig?.compactionEnabled,+ startupConfig?.interface?.contextUsage,+ ]);+}++/** Stacks an error's sentences, details and actions without inheriting prose spacing. */+export function ErrorBody({ children }: { children: React.ReactNode }) {+ return <div className="flex flex-col gap-2">{children}</div>;+}++/**+ * Secondary information a reader only wants after the headline: a provider's own message, a token+ * budget, a generation breakdown. Collapsed by default and rendered as text rather than through+ * `CodeBlock`, which frames a detail in a code bar and a dark slab that reads as output.+ *+ * Motion is `useExpandCollapse`, the same `grid-template-rows` tween the tool rows and activity+ * phases in the transcript use, so a detail inside an error box opens on the curve the rest of the+ * message content already moves on (and inherits its reduced-motion and `inert` handling).+ *+ * The body stays mounted while collapsed. That is what makes the card resize rather than jump: a+ * collapsed row still contributes its width to the box's intrinsic size, so the box only ever+ * changes height, and it changes it on the tween instead of in one step. The gap to the trigger+ * lives inside the animated element for the same reason — as a margin outside it, it would appear+ * in a single step once the height reached zero.+ */+export function ErrorDetails({ label, children }: { label: string; children: React.ReactNode }) {+ const [open, setOpen] = useState(false);+ const panelId = useId();+ const { style: panelStyle, ref: panelRef } = useExpandCollapse(open);++ return (+ <div>+ <button+ type="button"+ onClick={() => setOpen((expanded) => !expanded)}+ aria-expanded={open}+ aria-controls={panelId}+ className="flex items-center gap-1 rounded-md text-xs font-medium text-text-secondary transition-colors hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary"+ >+ {label}+ <ChevronRight+ className={cn(+ 'size-3.5 transition-transform duration-300 [transition-timing-function:cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none',+ open && 'rotate-90',+ )}+ aria-hidden="true"+ />+ </button>+ <div id={panelId} style={panelStyle} aria-hidden={!open}>+ <div ref={panelRef} className="overflow-hidden">+ <div className="mt-1 whitespace-pre-wrap break-words text-xs text-text-secondary">+ {children}+ </div>+ </div>+ </div>+ </div>+ );+}++export function ErrorActions({ children }: { children: React.ReactNode }) {+ return <div className="flex flex-wrap items-center gap-2">{children}</div>;+}++/** The one thing a reader can do about the failure, next to the sentence explaining it. */+export function ErrorAction({+ onClick,+ children,+}: {+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ /** One step tighter than the button default (8px) so the control reads as nested inside the+ * error card's 12px corner rather than echoing it. */+ <Button type="button" size="sm" className="rounded-md" onClick={onClick}>+ {children}+ </Button>+ );+}++export const formatNumber = (value: number): string => new Intl.NumberFormat().format(value);++/** Token credits are a float balance; two decimals, matching the balance settings row. */+export const formatCredits = (value: number): string =>+ new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value);++const isoTimestamp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;++/**+ * Formats a stored timestamp in the reader's locale. Only epoch milliseconds and ISO 8601 strings+ * are parsed: rows persisted by older servers carry an expiry in the server's own locale format,+ * which another locale can misread (a day-first date read month-first), so any other string is+ * shown as persisted.+ */+export function formatTimestamp(value: string | number): string {+ if (typeof value === 'string' && !isoTimestamp.test(value)) {+ return value;+ }+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) {+ return String(value);+ }+ return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(+ date,+ );+}++/** `m:ss`, or `h:mm:ss` past an hour — the shape a countdown is read in. */+export function formatDuration(milliseconds: number): string {+ const total = Math.max(0, Math.ceil(milliseconds / 1000));+ const seconds = total % 60;+ const minutes = Math.floor(total / 60) % 60;+ const hours = Math.floor(total / 3600);+ const pad = (value: number) => value.toString().padStart(2, '0');+ return hours > 0 ? `${hours}:${pad(minutes)}:${pad(seconds)}` : `${minutes}:${pad(seconds)}`;+}++/** "minute" or "45 minutes", for limit copy that ends in "per …". */+export function useWindowLabel(windowInMinutes?: number): string | undefined {+ const localize = useLocalize();+ if (windowInMinutes == null) {+ return undefined;+ }+ return windowInMinutes === 1+ ? localize('com_error_window_minute')+ : localize('com_error_window_minutes', { 0: formatNumber(windowInMinutes) });+}diff --git a/client/src/components/Messages/Content/Error/registry.ts b/client/src/components/Messages/Content/Error/registry.tsnew file mode 100644index 0000000000..1fc44b1a95--- /dev/null+++ b/client/src/components/Messages/Content/Error/registry.ts@@ -0,0 +1,78 @@+import { ErrorTypes, ViolationTypes } from 'librechat-data-provider';+import type { ComponentType } from 'react';+import type { ErrorRendererProps } from './parts';+import type { TranslationKeys } from '~/hooks';+import { ProviderErrorCodes } from './parts';+import ProviderError from './ProviderError';+import UserKeyError from './UserKeyError';+import BalanceError from './BalanceError';+import ContextError from './ContextError';+import ModelError from './ModelError';+import LimitError from './LimitError';+import AgentError from './AgentError';++/**+ * Codes whose whole rendering is one localized sentence.+ *+ * Anything needing a provider name, a number, a permission check or an action belongs in+ * `errorRenderers` instead.+ */+export const errorCopy: Record<string, TranslationKeys> = {+ [ErrorTypes.MODERATION]: 'com_error_moderation',+ [ErrorTypes.INVALID_ACTION]: 'com_error_invalid_action_error',+ [ErrorTypes.MODELS_NOT_LOADED]: 'com_error_models_not_loaded',+ [ErrorTypes.GOOGLE_TOOL_CONFLICT]: 'com_error_google_tool_conflict',+ [ErrorTypes.GOOGLE_VIDEO_UNPROCESSABLE]: 'com_error_google_video_unprocessable',+ [ErrorTypes.RESOURCE_RECOVERY_REQUIRED]: 'com_error_resource_recovery_required',+ [ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED]:+ 'com_error_stateful_code_environment_not_allowed',+ [ErrorTypes.STREAM_EXPIRED]: 'com_error_stream_expired',+ [ErrorTypes.MODEL_NOT_FOUND]: 'com_error_model_not_found',+ [ErrorTypes.MODEL_RATE_LIMIT]: 'com_error_model_rate_limit',+ [ErrorTypes.COMPACTION_FAILED]: 'com_error_compaction_failed',+ [ErrorTypes.AUTH_FAILED]: 'com_error_auth_failed',+ [ErrorTypes.AUTH_RATE_LIMITED]: 'com_error_auth_rate_limited',+ [ErrorTypes.AUTH_BANNED]: 'com_error_auth_banned',+ [ErrorTypes.AUTH_CROSS_ORIGIN]: 'com_auth_error_login_cross_origin',+ [ViolationTypes.BAN]: 'com_error_ban',+ [ViolationTypes.CONVO_ACCESS]: 'com_error_convo_access',+ [ViolationTypes.TOOL_CALL_LIMIT]: 'com_error_tool_call_limit',+ [ViolationTypes.SHARE_LIMIT]: 'com_error_share_limit',+ [ViolationTypes.LOGINS]: 'com_error_logins',+ [ViolationTypes.REGISTRATIONS]: 'com_error_registrations',+ [ViolationTypes.RESET_PASSWORD_LIMIT]: 'com_error_reset_password_limit',+ [ViolationTypes.VERIFY_EMAIL_LIMIT]: 'com_error_verify_email_limit',+ [ViolationTypes.NON_BROWSER]: 'com_error_non_browser',+ [ViolationTypes.GENERAL]: 'com_error_request_blocked',+};++/** Codes whose copy depends on payload fields, deployment capabilities or the user's rights. */+export const errorRenderers: Record<string, ComponentType<ErrorRendererProps>> = {+ [ErrorTypes.NO_USER_KEY]: UserKeyError,+ [ErrorTypes.EXPIRED_USER_KEY]: UserKeyError,+ [ErrorTypes.INVALID_USER_KEY]: UserKeyError,+ [ErrorTypes.NO_BASE_URL]: UserKeyError,+ [ErrorTypes.INVALID_BASE_URL]: UserKeyError,+ [ProviderErrorCodes.INVALID_API_KEY]: UserKeyError,+ [ProviderErrorCodes.INSUFFICIENT_QUOTA]: UserKeyError,+ [ErrorTypes.INVALID_AGENT_PROVIDER]: AgentError,+ [ErrorTypes.MISSING_MODEL]: ModelError,+ [ErrorTypes.ENDPOINT_MODELS_NOT_LOADED]: ModelError,+ [ErrorTypes.UPSTREAM_MODEL_ERROR]: ModelError,+ [ErrorTypes.CODE_WORKSPACE_UNAVAILABLE]: ModelError,+ [ViolationTypes.ILLEGAL_MODEL_REQUEST]: ModelError,+ [ErrorTypes.REFUSAL]: ProviderError,+ [ErrorTypes.GOOGLE_ERROR]: ProviderError,+ [ErrorTypes.INVALID_REQUEST]: ProviderError,+ [ErrorTypes.NO_SYSTEM_MESSAGES]: ProviderError,+ [ErrorTypes.INPUT_LENGTH]: ContextError,+ [ErrorTypes.EMPTY_MESSAGES]: ContextError,+ [ErrorTypes.FINAL_CONTEXT_OVERFLOW]: ContextError,+ [ErrorTypes.COMPACTION_SKIPPED]: ContextError,+ [ViolationTypes.TOKEN_BALANCE]: BalanceError,+ [ViolationTypes.MESSAGE_LIMIT]: LimitError,+ [ViolationTypes.CONCURRENT]: LimitError,+ [ViolationTypes.FILE_UPLOAD_LIMIT]: LimitError,+ [ViolationTypes.TTS_LIMIT]: LimitError,+ [ViolationTypes.STT_LIMIT]: LimitError,+};diff --git a/client/src/components/Messages/Content/Error/source.tsx b/client/src/components/Messages/Content/Error/source.tsxnew file mode 100644index 0000000000..79394d0f9a--- /dev/null+++ b/client/src/components/Messages/Content/Error/source.tsx@@ -0,0 +1,110 @@+import { createContext, useContext, useMemo } from 'react';+import { ContentTypes } from 'librechat-data-provider';+import type { TMessage } from 'librechat-data-provider';+import type { ReactNode } from 'react';+import { useMessageContext } from '~/Providers/MessageContext';++/** The fields of a message that say who produced a failure and when. */+export type ErrorSource = Pick<TMessage, 'endpoint' | 'model' | 'createdAt'> & {+ /**+ * The agent that ran the failing part: the agent of its own lane in a parallel run, otherwise+ * the agent a handoff earlier in the row made active.+ */+ partAgentId?: string;+};++/** Where a row's content changes agents, and which error parts name their own. */+type AgentPositions = {+ /** Positions of `AGENT_UPDATE` parts, in content order. */+ handoffs: Array<{ index: number; agentId: string }>;+ /** Error parts a parallel run stamped with the agent of their lane, by position. */+ owners: Record<number, string>;+};++type RowSource = { source: ErrorSource; positions: AgentPositions };++const ErrorSourceContext = createContext<RowSource | undefined>(undefined);++function findAgentPositions(content: TMessage['content']): AgentPositions {+ const positions: AgentPositions = { handoffs: [], owners: {} };+ for (let index = 0; index < (content?.length ?? 0); index++) {+ const part = content?.[index];+ if (part?.type === ContentTypes.ERROR && part.agentId) {+ positions.owners[index] = part.agentId;+ continue;+ }+ if (part?.type !== ContentTypes.AGENT_UPDATE) {+ continue;+ }+ const agentId = part[ContentTypes.AGENT_UPDATE]?.agentId;+ if (agentId) {+ positions.handoffs.push({ index, agentId });+ }+ }+ return positions;+}++/** The agent that ran the part at `partIndex`: its own lane's, else the last handoff before it. */+function findPartAgent(+ { handoffs, owners }: AgentPositions,+ partIndex: number,+): string | undefined {+ const owner = owners[partIndex];+ if (owner != null) {+ return owner;+ }+ let agentId: string | undefined;+ for (const handoff of handoffs) {+ if (handoff.index >= partIndex) {+ break;+ }+ agentId = handoff.agentId;+ }+ return agentId;+}++/**+ * Supplies a message row's identity to the errors rendered inside it.+ *+ * A failure during a run is persisted as an error content part, and `Part` renders it without the+ * message it belongs to. Without this, its copy could only name the conversation's current+ * endpoint and model, which stop being the ones that failed as soon as the reader switches models.+ *+ * One row can hold several agents' work: a sequential run hands off through `AGENT_UPDATE` parts,+ * and a parallel run stamps each part with the agent of its lane. The row therefore also records+ * where those agents sit, and an error part resolves its own agent from its position (the+ * absolute `partIndex` its `MessageContext` carries). The positions are keyed by value: a+ * streaming row, whose content changes on every token, keeps one context value until an agent+ * position actually changes, so its error parts do not re-render in between.+ */+export function ErrorSourceProvider({+ message,+ children,+}: {+ message: Pick<TMessage, 'endpoint' | 'model' | 'createdAt' | 'content'>;+ children: ReactNode;+}) {+ const { endpoint, model, createdAt, content } = message;+ const positionsKey = useMemo(() => JSON.stringify(findAgentPositions(content)), [content]);+ const row = useMemo<RowSource>(+ () => ({+ source: { endpoint, model, createdAt },+ positions: JSON.parse(positionsKey) as AgentPositions,+ }),+ [endpoint, model, createdAt, positionsKey],+ );+ return <ErrorSourceContext.Provider value={row}>{children}</ErrorSourceContext.Provider>;+}++/** The identity of the row rendering this error, resolved to the agent that ran its part. */+export function useErrorSource(): ErrorSource | undefined {+ const row = useContext(ErrorSourceContext);+ const { partIndex } = useMessageContext();+ return useMemo(() => {+ if (row == null) {+ return undefined;+ }+ const partAgentId = partIndex == null ? undefined : findPartAgent(row.positions, partIndex);+ return partAgentId == null ? row.source : { ...row.source, partAgentId };+ }, [row, partIndex]);+}diff --git a/client/src/components/Messages/Content/__tests__/Error.spec.tsx b/client/src/components/Messages/Content/__tests__/Error.spec.tsxindex da800ed60f..0c548c5fb6 100644--- a/client/src/components/Messages/Content/__tests__/Error.spec.tsx+++ b/client/src/components/Messages/Content/__tests__/Error.spec.tsx@@ -1,13 +1,31 @@import React from 'react';-import { ErrorTypes } from 'librechat-data-provider';-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';+import {+ ErrorTypes,+ SystemRoles,+ ContentTypes,+ ViolationTypes,+ EModelEndpoint,+} from 'librechat-data-provider';+import type { Agent, TConversation, TMessage } from 'librechat-data-provider';+import type { ReactElement } from 'react';+import { AgentsMapContext } from '~/Providers/AgentsMapContext';+import { MessageContext } from '~/Providers/MessageContext';import translation from '~/locales/en/translation.json';+import { ErrorSourceProvider } from '../Error/source';+import { ChatContext } from '~/Providers/ChatContext';+import { AuthContext } from '~/hooks/AuthContext';import Error from '../Error';-/**- * Resolves keys against the real English catalog rather than a stub, so a typed error whose- * localization key is missing or misspelled fails here instead of reaching users as a raw key.- */+let mockEndpointsData: Record<string, Record<string, unknown>> | undefined = {+ openAI: { userProvide: true },+};+let mockStartupData: { compactionEnabled: boolean; interface?: { contextUsage?: boolean } } = {+ compactionEnabled: false,+};+let mockAccess: Record<string, boolean> = {};++/** Keep this unit spec independent of query providers while exercising the real renderer hooks. */jest.mock('~/hooks', () => ({useLocalize:() =>@@ -21,22 +39,151 @@ jest.mock('~/hooks', () => ({values[name] != null ? String(values[name]) : match,);},+ useHasAccess: ({ permission }: { permission: string }) => mockAccess[permission] === true,+ /** Mirrors the real hook's contract — a grid style plus a ref — without pulling `useMediaQuery`+ * and its `matchMedia` dependency into a spec that asserts copy, not motion. */+ useExpandCollapse: (isExpanded: boolean) => ({+ style: {+ display: 'grid',+ gridTemplateRows: isExpanded ? '1fr' : '0fr',+ opacity: isExpanded ? 1 : 0,+ },+ ref: { current: null },+ }),+}));++jest.mock('~/data-provider', () => ({+ useGetEndpointsQuery: jest.fn(() => ({ data: mockEndpointsData })),+ useGetStartupConfig: jest.fn(() => ({ data: mockStartupData })),+}));++jest.mock('~/components/Input/SetKeyDialog', () => ({+ SetKeyDialog: () => null,}));const catalog = translation as Record<string, string>;-const upstreamFallback = 'The model provider could not complete this request.';+const providerMessage = {+ endpoint: 'openAI',+ model: 'gpt-4o',+ createdAt: new Date('2026-09-13T12:00:00.000Z'),+} as unknown as TMessage;-describe('Error — typed provider errors', () => {- it('renders the localized copy for a rejected Google video', () => {- /** The exact payload `resolveGoogleVideoError` emits from the server. */- const payload = JSON.stringify({ type: ErrorTypes.GOOGLE_VIDEO_UNPROCESSABLE });- render(<Error text={payload} />);+type RenderSurface = {+ /** The row identity an error content part inherits from `ErrorSourceProvider`. */+ source?: TMessage;+ /** The absolute content index `MessageContext` gives an error part rendered inside a row. */+ partIndex?: number;+ /** Mounts `ChatContext`, as the chat surface does, with this conversation. */+ conversation?: Partial<TConversation>;+ agents?: Record<string, Agent>;+ role?: SystemRoles;+};- expect(screen.getByText(catalog.com_error_google_video_unprocessable)).toBeInTheDocument();+function renderError(+ payload: Record<string, unknown> | string,+ message?: TMessage,+ surface: RenderSurface = {},+) {+ const text = typeof payload === 'string' ? payload : JSON.stringify(payload);+ let tree: ReactElement = <Error text={text} message={message} />;+ if (surface.partIndex != null) {+ tree = (+ <MessageContext.Provider+ value={{ messageId: 'response-1', isExpanded: true, partIndex: surface.partIndex }}+ >+ {tree}+ </MessageContext.Provider>+ );+ }+ if (surface.source != null) {+ tree = <ErrorSourceProvider message={surface.source}>{tree}</ErrorSourceProvider>;+ }+ if (surface.agents != null) {+ tree = <AgentsMapContext.Provider value={surface.agents}>{tree}</AgentsMapContext.Provider>;+ }+ if (surface.conversation != null) {+ const chat = { conversation: surface.conversation } as unknown as React.ContextType<+ typeof ChatContext+ >;+ tree = <ChatContext.Provider value={chat}>{tree}</ChatContext.Provider>;+ }+ if (surface.role != null) {+ const auth = { user: { role: surface.role } } as unknown as React.ContextType<+ typeof AuthContext+ >;+ tree = <AuthContext.Provider value={auth}>{tree}</AuthContext.Provider>;+ }+ return render(tree);+}++function expectReadable() {+ const output = document.body.textContent ?? '';+ expect(output).not.toMatch(/com_error_[A-Za-z0-9_]+/);+ expect(output).not.toContain(+ "Something went wrong. Here's the specific error message we encountered:",+ );+}+function localized(key: string, ...values: string[]) {+ return values.reduce((copy, value, index) => copy.replace(`{{${index}}}`, value), catalog[key]);+}++const numberFormat = new Intl.NumberFormat();++/** Mounts the chat surface, the only one whose composer can compact a conversation. */+const chatConversation: Partial<TConversation> = {+ endpoint: EModelEndpoint.openAI,+ model: 'gpt-4o',+};++/** A violation row, stamped by the server when it saved the failure (just now by default). */+const limitRow = (createdAt = Date.now()) =>+ ({+ endpoint: 'openAI',+ model: 'gpt-4o',+ createdAt: new Date(createdAt).toISOString(),+ }) as TMessage;+const dateTimeFormat = new Intl.DateTimeFormat(undefined, {+ dateStyle: 'medium',+ timeStyle: 'short',+});++beforeEach(() => {+ mockEndpointsData = { openAI: { userProvide: true } };+ mockStartupData = { compactionEnabled: false };+ mockAccess = {};+});++describe('Error — every client-facing error type', () => {+ /** The seeded gallery refuses to run while a member lacks a case; this is the renderer's half. */+ it.each([...Object.values(ErrorTypes), ...Object.values(ViolationTypes)])(+ 'renders %s as authored copy rather than the unknown-failure fallback',+ (type) => {+ renderError({ type }, providerMessage);++ expect(screen.queryByText(catalog.com_error_unknown)).not.toBeInTheDocument();+ expect(document.body.textContent).not.toContain('{');+ expectReadable();+ },+ );+});++describe('Error — reader-facing provider and fallback copy', () => {+ it.each([+ [ErrorTypes.INVALID_REQUEST, 'com_error_invalid_request_error', 'OpenAI'],+ [ErrorTypes.NO_SYSTEM_MESSAGES, 'com_error_no_system_messages', 'OpenAI'],+ [ErrorTypes.INVALID_ACTION, 'com_error_invalid_action_error', undefined],+ ])('resolves %s to a sentence rather than an unresolved key', (type, key, provider) => {+ renderError({ type }, provider ? providerMessage : undefined);++ expect(screen.getByText(localized(key, ...(provider ? [provider] : [])))).toBeInTheDocument();+ expectReadable();});- it('names video length, the dominant cause, in the copy', () => {- expect(catalog.com_error_google_video_unprocessable).toMatch(/too long/i);+ it('renders the localized copy for a rejected Google video', () => {+ renderError({ type: ErrorTypes.GOOGLE_VIDEO_UNPROCESSABLE });++ expect(screen.getByText(catalog.com_error_google_video_unprocessable)).toBeInTheDocument();+ expectReadable();});it.each([@@ -44,53 +191,200 @@ describe('Error — typed provider errors', () => {['MODEL_RATE_LIMIT', 'com_error_model_rate_limit'],])('replaces LangChain %s attribution with localized guidance', (code, key) => {const raw = `An error occurred while processing the request: 404 404 page not found Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${code}/`;- render(<Error text={raw} />);+ renderError(raw);expect(screen.getByText(catalog[key])).toBeInTheDocument();expect(screen.queryByText(/langchain\.com/i)).not.toBeInTheDocument();+ expectReadable();});- it.each([- [ErrorTypes.MODEL_NOT_FOUND, 'com_error_model_not_found'],- [ErrorTypes.MODEL_RATE_LIMIT, 'com_error_model_rate_limit'],- [ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, 'com_error_code_workspace_unavailable'],- ])('localizes the typed %s payload the server now emits', (type, key) => {- render(<Error text={JSON.stringify({ type })} />);+ it('keeps provider text for a LangChain code without localized copy, minus the URL', () => {+ const raw =+ 'An error occurred while processing the request: could not parse output\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/OUTPUT_PARSING_FAILURE/\n';+ renderError(raw);- expect(screen.getByText(catalog[key])).toBeInTheDocument();+ expect(screen.getByText(/could not parse output/)).toBeInTheDocument();+ expect(screen.queryByText(/langchain\.com/i)).not.toBeInTheDocument();+ expectReadable();+ });++ it('shows an unmapped payload message without exposing its JSON representation', () => {+ const message = 'The provider returned a code the client does not classify.';+ renderError({ code: 'im_a_teapot', message }, providerMessage);++ expect(screen.getByText(message)).toBeInTheDocument();+ const output = document.body.textContent ?? '';+ expect(output).not.toContain('{');+ expect(output).not.toContain('"code"');+ expectReadable();});- it('localizes an upstream model failure without a status', () => {- render(- <Error- text={`${upstreamFallback}\n${JSON.stringify({ type: ErrorTypes.UPSTREAM_MODEL_ERROR })}`}- />,+ it('reads a provider message nested under `error`, as OpenAI-style bodies carry it', () => {+ const providerText = 'Rate limit reached for gpt-4o in organization org-123 on tokens per min.';+ renderError(+ { error: { message: providerText, type: 'tokens', code: 'rate_limit_exceeded' } },+ providerMessage,);- expect(screen.getByText(catalog.com_error_upstream_model)).toBeInTheDocument();+ expect(screen.getByText(localized('com_error_provider_failed', 'OpenAI'))).toBeInTheDocument();+ expect(screen.getByText(providerText)).toBeInTheDocument();+ expect(screen.queryByText(catalog.com_error_unknown)).not.toBeInTheDocument();+ expect(document.body.textContent).not.toContain('{');+ expectReadable();+ });++ it('dispatches a provider code nested under `error` to its renderer', () => {+ renderError(+ {+ error: {+ code: 'invalid_api_key',+ type: 'invalid_request_error',+ message: 'Incorrect API key provided: sk-****.',+ },+ },+ providerMessage,+ );++ expect(screen.getByText(localized('com_error_invalid_api_key', 'OpenAI'))).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_key_update }),+ ).toBeInTheDocument();+ expectReadable();+ });++ it('dispatches a nested invalid-request type and keeps its message as the detail', () => {+ const detail = "Invalid value for 'temperature': must be between 0 and 2.";+ renderError({ error: { type: 'invalid_request_error', message: detail } }, providerMessage);++ expect(+ screen.getByText(localized('com_error_invalid_request_error', 'OpenAI')),+ ).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: catalog.com_error_details_provider }));+ expect(screen.getByText(detail)).toBeInTheDocument();});- it('localizes an upstream model failure with its safe status', () => {- render(- <Error- text={`${upstreamFallback}\n${JSON.stringify({- type: ErrorTypes.UPSTREAM_MODEL_ERROR,- status: 529,- })}`}- />,+ /** A top-level `type` names the body, even Anthropic's generic `"error"`, so it is not unwrapped. */+ it('does not unwrap a body whose top level already names a type', () => {+ renderError(+ { type: 'error', error: { type: 'invalid_request_error', message: 'prompt is too long' } },+ { endpoint: EModelEndpoint.anthropic, model: 'claude-sonnet-4-5' } as TMessage,);expect(- screen.getByText(catalog.com_error_upstream_model_status.replace('{{0}}', '529')),+ screen.getByText(localized('com_error_provider_failed', 'Anthropic')),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(localized('com_error_invalid_request_error', 'Anthropic')),+ ).not.toBeInTheDocument();+ expect(screen.getByText('prompt is too long')).toBeInTheDocument();+ });++ /** `getUserFacingRequestError` prefixes the SDK's message, which for Anthropic embeds the body. */+ it('keeps the reason from a provider body embedded in the persisted text', () => {+ const reason = 'prompt is too long: 250000 tokens > 200000 maximum';+ const body = JSON.stringify({+ type: 'error',+ error: { type: 'invalid_request_error', message: reason },+ request_id: 'req_011',+ });+ renderError(`An error occurred while processing the request: 400 ${body}`, {+ endpoint: EModelEndpoint.anthropic,+ model: 'claude-sonnet-4-5',+ } as TMessage);++ expect(+ screen.getByText(localized('com_error_provider_failed', 'Anthropic')),+ ).toBeInTheDocument();+ expect(+ screen.getByText(`An error occurred while processing the request: 400 ${reason}`),).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('{');+ expectReadable();+ });++ it('shows the complete long provider message after its disclosure is opened', () => {+ const providerText =+ `The upstream gateway rejected the request. ${'Retry advice and a stack frame repeated to exceed the client truncation cap. '.repeat(8)}`.trim();+ renderError(providerText, providerMessage);++ expect(screen.queryByText(/Something went wrong/)).not.toBeInTheDocument();+ expect(document.body.textContent).not.toContain('...');+ fireEvent.click(screen.getByRole('button', { name: catalog.com_error_details_provider }));+ expect(document.body.textContent).toContain(providerText);+ expectReadable();+ });+});++describe('Error — provider and model identity', () => {+ it('names the selected model for a refusal without stale Claude copy', () => {+ renderError(+ { type: ErrorTypes.REFUSAL, info: "I can't help with that request." },+ providerMessage,+ );++ expect(screen.getByText(localized('com_error_refusal', 'gpt-4o'))).toBeInTheDocument();+ expect(document.body.textContent).not.toMatch(/Claude|Sonnet/i);+ expectReadable();+ });++ /** `ModelEndHandler` persists the refusal metadata object itself as `info`. */+ it('offers the explanation Anthropic reports under stop_details', () => {+ const explanation = 'The request could enable malware development.';+ renderError(+ {+ type: ErrorTypes.REFUSAL,+ info: {+ stop_reason: 'refusal',+ stop_sequence: null,+ stop_details: { type: 'refusal', category: 'cyber', explanation },+ },+ },+ providerMessage,+ );++ const disclosure = screen.getByRole('button', { name: catalog.com_error_refusal_reason });+ fireEvent.click(disclosure);+ expect(disclosure).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText(explanation)).toBeInTheDocument();+ expectReadable();+ });++ it('renders a content-filter refusal without an empty explanation or its raw metadata', () => {+ renderError(+ { type: ErrorTypes.REFUSAL, info: { stop_reason: 'content_filtered' } },+ providerMessage,+ );++ expect(screen.getByText(localized('com_error_refusal', 'gpt-4o'))).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: catalog.com_error_refusal_reason }),+ ).not.toBeInTheDocument();+ expect(document.body.textContent).not.toMatch(/content_filtered|\[object Object\]/);});- it('keeps the wire fallback readable for a client that does not know the typed error', () => {- render(- <Error text={`${upstreamFallback}\n${JSON.stringify({ type: 'future_error_type' })}`} />,+ it('names the provider from endpoint_models_not_loaded payload info', () => {+ renderError(+ { type: ErrorTypes.ENDPOINT_MODELS_NOT_LOADED, info: 'anthropic' },+ providerMessage,);- expect(screen.getByText(new RegExp(upstreamFallback, 'i'))).toBeInTheDocument();+ expect(+ screen.getByText(localized('com_error_endpoint_models_not_loaded', 'Anthropic')),+ ).toBeInTheDocument();+ expectReadable();+ });++ /** The server persists this sentence as the failure's own text, so the copy stays provider-neutral. */+ it('renders the provider-neutral upstream copy with and without a status', () => {+ const { unmount } = renderError({ type: ErrorTypes.UPSTREAM_MODEL_ERROR }, providerMessage);+ expect(screen.getByText(catalog.com_error_upstream_model)).toBeInTheDocument();+ unmount();++ renderError({ type: ErrorTypes.UPSTREAM_MODEL_ERROR, status: 529 }, providerMessage);+ expect(+ screen.getByText(localized('com_error_upstream_model_status', '529')),+ ).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('OpenAI');});it.each([@@ -99,103 +393,433 @@ describe('Error — typed provider errors', () => {['worker_unavailable', 'com_error_code_workspace_worker_unavailable'],['unsupported', 'com_error_code_workspace_unsupported'],['missing', 'com_error_code_workspace_missing'],+ ['locked', 'com_error_code_workspace_locked'],])('localizes a workspace rejection with reason %s', (reason, key) => {- render(- <Error text={JSON.stringify({ type: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, reason })} />,- );+ renderError({ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, reason });expect(screen.getByText(catalog[key])).toBeInTheDocument();+ expectReadable();});it.each([{ reason: 'future_reason' }, {}])('uses safe workspace fallback copy for an unknown or legacy payload',(payload) => {- render(- <Error- text={JSON.stringify({ type: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, ...payload })}- />,- );+ renderError({ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, ...payload });expect(screen.getByText(catalog.com_error_code_workspace_unavailable)).toBeInTheDocument();+ expectReadable();},);+});- it('keeps the provider message for a LangChain code without localized copy, minus the URL', () => {- const raw =- 'An error occurred while processing the request: could not parse output\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/OUTPUT_PARSING_FAILURE/\n';- render(<Error text={raw} />);+describe('Error — user key and limits', () => {+ it('offers the add-key action when the endpoint accepts user credentials', () => {+ renderError({ type: ErrorTypes.NO_USER_KEY }, providerMessage);- expect(screen.getByText(/could not parse output/)).toBeInTheDocument();- expect(screen.queryByText(/langchain\.com/i)).not.toBeInTheDocument();+ expect(screen.getByText(localized('com_error_no_user_key', 'OpenAI'))).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_key_add }),+ ).toBeInTheDocument();});- it('falls back to the raw provider text for an unmapped error', () => {- const raw =- '[GoogleGenerativeAI Error]: [400 Bad Request] Request contains an invalid argument';- render(<Error text={raw} />);+ it('shows administrator guidance and no action for deployment-managed credentials', () => {+ mockEndpointsData = { openAI: { userProvide: false } };+ renderError({ type: ErrorTypes.NO_USER_KEY }, providerMessage);expect(- screen.getByText(new RegExp(raw.slice(0, 30).replace(/[[\]]/g, '\\$&'))),+ screen.getByText(localized('com_error_no_user_key_admin', 'OpenAI')),).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: catalog.com_error_user_key_add }),+ ).not.toBeInTheDocument();});-});-describe('Error: agent context budget errors', () => {- beforeAll(() => {- /** CodeBlock observes its code bar; jsdom ships no IntersectionObserver. */- (global as { IntersectionObserver?: unknown }).IntersectionObserver = class {- observe() {}- unobserve() {}- disconnect() {}- };+ /** A shared link's viewer has no endpoint configuration, so who owns the key is unknown. */+ it('keeps key copy generic where the endpoint configuration is unavailable', () => {+ mockEndpointsData = undefined;+ renderError({ type: ErrorTypes.NO_USER_KEY }, providerMessage);++ expect(screen.getByText(catalog.com_error_no_user_key_generic)).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('administrator');+ expect(screen.queryByRole('button')).not.toBeInTheDocument();});- it('renders localized copy and the token breakdown for empty_messages', () => {- /** Mirrors the SDK payload as embedded by the agents controller's error prefix. */- const info =- 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.\nToken budget breakdown:\n maxContextTokens: 10\n messageTokens: 32 (4 messages)\n availableForMessages: 9';- const payload = `An error occurred while processing the request: ${JSON.stringify({- type: ErrorTypes.EMPTY_MESSAGES,- info,- })}`;- render(<Error text={payload} />);+ it('offers the key dialog when a saved user key cannot be read', () => {+ renderError({ type: ErrorTypes.INVALID_USER_KEY }, providerMessage);- expect(screen.getByText(catalog.com_error_empty_messages)).toBeInTheDocument();- expect(screen.getByText(/Token budget breakdown/)).toBeInTheDocument();- expect(screen.queryByText(/Something went wrong/)).not.toBeInTheDocument();+ expect(+ screen.getByText(localized('com_error_invalid_user_key_provider', 'OpenAI')),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_key_update }),+ ).toBeInTheDocument();+ });++ describe('an endpoint whose base URL the reader provides', () => {+ const customRow = { endpoint: 'OpenRouter', model: 'openrouter/auto' } as TMessage;++ beforeEach(() => {+ mockEndpointsData = { OpenRouter: { type: 'custom', userProvideURL: true } };+ });++ /** The server reads the key from the reader's own record whenever the URL is theirs. */+ it('offers the key dialog for a missing key even with a deployment key configured', () => {+ renderError({ type: ErrorTypes.NO_USER_KEY }, customRow);++ expect(+ screen.getByText(localized('com_error_no_user_key', 'OpenRouter')),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_key_add }),+ ).toBeInTheDocument();+ });++ it('names a missing URL and offers to add it', () => {+ renderError({ type: ErrorTypes.NO_BASE_URL }, customRow);++ expect(+ screen.getByText(localized('com_error_no_base_url_provider', 'OpenRouter')),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_url_add }),+ ).toBeInTheDocument();+ });++ it('offers to update a URL the server refused', () => {+ renderError(+ {+ type: ErrorTypes.INVALID_BASE_URL,+ message: 'Base URL for OpenRouter targets a restricted address.',+ },+ customRow,+ );++ expect(+ screen.getByText(localized('com_error_invalid_base_url_provider', 'OpenRouter')),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_url_update }),+ ).toBeInTheDocument();+ });++ it("keeps the generic URL copy and no action where the record is not the reader's", () => {+ mockEndpointsData = { OpenRouter: { type: 'custom' } };+ renderError({ type: ErrorTypes.NO_BASE_URL }, customRow);++ expect(screen.getByText(catalog.com_error_no_base_url)).toBeInTheDocument();+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });});- it('renders localized copy with token counts for final_context_overflow', () => {- const payload = `An error occurred while processing the request: ${JSON.stringify({- type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,- info: 'Provider message formatting exceeded the context budget and no safe synthetic-context compaction could make it fit.',- provider: 'openAI',- projectedMessageTokens: 3,- availableMessageTokens: 0,- })}`;- render(<Error text={payload} />);+ it('formats an expired user-key date for readers', () => {+ const expiredAt = '2026-08-01T09:30:00.000Z';+ const formatted = dateTimeFormat.format(new Date(expiredAt));+ renderError(+ { type: ErrorTypes.EXPIRED_USER_KEY, expiredAt, endpoint: 'openAI' },+ providerMessage,+ );expect(- screen.getByText(new RegExp(catalog.com_error_final_context_overflow.slice(0, 40))),+ screen.getByText(localized('com_error_expired_user_key', 'OpenAI', formatted)),).toBeInTheDocument();- expect(screen.getByText(/need 3 tokens, but only 0 are available/)).toBeInTheDocument();- expect(screen.queryByText(/Something went wrong/)).not.toBeInTheDocument();+ expect(document.body.textContent).not.toContain(expiredAt);+ });++ /** A server in a day-first locale wrote August 1 as `01/08/2026`, which parses as January 8. */+ it('shows an expiry persisted in a server locale as written instead of reparsing it', () => {+ const expiredAt = '01/08/2026, 09:30:00';+ renderError(+ { type: ErrorTypes.EXPIRED_USER_KEY, expiredAt, endpoint: 'openAI' },+ providerMessage,+ );++ expect(+ screen.getByText(localized('com_error_expired_user_key', 'OpenAI', expiredAt)),+ ).toBeInTheDocument();+ });++ it('renders a message-limit countdown from a future reset time', () => {+ renderError(+ {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 40,+ windowInMinutes: 60,+ resetAt: Date.now() + 2 * 60 * 1000,+ },+ limitRow(),+ );++ expect(screen.getByText(/You can send another message in \d+:\d{2}\./)).toBeInTheDocument();+ });++ it('counts down to a reset more than a day out when the limiter window is that long', () => {+ renderError(+ {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 40,+ windowInMinutes: 3 * 24 * 60,+ resetAt: Date.now() + 2 * 24 * 60 * 60 * 1000,+ },+ limitRow(),+ );++ expect(+ screen.getByText(/You can send another message in (47:59:59|48:00:00)\./),+ ).toBeInTheDocument();+ });++ /** The server stamps both the row and its reset, so the window runs from the row, not this device. */+ it('keeps a valid countdown when this device clock runs behind the server', () => {+ const serverNow = Date.now() + 10 * 60 * 1000;+ renderError(+ {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 40,+ windowInMinutes: 60,+ resetAt: serverNow + 55 * 60 * 1000,+ },+ limitRow(serverNow),+ );++ expect(screen.getByText(/You can send another message in 1:0[45]:\d{2}\./)).toBeInTheDocument();+ });++ it('drops a reset further out than the limiter window allows', () => {+ renderError(+ {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 40,+ windowInMinutes: 60,+ resetAt: Date.now() + 3 * 60 * 60 * 1000,+ },+ limitRow(),+ );++ expect(+ screen.getByText(localized('com_error_message_limit', '40', '60 minutes')),+ ).toBeInTheDocument();+ expect(screen.queryByText(/You can send another message/)).not.toBeInTheDocument();+ });++ /** The error box is `role="alert"`, so a ticking line inside it would be announced every second. */+ it('keeps the ticking countdown out of the alert and states the reset moment instead', () => {+ const resetAt = Date.now() + 2 * 60 * 1000;+ renderError(+ { type: ViolationTypes.MESSAGE_LIMIT, max: 40, windowInMinutes: 60, resetAt },+ limitRow(),+ );++ expect(screen.getByText(/You can send another message in \d+:\d{2}\./)).toHaveAttribute(+ 'aria-hidden',+ 'true',+ );+ expect(+ screen.getByText(localized('com_error_retry_at', dateTimeFormat.format(new Date(resetAt)))),+ ).toHaveClass('sr-only');+ });++ /** The row a live violation renders is stamped by this device as it arrives. */+ it('counts a live countdown from the relative retry, not a server reset this device misreads', () => {+ renderError(+ {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 1,+ windowInMinutes: 1,+ retryAfterSeconds: 60,+ resetAt: Date.now() - 4 * 60 * 1000,+ },+ limitRow(),+ );++ expect(screen.getByText(/You can send another message in (0:59|1:00)\./)).toBeInTheDocument();+ expect(screen.queryByText(catalog.com_error_retry_available)).not.toBeInTheDocument();});- it('falls back to the plain sentence when overflow token counts are absent', () => {- const payload = JSON.stringify({- type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,- info: 'Fallback provider message formatting exceeded the context budget before invocation.',+ it('renders retry-available copy when a message limit has expired', () => {+ renderError(+ {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 40,+ windowInMinutes: 60,+ resetAt: Date.now() - 1000,+ },+ limitRow(),+ );++ expect(screen.getByText(catalog.com_error_retry_available)).toBeInTheDocument();+ });+});++describe('Error — token balance and context budget', () => {+ it('formats token credits and keeps generation rows behind a disclosure', () => {+ renderError({+ type: ViolationTypes.TOKEN_BALANCE,+ balance: 1250,+ tokenCost: 8400,+ promptTokens: 6300,+ generations: [+ { model: 'gpt-4o', promptTokens: 6300, completionTokens: 2100 },+ { model: 'gpt-4o-mini', promptTokens: 820, completionTokens: 240 },+ ],});- render(<Error text={payload} />);- expect(screen.getByText(catalog.com_error_final_context_overflow)).toBeInTheDocument();+ expect(+ screen.getByText(+ localized('com_error_token_balance', numberFormat.format(8400), numberFormat.format(1250)),+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByText(localized('com_error_token_balance_prompt', numberFormat.format(6300))),+ ).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('"model":');+ fireEvent.click(+ screen.getByRole('button', { name: catalog.com_error_token_balance_generations }),+ );+ expect(+ screen.getByText(+ localized(+ 'com_error_token_balance_generation',+ 'gpt-4o',+ numberFormat.format(6300),+ numberFormat.format(2100),+ ),+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByText(+ localized(+ 'com_error_token_balance_generation',+ 'gpt-4o-mini',+ numberFormat.format(820),+ numberFormat.format(240),+ ),+ ),+ ).toBeInTheDocument();+ });++ it('lists every generation charge rather than a truncated subset', () => {+ const generations = Array.from({ length: 25 }, (_, index) => ({+ model: `model-${index + 1}`,+ promptTokens: 100,+ completionTokens: 10,+ }));+ renderError({ type: ViolationTypes.TOKEN_BALANCE, balance: 10, tokenCost: 900, generations });++ fireEvent.click(+ screen.getByRole('button', { name: catalog.com_error_token_balance_generations }),+ );+ expect(screen.getAllByRole('listitem')).toHaveLength(25);+ expect(screen.getByText(/^model-25 —/)).toBeInTheDocument();+ });++ it('formats input length and offers the standard context next steps', () => {+ renderError({ type: ErrorTypes.INPUT_LENGTH, info: '214500 / 128000' }, providerMessage);++ expect(+ screen.getByText(+ localized(+ 'com_error_input_length',+ numberFormat.format(214500),+ numberFormat.format(128000),+ ),+ ),+ ).toBeInTheDocument();+ expect(screen.getByText(catalog.com_error_context_next_steps)).toBeInTheDocument();+ });++ it('never suggests compaction for a message that alone exceeds the limit', () => {+ mockStartupData = { compactionEnabled: true };+ renderError({ type: ErrorTypes.INPUT_LENGTH, info: '214500 / 128000' }, providerMessage);++ expect(screen.getByText(catalog.com_error_context_next_steps)).toBeInTheDocument();+ expect(+ screen.queryByText(catalog.com_error_context_next_steps_compact),+ ).not.toBeInTheDocument();+ });++ it('formats final overflow numbers and uses compaction next steps when available', () => {+ mockStartupData = { compactionEnabled: true };+ renderError(+ {+ type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,+ projectedMessageTokens: 214500,+ availableMessageTokens: 128000,+ },+ providerMessage,+ { conversation: chatConversation },+ );++ expect(+ screen.getByText(+ localized(+ 'com_error_final_context_overflow',+ numberFormat.format(214500),+ numberFormat.format(128000),+ ),+ ),+ ).toBeInTheDocument();+ expect(screen.getByText(catalog.com_error_context_next_steps_compact)).toBeInTheDocument();+ });++ /** The compact action lives in the context usage popover, which that setting removes. */+ /** Search results read a cached startup config, but only the chat composer can compact. */+ it('does not suggest compaction outside a chat', () => {+ mockStartupData = { compactionEnabled: true };+ renderError(+ {+ type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,+ projectedMessageTokens: 214500,+ availableMessageTokens: 128000,+ },+ providerMessage,+ );++ expect(screen.getByText(catalog.com_error_context_next_steps)).toBeInTheDocument();+ expect(+ screen.queryByText(catalog.com_error_context_next_steps_compact),+ ).not.toBeInTheDocument();+ });++ it('does not suggest compaction where the context usage indicator is hidden', () => {+ mockStartupData = { compactionEnabled: true, interface: { contextUsage: false } };+ renderError(+ {+ type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,+ projectedMessageTokens: 214500,+ availableMessageTokens: 128000,+ },+ providerMessage,+ { conversation: chatConversation },+ );++ expect(screen.getByText(catalog.com_error_context_next_steps)).toBeInTheDocument();+ expect(+ screen.queryByText(catalog.com_error_context_next_steps_compact),+ ).not.toBeInTheDocument();+ });++ it('renders empty-message context copy and formatted budget detail', () => {+ const info =+ 'Message pruning removed all messages as none fit in the context window. ' ++ 'Please increase the context window size or make your message shorter. ' ++ 'Token budget: 128000 total, 127480 reserved for instructions and tools, 520 available.';+ renderError({ type: ErrorTypes.EMPTY_MESSAGES, info }, providerMessage);++ expect(screen.getByText(catalog.com_error_empty_messages)).toBeInTheDocument();+ expect(screen.getByText(catalog.com_error_context_next_steps)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: catalog.com_error_context_token_budget }));+ expect(+ screen.getByText(new RegExp(`Token budget: ${numberFormat.format(128000)} total`)),+ ).toBeInTheDocument();+ expect(+ screen.getByText(new RegExp(`${numberFormat.format(127480)} reserved`)),+ ).toBeInTheDocument();});});describe('Error — manual compaction', () => {it('renders the failed-compaction copy', () => {- render(<Error text={JSON.stringify({ type: ErrorTypes.COMPACTION_FAILED })} />);+ renderError({ type: ErrorTypes.COMPACTION_FAILED });expect(screen.getByText(catalog.com_error_compaction_failed)).toBeInTheDocument();});@@ -205,16 +829,342 @@ describe('Error — manual compaction', () => {['instructions_exceed_budget', 'com_error_compaction_budget'],['nothing_to_summarize', 'com_error_compaction_nothing'],])('renders the copy for a compaction skipped because %s', (reason, key) => {- render(<Error text={JSON.stringify({ type: ErrorTypes.COMPACTION_SKIPPED, reason })} />);+ renderError({ type: ErrorTypes.COMPACTION_SKIPPED, reason });expect(screen.getByText(catalog[key])).toBeInTheDocument();});it('falls back to the failed copy for an unknown skip reason', () => {- render(- <Error text={JSON.stringify({ type: ErrorTypes.COMPACTION_SKIPPED, reason: 'exhausted' })} />,- );+ renderError({ type: ErrorTypes.COMPACTION_SKIPPED, reason: 'exhausted' });expect(screen.getByText(catalog.com_error_compaction_failed)).toBeInTheDocument();});});++describe('Error — identity of the row an error part belongs to', () => {+ const failedTurn = { endpoint: EModelEndpoint.anthropic, model: 'claude-sonnet-4-5' } as TMessage;++ it("names the model that failed rather than the conversation's current one", () => {+ renderError({ type: ErrorTypes.REFUSAL }, undefined, {+ source: failedTurn,+ conversation: { endpoint: EModelEndpoint.openAI, model: 'gpt-4o' },+ });++ expect(+ screen.getByText(localized('com_error_refusal', 'claude-sonnet-4-5')),+ ).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('gpt-4o');+ });++ /** A restored row without identity must not borrow whatever the conversation selected since. */+ it("keeps a row's missing identity unknown instead of borrowing the conversation's", () => {+ renderError({ type: ErrorTypes.NO_USER_KEY }, { text: 'restored' } as TMessage, {+ conversation: { endpoint: EModelEndpoint.openAI, model: 'gpt-4o' },+ });++ expect(screen.getByText(catalog.com_error_no_user_key_generic)).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('OpenAI');+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('reads the conversation only for an error rendered with no row at all', () => {+ renderError({ type: ErrorTypes.REFUSAL }, undefined, {+ conversation: { endpoint: EModelEndpoint.openAI, model: 'gpt-4o' },+ });++ expect(screen.getByText(localized('com_error_refusal', 'gpt-4o'))).toBeInTheDocument();+ });++ it('lets a row passed directly outrank the surrounding source', () => {+ renderError({ type: ErrorTypes.REFUSAL }, providerMessage, { source: failedTurn });++ expect(screen.getByText(localized('com_error_refusal', 'gpt-4o'))).toBeInTheDocument();+ });+});++describe('Error — saved agents', () => {+ /** A saved agent's row names the agents endpoint and stores the agent id as its model. */+ const agentRow = { endpoint: EModelEndpoint.agents, model: 'agent_research' } as TMessage;+ const researchAgent = {+ id: 'agent_research',+ name: 'Research',+ provider: EModelEndpoint.google,+ model: 'gemini-2.5-pro',+ isEditable: true,+ } satisfies Partial<Agent> as Agent;+ const agents = { [researchAgent.id]: researchAgent };++ beforeEach(() => {+ mockEndpointsData = { agents: {}, google: { userProvide: true } };+ });++ it("resolves a key failure against the agent's provider and offers that provider's key", () => {+ renderError({ type: ErrorTypes.NO_USER_KEY }, agentRow, { agents });++ expect(screen.getByText(localized('com_error_no_user_key', 'Google'))).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_key_add }),+ ).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('My Agents');+ });++ it("names the agent's model rather than the agent id stored on the row", () => {+ renderError({ type: ErrorTypes.REFUSAL }, agentRow, { agents });++ expect(screen.getByText(localized('com_error_refusal', 'gemini-2.5-pro'))).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('agent_research');+ });++ it('keeps generic copy when the agents map cannot resolve the agent', () => {+ renderError({ type: ErrorTypes.NO_USER_KEY }, agentRow);++ expect(screen.getByText(catalog.com_error_no_user_key_generic)).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: catalog.com_error_user_key_add }),+ ).not.toBeInTheDocument();+ expect(document.body.textContent).not.toContain('agent_research');+ });++ /** An ephemeral agent's row stores the model itself, since there is no agent id to store. */+ it("keeps an agents row's recorded model when no saved agent resolves", () => {+ renderError({ type: ErrorTypes.REFUSAL }, {+ endpoint: EModelEndpoint.agents,+ model: 'gpt-4o',+ } as TMessage);++ expect(screen.getByText(localized('com_error_refusal', 'gpt-4o'))).toBeInTheDocument();+ });++ /** The client's live placeholder for an agents turn stores the conversation's agent id as `model`. */+ it('resolves an ephemeral agent id to the endpoint and model it encodes', () => {+ mockEndpointsData = { agents: {}, openAI: { userProvide: true } };+ renderError({ type: ErrorTypes.NO_USER_KEY }, {+ endpoint: EModelEndpoint.agents,+ model: 'openAI__gpt-4o___GPT-4o',+ } as TMessage);++ expect(screen.getByText(localized('com_error_no_user_key', 'OpenAI'))).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_key_add }),+ ).toBeInTheDocument();+ });++ /** Switching the conversation to a saved agent later must not rewrite who produced an old failure. */+ it("keeps an ephemeral row's own model when the conversation now runs a saved agent", () => {+ renderError(+ { type: ErrorTypes.REFUSAL },+ { endpoint: EModelEndpoint.agents, model: 'gpt-4o' } as TMessage,+ {+ agents,+ conversation: { endpoint: EModelEndpoint.agents, agent_id: researchAgent.id },+ },+ );++ expect(screen.getByText(localized('com_error_refusal', 'gpt-4o'))).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('gemini-2.5-pro');+ });++ it('never names the ephemeral placeholder as a model', () => {+ renderError({ type: ErrorTypes.REFUSAL }, {+ endpoint: EModelEndpoint.agents,+ model: 'ephemeral',+ } as TMessage);++ expect(screen.getByText(catalog.com_error_refusal_unknown)).toBeInTheDocument();+ });++ it('lets an expired key name the endpoint its payload reports over the row', () => {+ const expiredAt = '2026-08-01T09:30:00.000Z';+ renderError(+ { type: ErrorTypes.EXPIRED_USER_KEY, expiredAt, endpoint: EModelEndpoint.google },+ providerMessage,+ );++ expect(+ screen.getByText(+ localized(+ 'com_error_expired_user_key',+ 'Google',+ dateTimeFormat.format(new Date(expiredAt)),+ ),+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: catalog.com_error_user_key_update }),+ ).toBeInTheDocument();+ });+});++describe('Error — agent provider guidance', () => {+ const agentRow = { endpoint: EModelEndpoint.agents, model: 'agent_ops' } as TMessage;+ const opsAgent = {+ id: 'agent_ops',+ name: 'Ops',+ provider: EModelEndpoint.bedrock,+ model: 'anthropic.claude-sonnet-4-5',+ isEditable: true,+ } satisfies Partial<Agent> as Agent;+ const payload = { type: ErrorTypes.INVALID_AGENT_PROVIDER, info: EModelEndpoint.bedrock };++ beforeEach(() => {+ mockEndpointsData = { agents: {} };+ mockAccess = { USE: true, CREATE: true };+ });++ it('sends a reader who can edit the agent to the builder', () => {+ renderError(payload, agentRow, { agents: { [opsAgent.id]: opsAgent } });++ expect(+ screen.getByText(localized('com_error_invalid_agent_provider', 'AWS Bedrock')),+ ).toBeInTheDocument();+ expect(screen.getByText(catalog.com_error_invalid_agent_provider_editable)).toBeInTheDocument();+ });++ it.each([+ ['the builder is disabled', { agents: { disableBuilder: true } }, { USE: true, CREATE: true }],+ ['the reader cannot create agents', { agents: {} }, { USE: true, CREATE: false }],+ ['the reader cannot use agents', { agents: {} }, { USE: false, CREATE: true }],+ ['agents are not configured', {}, { USE: true, CREATE: true }],+ ])('does not point to the builder when %s', (_label, endpoints, access) => {+ mockEndpointsData = endpoints;+ mockAccess = access;+ renderError(payload, agentRow, { agents: { [opsAgent.id]: opsAgent } });++ expect(screen.getByText(catalog.com_error_invalid_agent_provider_admin)).toBeInTheDocument();+ expect(+ screen.queryByText(catalog.com_error_invalid_agent_provider_editable),+ ).not.toBeInTheDocument();+ });++ it("sends an administrator to the builder for an agent outside the reader's grants", () => {+ renderError(payload, agentRow, {+ agents: { [opsAgent.id]: { ...opsAgent, isEditable: false } },+ role: SystemRoles.ADMIN,+ });++ expect(screen.getByText(catalog.com_error_invalid_agent_provider_editable)).toBeInTheDocument();+ });++ it('names the owner when the reader cannot edit the agent', () => {+ renderError(payload, agentRow, {+ agents: {+ [opsAgent.id]: { ...opsAgent, isEditable: false, owner_contact: { name: 'Dana' } },+ },+ });++ expect(+ screen.getByText(localized('com_error_invalid_agent_provider_owner', 'Dana')),+ ).toBeInTheDocument();+ });+});++describe('Error — agent handoffs within a row', () => {+ const rootAgent = {+ id: 'agent_root',+ name: 'Planner',+ provider: EModelEndpoint.google,+ model: 'gemini-2.5-pro',+ } satisfies Partial<Agent> as Agent;+ const writerAgent = {+ id: 'agent_writer',+ name: 'Writer',+ provider: EModelEndpoint.anthropic,+ model: 'claude-sonnet-4-5',+ } satisfies Partial<Agent> as Agent;+ /** Index 1 hands the run to the writer, and the run fails at index 2. */+ const handoffRow = {+ endpoint: EModelEndpoint.agents,+ model: rootAgent.id,+ content: [+ { type: ContentTypes.TEXT, text: 'Drafting the outline.' },+ { type: ContentTypes.AGENT_UPDATE, agent_update: { agentId: writerAgent.id, index: 1 } },+ { type: ContentTypes.ERROR, error: JSON.stringify({ type: ErrorTypes.NO_USER_KEY }) },+ ],+ } as unknown as TMessage;++ beforeEach(() => {+ mockEndpointsData = {+ agents: {},+ google: { userProvide: true },+ anthropic: { userProvide: true },+ };+ });++ it('resolves an error part after a handoff against the agent the run was handed to', () => {+ renderError({ type: ErrorTypes.NO_USER_KEY }, undefined, {+ source: handoffRow,+ partIndex: 2,+ agents: { [rootAgent.id]: rootAgent, [writerAgent.id]: writerAgent },+ });++ expect(screen.getByText(localized('com_error_no_user_key', 'Anthropic'))).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('Google');+ });++ it('keeps the agent that handed off for a part before the handoff', () => {+ renderError({ type: ErrorTypes.NO_USER_KEY }, undefined, {+ source: handoffRow,+ partIndex: 0,+ agents: { [rootAgent.id]: rootAgent, [writerAgent.id]: writerAgent },+ });++ expect(screen.getByText(localized('com_error_no_user_key', 'Google'))).toBeInTheDocument();+ });++ it('resolves a handoff to a parallel ephemeral agent through the id it encodes', () => {+ const parallelRow = {+ ...handoffRow,+ content: [+ { type: ContentTypes.TEXT, text: 'Drafting the outline.' },+ {+ type: ContentTypes.AGENT_UPDATE,+ agent_update: { agentId: 'anthropic__claude-sonnet-4-5___Claude____1', index: 1 },+ },+ { type: ContentTypes.ERROR, error: JSON.stringify({ type: ErrorTypes.NO_USER_KEY }) },+ ],+ } as unknown as TMessage;+ renderError({ type: ErrorTypes.NO_USER_KEY }, undefined, {+ source: parallelRow,+ partIndex: 2,+ agents: { [rootAgent.id]: rootAgent },+ });++ expect(screen.getByText(localized('com_error_no_user_key', 'Anthropic'))).toBeInTheDocument();+ });++ /** A parallel run stamps each part with its lane's agent, whatever handoff preceded it. */+ it("resolves a parallel lane's error part against the agent of its own lane", () => {+ const laneRow = {+ ...handoffRow,+ content: [+ { type: ContentTypes.AGENT_UPDATE, agent_update: { agentId: writerAgent.id, index: 0 } },+ { type: ContentTypes.TEXT, text: 'Drafting.', agentId: writerAgent.id, groupId: 1 },+ {+ type: ContentTypes.ERROR,+ error: JSON.stringify({ type: ErrorTypes.NO_USER_KEY }),+ agentId: rootAgent.id,+ groupId: 1,+ },+ ],+ } as unknown as TMessage;+ renderError({ type: ErrorTypes.NO_USER_KEY }, undefined, {+ source: laneRow,+ partIndex: 2,+ agents: { [rootAgent.id]: rootAgent, [writerAgent.id]: writerAgent },+ });++ expect(screen.getByText(localized('com_error_no_user_key', 'Google'))).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('Anthropic');+ });++ it('names no provider when the agent handed to cannot be resolved', () => {+ renderError({ type: ErrorTypes.NO_USER_KEY }, undefined, {+ source: handoffRow,+ partIndex: 2,+ agents: { [rootAgent.id]: rootAgent },+ });++ expect(screen.getByText(catalog.com_error_no_user_key_generic)).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('Google');+ });+});diff --git a/client/src/components/Messages/ContentRender.tsx b/client/src/components/Messages/ContentRender.tsxindex 96b6ebe743..c3b954583d 100644--- a/client/src/components/Messages/ContentRender.tsx+++ b/client/src/components/Messages/ContentRender.tsx@@ -14,6 +14,7 @@ import { revealOnRowHoverClasses, messageFooterClasses } from '~/components/Chatimport { useLocalize, useAttachments, useMessageActions, useContentMetadata } from '~/hooks';import ToolCallLimitNotice from '~/components/Chat/Messages/Content/ToolCallLimitNotice';import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';+import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';import Elapsed, { shouldShowElapsed } from '~/components/Chat/Messages/Elapsed';import { getHeaderHoverLabel } from '~/components/Chat/Messages/ui/HeaderLabel';import ContentParts from '~/components/Chat/Messages/Content/ContentParts';@@ -213,25 +214,27 @@ const ContentRender = memo(function ContentRender({</SubRow>}>- <ContentParts- edit={edit}- isLast={isLast}- enterEdit={enterEdit}- siblingIdx={siblingIdx}- messageId={msg.messageId}- attachments={attachments}- searchResults={searchResults}- manualSkills={msg.manualSkills}- authorHeader={authorHeader}- setSiblingIdx={setSiblingIdx}- isLatestMessage={isLatestMessage}- isSubmitting={isSubmitting}- isCreatedByUser={msg.isCreatedByUser}- createdAt={msg.createdAt ?? msg.clientTimestamp}- showThinking={showThinking}- conversationId={conversation?.conversationId}- content={msg.content as Array<TMessageContentParts | undefined>}- />+ <ErrorSourceProvider message={msg}>+ <ContentParts+ edit={edit}+ isLast={isLast}+ enterEdit={enterEdit}+ siblingIdx={siblingIdx}+ messageId={msg.messageId}+ attachments={attachments}+ searchResults={searchResults}+ manualSkills={msg.manualSkills}+ authorHeader={authorHeader}+ setSiblingIdx={setSiblingIdx}+ isLatestMessage={isLatestMessage}+ isSubmitting={isSubmitting}+ isCreatedByUser={msg.isCreatedByUser}+ createdAt={msg.createdAt ?? msg.clientTimestamp}+ showThinking={showThinking}+ conversationId={conversation?.conversationId}+ content={msg.content as Array<TMessageContentParts | undefined>}+ />+ </ErrorSourceProvider>{/** A turn that ran out of agent steps is incomplete, not broken. Rendered* here rather than inside `ContentParts` because it is a message-level* outcome, and `ContentParts` also serves surfaces (subagent panels,diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 9e558487e8..6074636d3f 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -428,53 +428,118 @@"com_endpoint_use_search_grounding": "Grounding with Google Search","com_endpoint_use_url_context": "URL Context","com_endpoint_verbosity": "Verbosity",- "com_error_endpoint_models_not_loaded": "Models for {{0}} could not be loaded. Please refresh the page and try again.",- "com_error_expired_user_key": "Provided key for {{0}} expired at {{1}}. Please provide a new key and try again.",- "com_error_files_dupe": "Duplicate file detected.",- "com_error_files_empty": "Empty files are not allowed.",+ "com_error_agent_contact_email": "Email {{0}}",+ "com_error_auth_banned": "Access is blocked for this account or address. Ask an administrator to review it.",+ "com_error_auth_failed": "Your session could not be verified. Sign in again, then resend the message.",+ "com_error_auth_rate_limited": "Too many attempts in a short time. Wait a moment and try again.",+ "com_error_ban": "Your account is temporarily banned for violating the terms of service.",+ "com_error_code_workspace_invalid": "The workspace selection is invalid; select an available workspace.",+ "com_error_code_workspace_locked": "This chat already uses a different code environment. Continue with its original environment or start a new chat.",+ "com_error_code_workspace_missing": "The selected workspace is no longer registered. Restore it on the attached machine or start a new chat.",+ "com_error_code_workspace_required": "Choose an attached workspace before sending.",+ "com_error_code_workspace_unavailable": "The selected code workspace is unavailable. Reconnect its machine or choose an available workspace, then try again.",+ "com_error_code_workspace_unsupported": "The worker does not support workspace selection.",+ "com_error_code_workspace_worker_unavailable": "The machine is unavailable; reconnect or choose another environment.","com_error_compaction_budget": "Could not compact the context: the agent's instructions and tool definitions already exceed the context budget.","com_error_compaction_disabled": "Context compaction is not available for this agent because summarization is disabled.","com_error_compaction_failed": "Could not compact the context: the summarizer produced no summary. Nothing was changed.","com_error_compaction_nothing": "Nothing to compact: the retained recent turns already cover the whole conversation.",- "com_error_code_workspace_unavailable": "The selected code workspace is unavailable. Reconnect its machine or choose an available workspace, then try again.",- "com_error_code_workspace_required": "Choose an attached workspace before sending.",- "com_error_code_workspace_invalid": "The workspace selection is invalid; select an available workspace.",- "com_error_code_workspace_worker_unavailable": "The machine is unavailable; reconnect or choose another environment.",- "com_error_code_workspace_unsupported": "The worker does not support workspace selection.",- "com_error_code_workspace_missing": "The selected workspace is no longer registered. Restore it on the attached machine or start a new chat.",- "com_error_code_workspace_locked": "This chat already uses a different code environment. Continue with its original environment or start a new chat.",- "com_error_context_tokens_detail": "Your messages need {{0}} tokens, but only {{1}} are available.",- "com_error_empty_messages": "Your messages do not fit in the current context window, so there was nothing left to send to the model. Increase the max context size from the conversation parameters, shorten your message, or start a new conversation.",+ "com_error_concurrent": "Only {{0}} messages can run at once. Wait for the other responses to finish.",+ "com_error_concurrent_one": "Only one message can run at a time. Wait for the current response to finish.",+ "com_error_context_next_steps": "Shorten your message, raise the max context size in the conversation parameters, or start a new chat.",+ "com_error_context_next_steps_compact": "Compact the conversation to free up room, shorten your message, or start a new chat.",+ "com_error_context_token_budget": "Token budget",+ "com_error_convo_access": "You do not have access to this conversation.",+ "com_error_details_provider": "Provider response",+ "com_error_empty_messages": "Your messages do not fit in the current context window, so there was nothing left to send to the model.",+ "com_error_endpoint_models_not_loaded": "Models for {{0}} could not be loaded. Please refresh the page and try again.",+ "com_error_expired_user_key": "Your {{0}} API key expired on {{1}}.",+ "com_error_expired_user_key_generic": "Your API key expired on {{0}}.",+ "com_error_file_upload_limit": "You have reached the upload limit of {{0}} files per {{1}}.",+ "com_error_files_dupe": "Duplicate file detected.",+ "com_error_files_empty": "Empty files are not allowed.","com_error_files_process": "An error occurred while processing the file.","com_error_files_skipped_dupe": "Skipped duplicate file(s): {{0}}","com_error_files_skipped_size": "Skipped file(s) over the {{0}} MB size limit: {{1}}","com_error_files_unsupported": "This file type can't be attached here.","com_error_files_upload": "An error occurred while uploading the file.","com_error_files_upload_canceled": "The file upload request was canceled. Note: the file upload may still be processing and will need to be manually deleted.",- "com_error_files_upload_too_large": "The file is too large. Please upload a file smaller than {{0}} MB",+ "com_error_files_upload_too_large": "The file is too large. Please upload a file smaller than {{0}} MB.","com_error_files_validation": "An error occurred while validating the file.",- "com_error_final_context_overflow": "The request exceeds the current context window and could not be reduced to fit. Increase the max context size from the conversation parameters or shorten your message.",- "com_error_google_tool_conflict": "Usage of built-in Google tools are not supported with external tools. Please disable either the built-in tools or the external tools.",+ "com_error_final_context_overflow": "This request needs {{0}} tokens, but only {{1}} fit in the current context window.",+ "com_error_final_context_overflow_unknown": "This request exceeds the current context window and could not be reduced to fit.",+ "com_error_google_error": "Google rejected this request.",+ "com_error_google_tool_conflict": "Built-in Google tools cannot be used together with external tools. Disable one of the two and try again.","com_error_google_video_unprocessable": "The linked video could not be processed. It is most likely too long for this model, but it may also be unavailable in this region or restricted. Try a shorter video, or describe the relevant parts in your message instead.","com_error_heic_conversion": "Failed to convert HEIC image to JPEG. Please try converting the image manually or use a different format.","com_error_illegal_model_request": "The model \"{{0}}\" is not available for {{1}}. Please select a different model.",- "com_error_input_length": "The latest message token count is too long, exceeding the token limit, or your token limit parameters are misconfigured, adversely affecting the context window. More info: {{0}}. Please shorten your message, adjust the max context size from the conversation parameters, or fork the conversation to continue.",- "com_error_invalid_agent_provider": "The \"{{0}}\" provider is not available for use with Agents. Please go to your agent's settings and select a currently available provider.",+ "com_error_input_length": "Your message needs {{0}} tokens, but this conversation allows {{1}}.",+ "com_error_input_length_unknown": "Your message is too long for this conversation's context window.",+ "com_error_insufficient_quota": "The {{0}} API key has no quota left.",+ "com_error_insufficient_quota_admin": "The {{0}} API key has no quota left. Ask an administrator to raise its limits or renew it.",+ "com_error_insufficient_quota_generic": "The API key in use has no quota left.",+ "com_error_invalid_action_error": "This action could not run because its domain is not on the allowed list. Ask an administrator to allow it.",+ "com_error_invalid_agent_provider": "The \"{{0}}\" provider is not available for agents.",+ "com_error_invalid_agent_provider_admin": "Ask an administrator to select an available provider for this agent.",+ "com_error_invalid_agent_provider_editable": "Open the agent builder and select an available provider.",+ "com_error_invalid_agent_provider_owner": "Ask {{0}}, who owns this agent, to select an available provider.",+ "com_error_invalid_api_key": "{{0}} rejected the API key in use.",+ "com_error_invalid_api_key_admin": "{{0}} rejected the configured API key. Ask an administrator to check it.",+ "com_error_invalid_api_key_generic": "The API key in use was rejected.","com_error_invalid_base_url": "The base URL you provided targets a restricted address. Please use a valid external URL and try again.",+ "com_error_invalid_base_url_provider": "The {{0}} API URL you saved cannot be used. Update it to a valid external HTTP or HTTPS address.",+ "com_error_invalid_request_error": "{{0}} rejected this request as invalid. Check the conversation's model and parameters, then try again.",+ "com_error_invalid_request_error_unknown": "The provider rejected this request as invalid. Check the conversation's model and parameters, then try again.","com_error_invalid_user_key": "Invalid key provided. Please provide a valid key and try again.",+ "com_error_invalid_user_key_provider": "The {{0}} API key you saved could not be read. Update it and try again.",+ "com_error_limit_reached": "You have reached a request limit. Wait a moment and try again.",+ "com_error_logins": "Too many sign-in attempts. Wait a moment and try again.",+ "com_error_message_limit": "You have reached your limit of {{0}} messages per {{1}}.",+ "com_error_message_limit_one": "You have reached your limit of one message per {{0}}.","com_error_missing_model": "No model selected for {{0}}. Please select a model and try again.","com_error_model_not_found": "The selected model is unavailable from this provider. Select a different model or ask an administrator to verify the provider configuration.","com_error_model_rate_limit": "The provider declined this request for exceeding a rate or spending limit. Wait a moment and try again, or ask an administrator to review the provider's limits.","com_error_models_not_loaded": "Models configuration could not be loaded. Please refresh the page and try again.",- "com_error_moderation": "It appears that the content submitted has been flagged by our moderation system for not aligning with our community guidelines. We're unable to proceed with this specific topic. If you have any other questions or topics you'd like to explore, please edit your message, or create a new conversation.",+ "com_error_moderation": "This message was flagged by the moderation system, so it was not sent. Edit the message or start a new conversation.","com_error_no_base_url": "No base URL found. Please provide one and try again.",- "com_error_no_user_key": "No key found. Please provide a key and try again.",- "com_error_refusal": "Response refused by safety filters. Rewrite your message and try again. If you encounter this frequently while using Claude Sonnet 4.5 or Opus 4.1, you can try Sonnet 4, which has different usage restrictions.",+ "com_error_no_base_url_provider": "Add your {{0}} API URL to send messages.",+ "com_error_no_system_messages": "{{0}} does not accept custom instructions. Remove them for this conversation, or pick a model that supports them.",+ "com_error_no_system_messages_unknown": "This model does not accept custom instructions. Remove them for this conversation, or pick a model that supports them.",+ "com_error_no_user_key": "Add your own {{0}} API key to send messages.",+ "com_error_no_user_key_admin": "No API key is configured for {{0}}. Ask an administrator to add one.",+ "com_error_no_user_key_generic": "An API key is required to send messages.",+ "com_error_non_browser": "This request was blocked because it did not come from a browser.",+ "com_error_provider_failed": "{{0}} could not complete this request.",+ "com_error_refusal": "{{0}} declined to answer this request. Rewrite your message and try again.",+ "com_error_refusal_reason": "The model's explanation",+ "com_error_refusal_unknown": "The model declined to answer this request. Rewrite your message and try again.",+ "com_error_registrations": "Too many accounts were created from this address. Wait a moment and try again.",+ "com_error_request_blocked": "This request was blocked.",+ "com_error_reset_password_limit": "Too many password reset requests. Wait a moment and try again.","com_error_resource_recovery_required": "Some files from this conversation could not be restored. Reattach the files and try again.",+ "com_error_retry_available": "You can send another message now.",+ "com_error_retry_at": "You can send another message at {{0}}.",+ "com_error_retry_countdown": "You can send another message in {{0}}.",+ "com_error_share_limit": "Too many shared link requests. Wait a moment and try again.",+ "com_error_stateful_code_environment_not_allowed": "This deployment does not allow the persistent code environment this agent requested. Ask an administrator to enable it, or use an agent that runs code in a temporary environment.","com_error_stream_expired": "The response stream has expired or already completed. Please try again.",- "com_error_token_balance": "Insufficient funds. Balance: {{0}}. Prompt tokens: {{1}}. Cost: {{2}}.",+ "com_error_stt_limit": "You have reached the speech-to-text limit of {{0}} requests per {{1}}.",+ "com_error_token_balance": "You do not have enough token credits for this request. It needs {{0}} credits and your balance is {{1}}.",+ "com_error_token_balance_generation": "{{0}} — {{1}} prompt tokens, {{2}} completion tokens",+ "com_error_token_balance_generations": "Recent generations",+ "com_error_token_balance_prompt": "Prompt size: {{0}} tokens.",+ "com_error_tool_call_limit": "You have reached the tool call limit. Wait a moment and try again.",+ "com_error_tts_limit": "You have reached the text-to-speech limit of {{0}} requests per {{1}}.",+ "com_error_unknown": "This response failed and the provider did not report a reason.","com_error_upstream_model": "The model provider could not complete this request.","com_error_upstream_model_status": "The model provider could not complete this request (status {{0}}).",+ "com_error_user_key_add": "Add your key",+ "com_error_user_key_update": "Update your key",+ "com_error_user_url_add": "Add your URL",+ "com_error_user_url_update": "Update your URL",+ "com_error_verify_email_limit": "Too many verification emails were requested. Wait a moment and try again.",+ "com_error_window_minute": "minute",+ "com_error_window_minutes": "{{0}} minutes","com_file_pages": "Pages: {{pages}}","com_file_source": "File","com_file_unknown": "Unknown File",@@ -1979,7 +2044,7 @@"com_ui_resource": "resource","com_ui_respond": "Respond","com_ui_response": "Response",- "com_ui_response_incomplete": "The response is incomplete; it's either still processing, was cancelled, or censored. Refresh or try a different prompt.",+ "com_ui_response_incomplete": "This response stopped before it finished. Regenerate it or send a new message.","com_ui_result": "Result","com_ui_result_found": "{{count}} result found","com_ui_results_found": "{{count}} results found",@@ -2511,6 +2576,7 @@"com_ui_tool_call_limit_body": "The agent used every step allowed in a single turn, so it stopped before finishing. Everything above is saved. Choose how to carry on.","com_ui_tool_call_limit_continue": "Keep going","com_ui_tool_call_limit_continue_prompt": "Keep going from where you stopped.",+ "com_ui_tool_call_limit_dismiss": "Dismiss this notice","com_ui_tool_call_limit_title": "Reached the tool call limit for this turn","com_ui_tool_collection_prefix": "A collection of tools from","com_ui_tool_credentials_saved": "Credentials saved",diff --git a/config/create-error-convo.js b/config/create-error-convo.jsnew file mode 100644index 0000000000..20e3ff3ab0--- /dev/null+++ b/config/create-error-convo.js@@ -0,0 +1,621 @@+/**+ * Seeds a mock conversation that renders every client-facing error shape.+ *+ * The chat client decides how to render a failure from the persisted row alone:+ * `error: true` sends `text` through `Messages/Content/Error`, `unfinished`+ * renders the incomplete/step-budget cards, and a `ContentTypes.ERROR` part+ * renders inline between ordinary parts. This script writes one user turn plus+ * one response turn for every one of those shapes, so the whole error surface+ * can be reviewed in a single conversation instead of being provoked one+ * failure at a time.+ *+ * Every `ErrorTypes` and `ViolationTypes` member must appear in the catalogue+ * below; the script refuses to write anything while one is missing, so a new+ * error type cannot be added upstream without also being reviewable here.+ *+ * Upload-time failures (`com_error_files_*`) are deliberately absent: they are+ * transient toasts raised by the composer and never persist on a message.+ *+ * Usage: npm run create-error-convo -- [email protected] [--endpoint=openAI] [--model=gpt-4o] [--title="..."]+ */+const crypto = require('node:crypto');+const mongoose = require('mongoose');+const { createModels } = require('@librechat/data-schemas');+const { Constants, ContentTypes, ErrorTypes, ViolationTypes } = require('librechat-data-provider');+const { askQuestion, silentExit } = require('./helpers');+const connect = require('./connect');++/** The exact tail LangChain appends to a classified provider error. */+const troubleshooting = (code) =>+ `\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${code}/\n`;++/** Boilerplate the SDK puts in front of the real pruning detail. */+const emptyMessagesInfo =+ 'Message pruning removed all messages as none fit in the context window. ' ++ 'Please increase the context window size or make your message shorter. ' ++ 'Token budget: 128000 total, 127480 reserved for instructions and tools, 520 available.';++/** `MessageContent` matches this text exactly to render the delayed connection card. */+const connectionErrorText = 'Error connecting to server, try refreshing the page.';++/**+ * A payload case persists `JSON.stringify(payload)` as the message text, which+ * is what `sendError`/`denyRequest` do on the server. `covers` records which+ * enum member the case exercises so the completeness check can see it.+ */+const payloadCase = (label, payload, options = {}) => ({+ label,+ text: JSON.stringify(payload),+ covers: payload.type ?? payload.code,+ ...options,+});++/** A raw-text case: provider text the client never classified. */+const textCase = (label, text, options = {}) => ({ label, text, ...options });++/** A structural case: the row itself (not its text) selects the rendering. */+const shapeCase = (label, message) => ({ label, error: false, ...message });++const ERROR_CASES = [+ /* ---------- user-key and endpoint configuration ---------- */+ payloadCase('No user-provided key', { type: ErrorTypes.NO_USER_KEY }),+ payloadCase('Expired user-provided key', {+ type: ErrorTypes.EXPIRED_USER_KEY,+ expiredAt: '2026-08-01T09:30:00.000Z',+ endpoint: 'openAI',+ }),+ /**+ * The same two failures on an endpoint whose key comes from the user rather than the+ * deployment: that is the branch which offers the key dialog, and `endpoint` on the row is what+ * the client reads to decide.+ */+ payloadCase(+ 'No key on a user-provided endpoint',+ { type: ErrorTypes.NO_USER_KEY },+ { endpoint: 'google', model: 'gemini-2.5-pro' },+ ),+ payloadCase(+ 'Expired key on a user-provided endpoint',+ {+ type: ErrorTypes.EXPIRED_USER_KEY,+ expiredAt: '2026-08-01T09:30:00.000Z',+ endpoint: 'google',+ },+ { endpoint: 'google', model: 'gemini-2.5-pro' },+ ),+ /** Rows persisted before the server stamped ISO timestamps carry its own locale format. */+ payloadCase('Expired key stamped in a server locale (shown as written)', {+ type: ErrorTypes.EXPIRED_USER_KEY,+ expiredAt: '01/08/2026, 09:30:00',+ endpoint: 'openAI',+ }),+ payloadCase('Invalid user-provided key', { type: ErrorTypes.INVALID_USER_KEY }),+ payloadCase(+ 'Unreadable key on a user-provided endpoint',+ { type: ErrorTypes.INVALID_USER_KEY },+ { endpoint: 'google', model: 'gemini-2.5-pro' },+ ),+ payloadCase('No base URL provided', { type: ErrorTypes.NO_BASE_URL }),+ payloadCase('Base URL targets a restricted address', { type: ErrorTypes.INVALID_BASE_URL }),+ payloadCase('No model selected', { type: ErrorTypes.MISSING_MODEL, info: 'openAI' }),+ payloadCase('Models configuration not loaded', { type: ErrorTypes.MODELS_NOT_LOADED }),+ payloadCase('Endpoint models not loaded', {+ type: ErrorTypes.ENDPOINT_MODELS_NOT_LOADED,+ info: 'anthropic',+ }),+ payloadCase('Provider excluded from agents', {+ type: ErrorTypes.INVALID_AGENT_PROVIDER,+ info: 'bedrock',+ }),++ /* ---------- request rejected before or during invocation ---------- */+ payloadCase('Moderation flagged the input', { type: ErrorTypes.MODERATION }),+ payloadCase('Prompt exceeds the token limit', {+ type: ErrorTypes.INPUT_LENGTH,+ info: '234856 / 172627',+ }),+ payloadCase('Provider rejected the request', { type: ErrorTypes.INVALID_REQUEST }),+ payloadCase('Action domain not allowed', { type: ErrorTypes.INVALID_ACTION }),+ payloadCase('Provider forbids system messages', { type: ErrorTypes.NO_SYSTEM_MESSAGES }),+ /** `ModelEndHandler` persists the provider's stop metadata object itself as `info`. */+ payloadCase('Model refused to answer (Anthropic stop details)', {+ type: ErrorTypes.REFUSAL,+ info: {+ stop_reason: 'refusal',+ stop_sequence: null,+ stop_details: {+ type: 'refusal',+ category: 'cyber',+ explanation: 'The request could enable malware development.',+ },+ },+ }),+ payloadCase('Model refused to answer (Bedrock content filter)', {+ type: ErrorTypes.REFUSAL,+ info: { stop_reason: 'content_filtered' },+ }),++ /* ---------- Google-specific ---------- */+ payloadCase('Google provider error (verbatim text)', {+ type: ErrorTypes.GOOGLE_ERROR,+ info: '400 Bad Request\nRequest contains an invalid argument: contents[3].parts is empty.',+ }),+ payloadCase('Google built-in tools conflict', { type: ErrorTypes.GOOGLE_TOOL_CONFLICT }),+ payloadCase('Google could not process the video', {+ type: ErrorTypes.GOOGLE_VIDEO_UNPROCESSABLE,+ }),++ /* ---------- code execution and workspaces ---------- */+ payloadCase('Attached resources could not be restored', {+ type: ErrorTypes.RESOURCE_RECOVERY_REQUIRED,+ }),+ payloadCase('Stateful code environment disallowed', {+ code: ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED,+ status: 403,+ }),+ payloadCase('Code workspace unavailable (no reason)', {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ }),+ payloadCase('Code workspace required', {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'required',+ }),+ payloadCase('Code workspace invalid', {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'invalid',+ }),+ payloadCase('Code workspace worker unavailable', {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'worker_unavailable',+ }),+ payloadCase('Code workspace unsupported', {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'unsupported',+ }),+ payloadCase('Code workspace missing', {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'missing',+ }),+ payloadCase('Code workspace locked to another environment', {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'locked',+ }),+ payloadCase('Code workspace with an unknown reason', {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'not_a_known_reason',+ }),++ /* ---------- streaming and upstream model failures ---------- */+ payloadCase('Stream expired before the client attached', { type: ErrorTypes.STREAM_EXPIRED }),+ payloadCase('Model not served by this provider', { type: ErrorTypes.MODEL_NOT_FOUND }),+ payloadCase('Provider rate or spend limit', { type: ErrorTypes.MODEL_RATE_LIMIT }),+ {+ label: 'Upstream model error with status (server prefix + JSON)',+ text: `The model provider failed and the run could not recover.\n${JSON.stringify({+ type: ErrorTypes.UPSTREAM_MODEL_ERROR,+ status: 503,+ })}`,+ covers: ErrorTypes.UPSTREAM_MODEL_ERROR,+ },+ payloadCase('Upstream model error without status', {+ type: ErrorTypes.UPSTREAM_MODEL_ERROR,+ }),++ /* ---------- context window and compaction ---------- */+ payloadCase('Context pruning removed every message', {+ type: ErrorTypes.EMPTY_MESSAGES,+ info: emptyMessagesInfo,+ }),+ payloadCase('Final context overflow with token detail', {+ type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,+ provider: 'openAI',+ projectedMessageTokens: 214_500,+ availableMessageTokens: 128_000,+ }),+ payloadCase('Final context overflow without token detail', {+ type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,+ }),+ payloadCase('Compaction skipped: summarization disabled', {+ type: ErrorTypes.COMPACTION_SKIPPED,+ reason: 'disabled',+ }),+ payloadCase('Compaction skipped: instructions exceed budget', {+ type: ErrorTypes.COMPACTION_SKIPPED,+ reason: 'instructions_exceed_budget',+ }),+ payloadCase('Compaction skipped: nothing to summarize', {+ type: ErrorTypes.COMPACTION_SKIPPED,+ reason: 'nothing_to_summarize',+ }),+ payloadCase('Compaction skipped with an unknown reason', {+ type: ErrorTypes.COMPACTION_SKIPPED,+ reason: 'not_a_known_reason',+ }),+ payloadCase('Compaction produced no summary', { type: ErrorTypes.COMPACTION_FAILED }),++ /* ---------- authentication ---------- */+ payloadCase('Authentication failed', {+ code: ErrorTypes.AUTH_FAILED,+ provider: 'local',+ }),+ payloadCase('Authentication rate limited', {+ code: ErrorTypes.AUTH_RATE_LIMITED,+ }),+ payloadCase('Authentication banned', { code: ErrorTypes.AUTH_BANNED }),+ payloadCase('Authentication rejected from another site', {+ code: ErrorTypes.AUTH_CROSS_ORIGIN,+ }),++ /* ---------- violations ---------- */+ payloadCase('Account banned', { type: ViolationTypes.BAN }),+ payloadCase('Illegal model request', {+ type: ViolationTypes.ILLEGAL_MODEL_REQUEST,+ info: 'openAI|gpt-4.5-preview',+ }),+ payloadCase('Token balance exhausted with generations', {+ type: ViolationTypes.TOKEN_BALANCE,+ balance: 1250,+ tokenCost: 8400,+ promptTokens: 6300,+ prev_count: 1,+ violation_count: 2,+ date: new Date('2026-09-01T10:00:00.000Z').toISOString(),+ generations: [+ { model: 'gpt-4o', promptTokens: 6300, completionTokens: 2100 },+ { model: 'gpt-4o-mini', promptTokens: 820, completionTokens: 240 },+ ],+ }),+ payloadCase('Token balance exhausted without generations', {+ type: ViolationTypes.TOKEN_BALANCE,+ balance: 0,+ tokenCost: 4000,+ promptTokens: 3200,+ }),+ payloadCase('Concurrent message limit', {+ type: ViolationTypes.CONCURRENT,+ limit: 1,+ pendingRequests: 2,+ score: 1,+ }),+ payloadCase('Message rate limit counting down within the hour', {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 40,+ limiter: 'user',+ windowInMinutes: 60,+ /**+ * What the limiter now persists. Seeded 55 minutes out so the countdown is still running+ * whenever the gallery is opened, rather than having already elapsed.+ */+ resetAt: Date.now() + 55 * 60 * 1000,+ retryAfterSeconds: 55 * 60,+ }),+ payloadCase('Message rate limit whose window already reset', {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 40,+ limiter: 'user',+ windowInMinutes: 60,+ resetAt: Date.now() - 2 * 60 * 1000,+ retryAfterSeconds: 60,+ }),+ payloadCase('Message rate limit without reset data', {+ type: ViolationTypes.MESSAGE_LIMIT,+ max: 1,+ limiter: 'ip',+ windowInMinutes: 1,+ }),+ payloadCase('File upload limit', {+ type: ViolationTypes.FILE_UPLOAD_LIMIT,+ max: 10,+ limiter: 'user',+ windowInMinutes: 60,+ }),+ payloadCase('Tool call limit violation', {+ type: ViolationTypes.TOOL_CALL_LIMIT,+ max: 1,+ limiter: 'user',+ windowInMinutes: 1,+ }),+ payloadCase('Conversation access denied', {+ type: ViolationTypes.CONVO_ACCESS,+ error: 'User not authorized for this conversation',+ }),+ payloadCase('TTS limit', {+ type: ViolationTypes.TTS_LIMIT,+ max: 50,+ limiter: 'user',+ windowInMinutes: 60,+ }),+ payloadCase('STT limit', {+ type: ViolationTypes.STT_LIMIT,+ max: 50,+ limiter: 'user',+ windowInMinutes: 60,+ }),+ payloadCase('Shared link retrieval limit', {+ type: ViolationTypes.SHARE_LIMIT,+ max: 20,+ limiter: 'ip',+ windowInMinutes: 60,+ }),+ payloadCase('Login attempt limit', {+ type: ViolationTypes.LOGINS,+ max: 7,+ limiter: 'ip',+ windowInMinutes: 20,+ }),+ payloadCase('Registration limit', {+ type: ViolationTypes.REGISTRATIONS,+ max: 5,+ limiter: 'ip',+ windowInMinutes: 60,+ }),+ payloadCase('Password reset limit', {+ type: ViolationTypes.RESET_PASSWORD_LIMIT,+ max: 3,+ limiter: 'ip',+ windowInMinutes: 10,+ }),+ payloadCase('Email verification limit', {+ type: ViolationTypes.VERIFY_EMAIL_LIMIT,+ max: 3,+ limiter: 'ip',+ windowInMinutes: 10,+ }),+ payloadCase('Non-browser access', { type: ViolationTypes.NON_BROWSER }),+ payloadCase('General violation', {+ type: ViolationTypes.GENERAL,+ error: 'Request blocked',+ }),++ /* ---------- provider error codes the client special-cases ---------- */+ payloadCase('Provider reports an invalid API key', {+ code: 'invalid_api_key',+ message: 'Incorrect API key provided: sk-****.',+ }),+ payloadCase('Provider reports an exhausted quota', {+ code: 'insufficient_quota',+ message: 'You exceeded your current quota, please check your plan and billing details.',+ }),+ payloadCase('Provider body nesting its message under error', {+ error: {+ message: 'Rate limit reached for gpt-4o in organization org-123 on tokens per min.',+ type: 'tokens',+ code: 'rate_limit_exceeded',+ },+ }),+ payloadCase('Unrecognized provider code (default fallback)', {+ code: 'im_a_teapot',+ message: 'The provider returned a code the client does not classify.',+ }),++ /* ---------- unclassified text ---------- */+ textCase(+ 'LangChain-classified rate limit (code read from the docs URL)',+ `429 You exceeded your current quota${troubleshooting('MODEL_RATE_LIMIT')}`,+ ),+ textCase(+ 'LangChain-classified missing model (code read from the docs URL)',+ `404 The model \`gpt-4.5-preview\` does not exist${troubleshooting('MODEL_NOT_FOUND')}`,+ ),+ textCase(+ 'LangChain code without copy (URL stripped, provider text kept)',+ `Failed to parse the model output${troubleshooting('OUTPUT_PARSING_FAILURE')}`,+ ),+ /** A failed run persists `<base message>: <SDK message>`, and Anthropic's SDK message embeds the body. */+ textCase(+ 'Provider body embedded after the failed-run prefix',+ `An error occurred while processing the request: 400 ${JSON.stringify({+ type: 'error',+ error: {+ type: 'invalid_request_error',+ message: 'prompt is too long: 250000 tokens > 200000 maximum',+ },+ request_id: 'req_011',+ })}`,+ ),+ textCase('Plain provider text (default fallback)', 'Error: connect ETIMEDOUT 104.18.7.192:443'),+ textCase(+ 'Provider text long enough to be collapsed into a detail',+ `The upstream gateway rejected the request. ${'Retry advice and a stack frame repeated to exceed the client truncation cap. '.repeat(+ 8,+ )}`,+ ),+ textCase('Connection error (delayed alert card)', connectionErrorText),++ /* ---------- row shapes, not text ---------- */+ shapeCase('Unfinished response (incomplete card)', {+ text: 'The migration plan has three phases. The first phase',+ unfinished: true,+ }),+ shapeCase('Step budget exhausted (tool call limit card)', {+ text: '',+ unfinished: true,+ finish_reason: Constants.TOOL_CALL_LIMIT_FINISH_REASON,+ content: [{ type: ContentTypes.TEXT, text: 'Checking the remaining files before I continue.' }],+ }),+ shapeCase('Error content part after partial output', {+ text: '',+ content: [+ {+ type: ContentTypes.TEXT,+ text: 'I read the deployment manifest and started the rollout, then the provider dropped the run:',+ },+ {+ type: ContentTypes.ERROR,+ error: JSON.stringify({ type: ErrorTypes.UPSTREAM_MODEL_ERROR, status: 503 }),+ },+ ],+ }),+ shapeCase('Error content part carrying plain text', {+ text: '',+ content: [+ {+ type: ContentTypes.ERROR,+ text: 'Tool `execute_code` exited with status 137 (out of memory).',+ },+ ],+ }),+ shapeCase('Error flagged on a user turn', {+ text: JSON.stringify({ type: ErrorTypes.MODERATION }),+ error: true,+ isCreatedByUser: true,+ }),+];++const COVERED = new Set(ERROR_CASES.map((errorCase) => errorCase.covers).filter(Boolean));++/** Refuses to seed a gallery that no longer shows every error type. */+function assertCatalogueIsComplete() {+ const missing = [...Object.values(ErrorTypes), ...Object.values(ViolationTypes)].filter(+ (type) => !COVERED.has(type),+ );+ if (missing.length === 0) {+ return;+ }+ console.red('The error catalogue is missing cases for:');+ missing.forEach((type) => console.red(` - ${type}`));+ console.orange('Add a case to ERROR_CASES in config/create-error-convo.js, then re-run.');+ silentExit(1);+}++function parseArgs(argv) {+ const options = {+ email: '',+ endpoint: 'openAI',+ model: 'gpt-4o',+ title: 'Error handling gallery',+ };+ for (const arg of argv) {+ const flag = /^--(endpoint|model|title)=(.+)$/.exec(arg);+ if (flag) {+ options[flag[1]] = flag[2];+ } else if (!options.email) {+ options.email = arg;+ }+ }+ return options;+}++/**+ * One user turn per case, so each response has a visible trigger, then the+ * response row that carries the failure. The chain is linear: every row's+ * parent is the row before it.+ */+function buildMessages({ conversationId, user, endpoint, model, startedAt }) {+ const messages = [];+ let parentMessageId = Constants.NO_PARENT;+ let createdAt = startedAt;++ ERROR_CASES.forEach((errorCase, index) => {+ const { label, covers: _covers, isCreatedByUser = false, ...response } = errorCase;+ const prompt = {+ messageId: crypto.randomUUID(),+ conversationId,+ user,+ parentMessageId,+ endpoint,+ model,+ sender: 'User',+ isCreatedByUser: true,+ text: `Case ${index + 1} — ${label}`,+ error: false,+ unfinished: false,+ createdAt: new Date(createdAt),+ updatedAt: new Date(createdAt),+ };+ createdAt += 1000;+ messages.push(prompt);++ const row = {+ messageId: crypto.randomUUID(),+ conversationId,+ user,+ parentMessageId: prompt.messageId,+ endpoint,+ model,+ sender: isCreatedByUser ? 'User' : model,+ isCreatedByUser,+ error: true,+ unfinished: false,+ createdAt: new Date(createdAt),+ updatedAt: new Date(createdAt),+ ...response,+ };+ createdAt += 1000;+ messages.push(row);+ parentMessageId = row.messageId;+ });++ return messages;+}++(async () => {+ assertCatalogueIsComplete();+ await connect();++ console.purple('---------------------------------------');+ console.purple('Create a mock conversation of every error');+ console.purple('---------------------------------------');++ const options = parseArgs(process.argv.slice(2));+ if (!options.email) {+ options.email = await askQuestion('Email of the account that should own the conversation:');+ }+ if (!options.email.includes('@')) {+ console.red(`Error: Invalid email address: ${options.email}`);+ silentExit(1);+ }++ const { User, Conversation, Message } = createModels(mongoose);+ const user = await User.findOne({ email: options.email }).select('_id').lean();+ if (!user) {+ console.red(`Error: No user found with email ${options.email}`);+ silentExit(1);+ }++ const conversationId = crypto.randomUUID();+ const messages = buildMessages({+ conversationId,+ user: user._id.toString(),+ endpoint: options.endpoint,+ model: options.model,+ startedAt: Date.now() - ERROR_CASES.length * 2000,+ });++ try {+ await Message.insertMany(messages, { timestamps: false });+ await Conversation.create({+ conversationId,+ user: user._id.toString(),+ title: options.title,+ endpoint: options.endpoint,+ model: options.model,+ isArchived: false,+ });+ } catch (error) {+ console.red(`Error: ${error.message}`);+ /** Without its conversation, every inserted row is unreachable debris that a rerun would add to. */+ await Promise.allSettled([+ Message.deleteMany({ conversationId }),+ Conversation.deleteMany({ conversationId }),+ ]);+ silentExit(1);+ }++ console.green(`Created "${options.title}" with ${ERROR_CASES.length} error cases`);+ console.purple(`conversationId: ${conversationId}`);+ console.purple(`open: /c/${conversationId}`);+ silentExit(0);+})();++process.on('uncaughtException', (err) => {+ if (!err.message.includes('fetch failed')) {+ console.error('There was an uncaught error:');+ console.error(err);+ }++ if (err.message.includes('fetch failed')) {+ return;+ }+ process.exit(1);+});diff --git a/e2e/specs/mock/scenarios/header-control-surface.spec.ts b/e2e/specs/mock/scenarios/header-control-surface.spec.tsindex 35eab798c6..fcd0f20c27 100644--- a/e2e/specs/mock/scenarios/header-control-surface.spec.ts+++ b/e2e/specs/mock/scenarios/header-control-surface.spec.ts@@ -198,7 +198,9 @@ test.describe('mobile chat header controls', () => {]);const theme = await page.locator('html').getAttribute('class');- expect(isOpaque(toggle.background), `toggle fill ${toggle.background} in ${theme}`).toBe(true);+ expect(isOpaque(toggle.background), `toggle fill ${toggle.background} in ${theme}`).toBe(+ true,+ );expect(toggle.background, `theme ${theme}`).toBe(newChat.background);expect(toggle.background, `theme ${theme}`).toBe(overflow.background);expect(toggle.radius).toBe(newChat.radius);diff --git a/package.json b/package.jsonindex 4d49924a4d..9a020ae2ea 100644--- a/package.json+++ b/package.json@@ -36,6 +36,7 @@"ban-user": "node config/ban-user.js","delete-user": "node config/delete-user.js","reset-meili-sync": "node config/reset-meili-sync.js",+ "create-error-convo": "node config/create-error-convo.js","update-banner": "node config/update-banner.js","delete-banner": "node config/delete-banner.js","backend": "cross-env NODE_ENV=production node api/server/index.js",diff --git a/packages/api/src/utils/index.ts b/packages/api/src/utils/index.tsindex 136a194f3c..f54f2efe18 100644--- a/packages/api/src/utils/index.ts+++ b/packages/api/src/utils/index.ts@@ -17,6 +17,7 @@ export * from './identity';export * from './path';export * from './key';export * from './latex';+export * from './limiter';export * from './llm';export * from './math';export * from './oidc';diff --git a/packages/api/src/utils/key.test.ts b/packages/api/src/utils/key.test.tsindex ae3de52708..d5c061688e 100644--- a/packages/api/src/utils/key.test.ts+++ b/packages/api/src/utils/key.test.ts@@ -1,7 +1,8 @@import path from 'path';import axios from 'axios';+import { ErrorTypes } from 'librechat-data-provider';+import { checkUserKeyExpiry, loadServiceKey } from './key';import { readFileAsString } from './files';-import { loadServiceKey } from './key';jest.mock('fs');jest.mock('axios');@@ -185,3 +186,30 @@ describe('loadServiceKey', () => {expect(result).toBeNull();});});++describe('checkUserKeyExpiry', () => {+ it('accepts a key that has not expired', () => {+ expect(() =>+ checkUserKeyExpiry(new Date(Date.now() + 60_000).toISOString(), 'openAI'),+ ).not.toThrow();+ });++ /** A locale-formatted date cannot be parsed back reliably by a client in another locale. */+ it('reports an expired key with a locale-independent ISO timestamp', () => {+ const expiresAt = '2026-08-01T09:30:00.000Z';++ let thrown: Error | undefined;+ try {+ checkUserKeyExpiry(expiresAt, 'google');+ } catch (error) {+ thrown = error as Error;+ }++ expect(thrown).toBeInstanceOf(Error);+ expect(JSON.parse(thrown?.message ?? '')).toEqual({+ type: ErrorTypes.EXPIRED_USER_KEY,+ expiredAt: expiresAt,+ endpoint: 'google',+ });+ });+});diff --git a/packages/api/src/utils/key.ts b/packages/api/src/utils/key.tsindex 041cbffc20..2dcf9e6cc1 100644--- a/packages/api/src/utils/key.ts+++ b/packages/api/src/utils/key.ts@@ -1,7 +1,7 @@import path from 'path';import axios from 'axios';-import { ErrorTypes } from 'librechat-data-provider';import { logger } from '@librechat/data-schemas';+import { ErrorTypes } from 'librechat-data-provider';import { readFileAsString } from './files';export interface GoogleServiceKey {@@ -124,14 +124,15 @@ export async function loadServiceKey(keyPath: string): Promise<GoogleServiceKey* @param expiresAt - The expiration date of the user key in a format that can be parsed by the Date constructor* @param endpoint - The endpoint associated with the user key to be checked* @throws Error if the user key has expired. The error message is a stringified JSON object- * containing the type of error (`ErrorTypes.EXPIRED_USER_KEY`), the expiration date in the local string format, and the endpoint.+ * containing the type of error (`ErrorTypes.EXPIRED_USER_KEY`), the expiration date as an ISO 8601+ * timestamp the client formats in the reader's locale, and the endpoint.*/export function checkUserKeyExpiry(expiresAt: string, endpoint: string): void {const expiresAtDate = new Date(expiresAt);if (expiresAtDate < new Date()) {const errorMessage = JSON.stringify({type: ErrorTypes.EXPIRED_USER_KEY,- expiredAt: expiresAtDate.toLocaleString(),+ expiredAt: expiresAtDate.toISOString(),endpoint,});throw new Error(errorMessage);diff --git a/packages/api/src/utils/limiter.spec.ts b/packages/api/src/utils/limiter.spec.tsnew file mode 100644index 0000000000..163aa25d9a--- /dev/null+++ b/packages/api/src/utils/limiter.spec.ts@@ -0,0 +1,40 @@+import { getRateLimitReset } from './limiter';++describe('getRateLimitReset', () => {+ const now = Date.UTC(2026, 8, 13, 12, 0, 0);++ it('reports the reset time the limiter store tracked', () => {+ const resetTime = new Date(now + 7 * 60 * 1000);++ expect(getRateLimitReset({ resetTime }, 60_000, now)).toEqual({+ resetAt: resetTime.getTime(),+ retryAfterSeconds: 420,+ });+ });++ it('rounds a partial second up so a retry never lands inside the window', () => {+ const resetTime = new Date(now + 1_200);++ expect(getRateLimitReset({ resetTime }, 60_000, now).retryAfterSeconds).toBe(2);+ });++ it.each([+ ['no rate limit info', undefined],+ ['a store without reset tracking', { resetTime: undefined }],+ ['an invalid reset date', { resetTime: new Date(Number.NaN) }],+ ])('falls back to one full window for %s', (_label, rateLimit) => {+ expect(getRateLimitReset(rateLimit, 3 * 24 * 60 * 60 * 1000, now)).toEqual({+ resetAt: now + 3 * 24 * 60 * 60 * 1000,+ retryAfterSeconds: 3 * 24 * 60 * 60,+ });+ });++ it('never tells a client to retry in less than a second', () => {+ const resetTime = new Date(now - 5_000);++ expect(getRateLimitReset({ resetTime }, 60_000, now)).toEqual({+ resetAt: resetTime.getTime(),+ retryAfterSeconds: 1,+ });+ });+});diff --git a/packages/api/src/utils/limiter.ts b/packages/api/src/utils/limiter.tsnew file mode 100644index 0000000000..3858d05fe6--- /dev/null+++ b/packages/api/src/utils/limiter.ts@@ -0,0 +1,27 @@+import type { RateLimitInfo } from 'express-rate-limit';++export interface RateLimitReset {+ /** Epoch milliseconds at which the client's window reopens. */+ resetAt: number;+ /** Whole seconds until `resetAt`, never below one, as a `Retry-After` header expects. */+ retryAfterSeconds: number;+}++/**+ * When a rate-limited client may retry. `express-rate-limit` reports the reset on+ * `req.rateLimit.resetTime` for stores that track it; without one, the window is assumed to reopen+ * one full window from now, the latest its current count can still apply.+ */+export function getRateLimitReset(+ rateLimit: Pick<RateLimitInfo, 'resetTime'> | undefined,+ windowMs: number,+ now: number = Date.now(),+): RateLimitReset {+ const reportedResetAt =+ rateLimit?.resetTime instanceof Date ? rateLimit.resetTime.getTime() : Number.NaN;+ const resetAt = Number.isFinite(reportedResetAt) ? reportedResetAt : now + windowMs;+ return {+ resetAt,+ retryAfterSeconds: Math.max(1, Math.ceil((resetAt - now) / 1000)),+ };+}