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
🧩 refactor: Message Parts Host Context (#16591)
Marco Berettad016c5b5861a
diff --git a/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx b/client/src/components/Chat/Messages/Content/Parts/BashCall.tsxindex 2cae8f90fb..2d703317f5 100644--- a/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx@@ -1,6 +1,5 @@import { useMemo, useRef, useState, useCallback, useEffect } from 'react';import copy from 'copy-to-clipboard';-import { useAtomValue } from 'jotai';import type { TAttachment, PartMetadata } from 'librechat-data-provider';import { parseBackgroundHandle, splitBackgroundAttachments } from './handle';import ProgressText from '~/components/Chat/Messages/Content/ProgressText';@@ -8,7 +7,7 @@ import parseJsonField, { areToolCallArgsComplete } from './parseJsonField';import CopyButton from '~/components/Messages/Content/CopyButton';import LangIcon from '~/components/Messages/Content/LangIcon';import { toolPanelSpacingClassName } from '../disclosure';-import { sandboxStartingByToolCallId } from '~/store';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import useToolCallState from './useToolCallState';import useLazyHighlight from './useLazyHighlight';import useFollowScroll from './useFollowScroll';@@ -59,7 +58,8 @@ export default function BashCall({const localize = useLocalize();const command = useMemo(() => parseJsonField(args, commandField), [args, commandField]);const isWritingCommand = !command || !areToolCallArgsComplete(args);- const sandboxStarting = useAtomValue(sandboxStartingByToolCallId(toolCallId ?? ''));+ const { useSandboxStarting } = useMessagePartsHost();+ const sandboxStarting = useSandboxStarting(toolCallId ?? '');/** Only a call the server stamped as attached-workspace carries an exit* status trailer; sandbox output keeps the text heuristic even when itdiff --git a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsxindex 8d438e9e87..03a2393cee 100644--- a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx@@ -1,11 +1,10 @@import { useMemo } from 'react';-import { useAtomValue } from 'jotai';import { SquareTerminal } from 'lucide-react';import type { TAttachment, PartMetadata } from 'librechat-data-provider';import { parseBackgroundHandle, splitBackgroundAttachments } from './handle';import ProgressText from '~/components/Chat/Messages/Content/ProgressText';import { toolPanelSpacingClassName } from '../disclosure';-import { sandboxStartingByToolCallId } from '~/store';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import useLazyHighlight from './useLazyHighlight';import useToolCallState from './useToolCallState';import CodeWindowHeader from './CodeWindowHeader';@@ -90,7 +89,8 @@ export default function ExecuteCode({/** Model-authored live label, streamed as the first args key; persists as* the settled label (completion is a UI state, not a tense change). */const intent = useToolCallIntent(args);- const sandboxStarting = useAtomValue(sandboxStartingByToolCallId(toolCallId ?? ''));+ const { useSandboxStarting } = useMessagePartsHost();+ const sandboxStarting = useSandboxStarting(toolCallId ?? '');const outputHasError = useMemo(() => ERROR_PATTERNS.test(output), [output]);/** A backgrounded call's persisted output stays the dispatch handle untildiff --git a/client/src/components/Chat/Messages/Content/Parts/LogLink.tsx b/client/src/components/Chat/Messages/Content/Parts/LogLink.tsxindex 4f284a0fb7..7bfeab1f09 100644--- a/client/src/components/Chat/Messages/Content/Parts/LogLink.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/LogLink.tsx@@ -1,8 +1,8 @@import React from 'react';-import { useToastContext } from '@librechat/client';import { FileSources, sharedFileDownload } from 'librechat-data-provider';import { getDownloadFilename, isHttpDownloadTarget, triggerDownload } from '~/utils';import { useCodeOutputDownload, useFileDownload } from '~/data-provider';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import useLocalize from '~/hooks/useLocalize';import { useShareContext } from '~/Providers';@@ -50,7 +50,8 @@ export const useAttachmentLink = ({source,}: AttachmentLinkOptions) => {const localize = useLocalize();- const { showToast } = useToastContext();+ const { useToast } = useMessagePartsHost();+ const showToast = useToast();const { shareId } = useShareContext();const useLocalDownload = isLocallyStoredSource(source) && !!file_id && !!user;diff --git a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx b/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsxindex 95bbd14441..8abddd2b57 100644--- a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx@@ -1,8 +1,5 @@import { memo, useMemo, useRef, useState } from 'react';-import { useAtomValue } from 'jotai';-import { useRecoilValue } from 'recoil';import { TextQuote } from 'lucide-react';-import { useToastContext } from '@librechat/client';import { useQueryClient } from '@tanstack/react-query';import { QueryKeys, type TMessage } from 'librechat-data-provider';import type { SteerReceiptState } from '~/components/Chat/Steering/Receipt';@@ -12,12 +9,11 @@ import useSteerEscalate from '~/hooks/Chat/useSteerEscalate';import useSteerRecovery from '~/hooks/Chat/useSteerRecovery';import { hasLiveRunPause } from '~/hooks/Chat/useSteering';import { useGetMessagesByConvoId } from '~/data-provider';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import { cn, isLegacyDeliveryUncertain } from '~/utils';-import { escalatingSteerFamily } from '~/store/steer';import { useLatestMessage } from '~/hooks/Messages';import { useLocalize } from '~/hooks';import SteerPart from './SteerPart';-import store from '~/store';const ACTION_CLASS ='rounded text-xs font-medium text-text-secondary hover:text-text-primary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-border-xheavy';@@ -38,15 +34,17 @@ interface PendingSteersProps {function PendingSteers({ conversationId, index = 0 }: PendingSteersProps) {const localize = useLocalize();- const { showToast } = useToastContext();- const steers = useRecoilValue(store.pendingSteersByConvoId(conversationId));+ const { useToast, usePendingSteers, useSteerEscalating, usePaneConversationId } =+ useMessagePartsHost();+ const showToast = useToast();+ const steers = usePendingSteers(conversationId);const { retry, sendAsNew } = useSteerRecovery(conversationId);const cancelSteer = useSteerCancel(conversationId);const escalate = useSteerEscalate(conversationId);const moveToQueue = useSteerMoveToQueue(conversationId);const rehomeSteer = useSteerRehome(conversationId);const [movingId, setMovingId] = useState<string | null>(null);- const escalating = useAtomValue(escalatingSteerFamily(conversationId));+ const escalating = useSteerEscalating(conversationId);/* Resolve the cache to the branch the user is viewing before applying theshared pause predicate. The cache contains every sibling branch, while`useLatestMessage` follows the same selection state as the message view. */@@ -54,7 +52,7 @@ function PendingSteers({ conversationId, index = 0 }: PendingSteersProps) {const cachedMessages =queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationId]) ?? [];const latestMessage = useLatestMessage(index, conversationId);- const paneConversationId = useRecoilValue(store.conversationIdByIndex(index));+ const paneConversationId = usePaneConversationId(index);const { data: fallbackPaused } = useGetMessagesByConvoId<boolean>(conversationId, {select: hasLiveRunPause,});diff --git a/client/src/components/Chat/Messages/Content/Parts/PtcToolTrace.tsx b/client/src/components/Chat/Messages/Content/Parts/PtcToolTrace.tsxindex 63ce54396d..0f237c5ed7 100644--- a/client/src/components/Chat/Messages/Content/Parts/PtcToolTrace.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/PtcToolTrace.tsx@@ -1,11 +1,9 @@-import { useRecoilValue } from 'recoil';import { useTranslation } from 'react-i18next';import { isReportableRunStepDuration } from 'librechat-data-provider';+import type { PtcTraceEntry } from '~/hooks/Chat/contract';import type { TranslationKeys } from '~/hooks';-import type { PtcTraceEntry } from '~/store';import { cn, parseToolName, getRunStepDurationLabels } from '~/utils';-import { useMessageContext } from '~/Providers/MessageContext';-import { ptcTraceByToolCallId, ptcTraceKey } from '~/store';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import { useMCPServerNames } from '~/hooks/MCP';import useFollowScroll from './useFollowScroll';import { useLocalize } from '~/hooks';@@ -59,7 +57,7 @@ function PtcTraceLine({ entry }: { entry: PtcTraceEntry }) {{STATUS_GLYPH[entry.status]}</span><span className="sr-only">{localize(STATUS_LABEL_KEYS[entry.status])}</span>- <span className="shrink-0 text-text-primary">+ <span className="text-text-primary shrink-0">{parsed.mcpServer && (<><span className="text-text-secondary">{parsed.mcpServer}</span>@@ -68,10 +66,10 @@ function PtcTraceLine({ entry }: { entry: PtcTraceEntry }) {)}{parsed.friendlyKey ? localize(parsed.friendlyKey) : parsed.toolName}</span>- <span className="min-w-0 flex-1 truncate text-text-tertiary">{entry.args ?? ''}</span>+ <span className="text-text-tertiary min-w-0 flex-1 truncate">{entry.args ?? ''}</span>{duration ? (<>- <span className="shrink-0 tabular-nums text-text-tertiary" aria-hidden="true">+ <span className="text-text-tertiary shrink-0 tabular-nums" aria-hidden="true">{localize(duration.key, duration.values)}</span><span className="sr-only">@@ -80,7 +78,7 @@ function PtcTraceLine({ entry }: { entry: PtcTraceEntry }) {</>) : (/* The sr-only status above already speaks this cell's meaning. */- <span className="shrink-0 text-text-tertiary" aria-hidden="true">+ <span className="text-text-tertiary shrink-0" aria-hidden="true">{running ? localize('com_ui_ptc_trace_running') : ''}</span>)}@@ -88,7 +86,7 @@ function PtcTraceLine({ entry }: { entry: PtcTraceEntry }) {{failed && (<div className="flex items-baseline gap-1.5"><span className="w-2 shrink-0" aria-hidden="true" />- <span className="min-w-0 flex-1 truncate text-status-error">+ <span className="text-status-error min-w-0 flex-1 truncate">{entry.error ?? localize('com_ui_ptc_trace_failed')}</span></div>@@ -120,10 +118,9 @@ export default function PtcToolTrace({const localize = useLocalize();/** Scope to this card's own message: providers reuse `tool_call_id` across* turns, so the raw id alone would show a later program's calls here. */- const { messageId } = useMessageContext();- const trace = useRecoilValue(- ptcTraceByToolCallId(toolCallId && messageId ? ptcTraceKey(messageId, toolCallId) : ''),- );+ const { useMessage, usePtcTrace } = useMessagePartsHost();+ const { messageId } = useMessage();+ const trace = usePtcTrace(messageId, toolCallId ?? '');/** One character per row, so the pin re-fires both when a call is appended* and when one settles — a settle can add an error line and change height. */@@ -145,7 +142,7 @@ export default function PtcToolTrace({* intended separation under a custom theme. */return (<div className={cn('p-4 text-xs', className)}>- <div className="mb-1.5 text-[10px] font-medium uppercase tracking-wide text-text-secondary">+ <div className="text-text-secondary mb-1.5 text-[10px] font-medium tracking-wide uppercase">{localize('com_ui_ptc_trace_title')}</div><ol@@ -157,7 +154,7 @@ export default function PtcToolTrace({{/* The retained tail is a window, not the whole program — say sorather than let the reader assume these are all the calls. */}{trace.dropped > 0 && (- <li className="leading-5 text-text-tertiary">+ <li className="text-text-tertiary leading-5">{localize('com_ui_ptc_trace_earlier', { count: trace.dropped })}</li>)}diff --git a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsxindex 57e577dff7..8d158abb87 100644--- a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx@@ -1,6 +1,6 @@import { memo, useMemo, useState, useEffect, useCallback, useRef, useId } from 'react';+import { useAtom } from 'jotai';import copy from 'copy-to-clipboard';-import { useAtom, useAtomValue } from 'jotai';import { Lightbulb, ChevronDown } from 'lucide-react';import { ContentTypes } from 'librechat-data-provider';import { Button, disclosureChevronVariants } from '@librechat/client';@@ -15,10 +15,8 @@ import {import { useLocalize, useExpandCollapse, useLazyCollapseBody } from '~/hooks';import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming';import CopyButton from '~/components/Messages/Content/CopyButton';-import { showThinkingAtom } from '~/store/showThinking';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import { useReasoningDisclosure } from '../disclosure';-import { fontSizeAtom } from '~/store/fontSize';-import { useMessageContext } from '~/Providers';import { ROW_GLYPH_SLOT } from '../rows';import { cn } from '~/utils';@@ -69,7 +67,8 @@ const PEEK_FADE =*/export const StreamingThoughtPeek = memo(({ text }: { text: string }) => {const ref = useRef<HTMLDivElement>(null);- const fontSize = useAtomValue(fontSizeAtom);+ const { useFontSize } = useMessagePartsHost();+ const fontSize = useFontSize();const peek = useMemo(() => lastSentences(text), [text]);/** Pin to the newest content as tokens arrive. `overflow-hidden` elements@@ -155,7 +154,8 @@ const Reasoning = memo((props: ReasoningProps) => {const { reasoning, isLast, reasoningLabel, partKeyIndex = 0 } = props;const contentId = useId();const localize = useLocalize();- const showThinking = useAtomValue(showThinkingAtom);+ const { useShowThinking, useMessage } = useMessagePartsHost();+ const showThinking = useShowThinking();const smoothStreaming = useSmoothStreaming();const [expansionOverride, setIsExpanded] = useAtom(useReasoningDisclosure(partKeyIndex));const [defaultExpanded] = useState(showThinking);@@ -165,7 +165,7 @@ const Reasoning = memo((props: ReasoningProps) => {const { ref: headerRef, inViewport: headerInViewport } = useInViewport();const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(isExpanded);- const { isSubmitting, isLatestMessage, nextType } = useMessageContext();+ const { isSubmitting, isLatestMessage, nextType } = useMessage();// Strip <think> tags from the reasoning content (modern format)const reasoningText = useMemo(() => stripThinkTags(reasoning), [reasoning]);@@ -310,7 +310,8 @@ export const ReasoningCompact = memo(}: ReasoningCompactProps) => {const contentId = useId();const localize = useLocalize();- const fontSize = useAtomValue(fontSizeAtom);+ const { useFontSize } = useMessagePartsHost();+ const fontSize = useFontSize();const [expansionOverride, setIsExpanded] = useAtom(useReasoningDisclosure(partKeyIndex));const [defaultExpanded] = useState(showThinking);const isExpanded = expansionOverride ?? defaultExpanded;diff --git a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsxindex 23a99c3f55..223a8853a2 100644--- a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx@@ -1,20 +1,17 @@import { memo, useMemo, useState, useEffect, useCallback } from 'react';-import { useRecoilValue } from 'recoil';-import { useAtomValue, useSetAtom } from 'jotai';import type { TFile, TMessage } from 'librechat-data-provider';import SteerReceipt, { type SteerReceiptState } from '~/components/Chat/Steering/Receipt';import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDialog';-import { liveAppliedSteerFamily, liveAppliedSteerIdsAtom } from '~/store/steer';import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';import MessageQuotes from '~/components/Chat/Messages/Content/MessageQuotes';import { cn, hydrateFileDeliveryMetadata, usesImagePreview } from '~/utils';import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';import FileContainer from '~/components/Chat/Input/Files/FileContainer';-import { useFileMapContext, useShareContext } from '~/Providers';import Image from '~/components/Chat/Messages/Content/Image';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import CollapsibleText from './CollapsibleText';+import { useShareContext } from '~/Providers';import { useLocalize } from '~/hooks';-import store from '~/store';/*** A mid-run steering message rendered as a standard user message inside the@@ -50,14 +47,13 @@ const SteerPart = memo(function SteerPart({receiptState?: SteerReceiptState;}) {const localize = useLocalize();- /** Read the atom rather than the auth context: AuthContextProvider mirrors the- * user into it, and the public share route mounts outside that provider. */- const user = useRecoilValue(store.user);+ const { useUser, useFileMap, useUserTextPreferences, useLiveAppliedSteer } =+ useMessagePartsHost();+ const user = useUser();const { isSharedConvo } = useShareContext();- const fileMap = useFileMapContext();- const usernameDisplay = useRecoilValue<boolean>(store.UsernameDisplay);- const enableUserMsgMarkdown = useRecoilValue<boolean>(store.enableUserMsgMarkdown);- const collapseLongUserMessages = useRecoilValue<boolean>(store.collapseLongUserMessages);+ const fileMap = useFileMap();+ const { usernameDisplay, enableUserMsgMarkdown, collapseLongUserMessages } =+ useUserTextPreferences();/** The share surface must never label the SHARER's steers with the* viewer's identity; always the generic user label there. */@@ -97,8 +93,7 @@ const SteerPart = memo(function SteerPart({* identity consumes its id whether it animated or not, so nothing lingers.* The membership selector scopes the subscription to THIS id — stamping or* consuming one steer never re-renders the other mounted parts. */- const isLiveApplied = useAtomValue(liveAppliedSteerFamily(steerId ?? ''));- const setLiveAppliedIds = useSetAtom(liveAppliedSteerIdsAtom);+ const [isLiveApplied, consumeLiveApplied] = useLiveAppliedSteer(steerId ?? '');const [captured, setCaptured] = useState<{ id: string | undefined; animate: boolean }>({id: steerId,animate: isLiveApplied,@@ -111,10 +106,8 @@ const SteerPart = memo(function SteerPart({if (steerId == null || steerId.length === 0) {return;}- setLiveAppliedIds((prev) =>- prev.includes(steerId) ? prev.filter((id) => id !== steerId) : prev,- );- }, [steerId, setLiveAppliedIds]);+ consumeLiveApplied(steerId);+ }, [steerId, consumeLiveApplied]);if (typeof steer !== 'string' || steer.length === 0) {return null;diff --git a/client/src/components/Chat/Messages/Content/Parts/Summary.tsx b/client/src/components/Chat/Messages/Content/Parts/Summary.tsxindex 9a64f7bf60..ca4317c339 100644--- a/client/src/components/Chat/Messages/Content/Parts/Summary.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/Summary.tsx@@ -1,12 +1,10 @@import { memo, useMemo, useState, useCallback, useRef, useId, useEffect } from 'react';-import { useAtomValue } from 'jotai';import { Copy, Check } from 'lucide';import { ScrollText, ChevronDown, ChevronUp } from 'lucide-react';import { Button, MorphIcon, TooltipAnchor } from '@librechat/client';import type { SummaryContentPart } from 'librechat-data-provider';import type { MouseEvent, FocusEvent } from 'react';-import { fontSizeAtom } from '~/store/fontSize';-import { useMessageContext } from '~/Providers';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -41,7 +39,8 @@ function useCopyToClipboard(content?: string) {}const SummaryContent = memo(({ children, meta }: { children: React.ReactNode; meta?: string }) => {- const fontSize = useAtomValue(fontSizeAtom);+ const { useFontSize } = useMessagePartsHost();+ const fontSize = useFontSize();return (<div className="border-border-medium bg-surface-tertiary text-text-secondary relative rounded-3xl border p-4 pb-10">@@ -72,7 +71,8 @@ const SummaryButton = memo(onCopy: (e: MouseEvent<HTMLButtonElement>) => void;}) => {const localize = useLocalize();- const fontSize = useAtomValue(fontSizeAtom);+ const { useFontSize } = useMessagePartsHost();+ const fontSize = useFontSize();return (<div className="group/summary flex w-full items-center justify-between gap-2">@@ -210,7 +210,8 @@ const Summary = memo(const [isExpanded, setIsExpanded] = useState(false);const [isBarVisible, setIsBarVisible] = useState(false);const containerRef = useRef<HTMLDivElement>(null);- const { isSubmitting, isLatestMessage } = useMessageContext();+ const { useMessage } = useMessagePartsHost();+ const { isSubmitting, isLatestMessage } = useMessage();const text = useMemo(() =>diff --git a/client/src/components/Chat/Messages/Content/Parts/Text.tsx b/client/src/components/Chat/Messages/Content/Parts/Text.tsxindex fc450c5daa..90a00c4a8e 100644--- a/client/src/components/Chat/Messages/Content/Parts/Text.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/Text.tsx@@ -1,12 +1,10 @@import { memo, useMemo, ReactElement } from 'react';-import { useRecoilValue } from 'recoil';import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming';import Markdown from '~/components/Chat/Messages/Content/Markdown';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import CollapsibleText from './CollapsibleText';-import { useMessageContext } from '~/Providers';import { cn } from '~/utils';-import store from '~/store';type TextPartProps = {text: string;@@ -20,9 +18,9 @@ type ContentType =| ReactElement;const TextPart = memo(function TextPart({ text, isCreatedByUser, showCursor }: TextPartProps) {- const { isSubmitting = false, isLatestMessage = false } = useMessageContext();- const enableUserMsgMarkdown = useRecoilValue(store.enableUserMsgMarkdown);- const collapseLongUserMessages = useRecoilValue(store.collapseLongUserMessages);+ const { useMessage, useUserTextPreferences } = useMessagePartsHost();+ const { isSubmitting = false, isLatestMessage = false } = useMessage();+ const { enableUserMsgMarkdown, collapseLongUserMessages } = useUserTextPreferences();const smoothStreaming = useSmoothStreaming();// The word fade itself indicates streaming, so the trailing block cursor// only shows when the fade is unavailable (setting off or reduced motion).diff --git a/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx b/client/src/components/Chat/Messages/Content/Parts/Thinking.tsxindex 32f88e39b3..470b232ae4 100644--- a/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx@@ -8,15 +8,13 @@ import {useId,type MouseEvent,} from 'react';-import { useAtomValue } from 'jotai';import { Lightbulb, ChevronDown } from 'lucide-react';import { Button, MorphIcon, TooltipAnchor } from '@librechat/client';import { ChevronUp as ChevronUpNode, ChevronDown as ChevronDownNode } from 'lucide';import type { FocusEvent, FC } from 'react';import CopyButton from '~/components/Messages/Content/CopyButton';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import { useLocalize, useExpandCollapse } from '~/hooks';-import { showThinkingAtom } from '~/store/showThinking';-import { fontSizeAtom } from '~/store/fontSize';import { AnimatedText } from '../animate';import { ROW_GLYPH_SLOT } from '../rows';import { cn } from '~/utils';@@ -57,7 +55,8 @@ export const ThinkingContent: FC<{children: React.ReactNode;animate?: boolean;}> = memo(({ children, animate = false }) => {- const fontSize = useAtomValue(fontSizeAtom);+ const { useFontSize } = useMessagePartsHost();+ const fontSize = useFontSize();const content =animate && typeof children === 'string' ? <AnimatedText text={children} /> : children;@@ -300,7 +299,8 @@ export const FloatingThinkingBar = memo(*/const Thinking: React.ElementType = memo(({ children }: { children: React.ReactNode }) => {const localize = useLocalize();- const showThinking = useAtomValue(showThinkingAtom);+ const { useShowThinking } = useMessagePartsHost();+ const showThinking = useShowThinking();const [isExpanded, setIsExpanded] = useState(showThinking);const [isBarVisible, setIsBarVisible] = useState(false);const containerRef = useRef<HTMLDivElement>(null);diff --git a/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx b/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsxindex c6bb707a38..9c7669ae6b 100644--- a/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx@@ -1,19 +1,11 @@import { memo, useEffect, useId, useLayoutEffect, useRef } from 'react';-import {- useRecoilCallback,- useRecoilState,- useRecoilValue,- useResetRecoilState,- useSetRecoilState,-} from 'recoil';import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';import type { Artifact } from '~/common';import { artifactRowKind, isCodeOnlyArtifact } from '~/utils/artifacts';-import { useMessageContext } from '~/Providers/MessageContext';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import { displayFilename } from './attachmentTypes';import { useAttachmentLink } from './LogLink';import ArtifactRow from './ArtifactRow';-import store from '~/store';interface ToolArtifactCardProps {attachment: TAttachment;@@ -67,36 +59,26 @@ interface ToolArtifactCardProps {*/const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps) => {const claimKey = useId();- const { isSubmitting, messageId } = useMessageContext();+ const { useMessage, useArtifactPanel, useToolArtifactClaim } = useMessagePartsHost();+ const { isSubmitting, messageId } = useMessage();const ownerMessageId = messageId || attachment.messageId || '';const file = attachment as TFile & TAttachmentMetadata;const fileId = file.file_id;- const setVisible = useSetRecoilState(store.artifactsVisibility);- const setArtifacts = useSetRecoilState(store.artifactsState);- const setCurrentArtifactId = useSetRecoilState(store.currentArtifactId);- const resetCurrentArtifactId = useResetRecoilState(store.currentArtifactId);- const currentArtifactId = useRecoilValue(store.currentArtifactId);- const existingEntry = useRecoilValue(store.artifactByIdSelector(artifact.id));- const [claim, setClaim] = useRecoilState(store.toolArtifactClaim(artifact.id));+ const {+ currentArtifactId,+ registered: existingEntry,+ register,+ open,+ close,+ consumeJustResolved,+ } = useArtifactPanel(artifact.id);+ const [claim, setClaim] = useToolArtifactClaim(artifact.id);const isSelected = artifact.id === currentArtifactId;const isMyClaim = claim === claimKey;- /* Read+reset only for this response — `useRecoilCallback` avoids subscribing- * to other file or message flags (no re-renders when other previews resolve).- * The deferred-preview hook flips this to `true` on the pending→ready- * edge; we consume it once and reset, so repeat mounts (panel close- * then reopen, history scroll) don't auto-open a second time. */- const consumeJustResolved = useRecoilCallback(- ({ snapshot, reset }) =>- (ownerId: string, id: string) => {- const signal = store.previewJustResolved([ownerId, id]);- const flagged = snapshot.getLoadable(signal).valueMaybe() ?? false;- if (flagged) {- reset(signal);- }- return flagged;- },- [],- );+ /* `consumeJustResolved` reads and resets only this response's flag, without+ * subscribing to other file or message flags. The deferred-preview hook flips+ * it to `true` on the pending→ready edge; we consume it once, so repeat mounts+ * (panel close then reopen, history scroll) don't auto-open a second time. *//** Positional reconciliation can reuse this card for another response with the same file ID. */const mountedDuringStreamRef = useRef({ ownerMessageId, isSubmitting: isSubmitting === true });if (mountedDuringStreamRef.current.ownerMessageId !== ownerMessageId) {@@ -131,8 +113,8 @@ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps)) {return;}- setArtifacts((prev) => ({ ...(prev ?? {}), [artifact.id]: artifact }));- }, [artifact, existingEntry, isMyClaim, setArtifacts]);+ register(artifact);+ }, [artifact, existingEntry, isMyClaim, register]);useEffect(() => {if (isCodeOnlyArtifact(artifact.type)) {@@ -165,21 +147,12 @@ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps)return;}// Streaming arrival or just-resolved preview: focus the new artifact- // AND force the panel visible. Without `setVisible(true)`, a session+ // AND force the panel visible. Without revealing it, a session// where the user had previously closed the panel (visibility=false)// would surface the selection in the chip ("click to close") but- // never actually open — `Presentation` gates rendering on visibility.- setCurrentArtifactId(artifact.id);- setVisible(true);- }, [- artifact.id,- artifact.type,- fileId,- ownerMessageId,- consumeJustResolved,- setCurrentArtifactId,- setVisible,- ]);+ // never actually open: `Presentation` gates rendering on visibility.+ open(artifact.id);+ }, [artifact.id, artifact.type, fileId, ownerMessageId, consumeJustResolved, open]);const { handleDownload } = useAttachmentLink({href: attachment.filepath ?? '',@@ -191,14 +164,12 @@ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps)const handleOpen = () => {if (isSelected) {- resetCurrentArtifactId();- setVisible(false);+ close();return;}// Registration already happened in the mount effect; the click only// needs to focus + reveal the panel for users who have closed it.- setCurrentArtifactId(artifact.id);- setVisible(true);+ open(artifact.id);};// Another card with the same artifact id has the active claim — renderdiff --git a/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx b/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsxindex 7759135758..dc9d92540a 100644--- a/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx@@ -1,14 +1,13 @@import { memo, useId, useLayoutEffect, useMemo, useState } from 'react';import { Download } from 'lucide-react';-import { useRecoilState } from 'recoil';import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';import { fileToArtifact, TOOL_ARTIFACT_TYPES, toolArtifactKey } from '~/utils/artifacts';import Mermaid from '~/components/Messages/Content/Mermaid/Mermaid';+import { useMessagePartsHost } from '~/hooks/Chat/parts';import { displayFilename } from './attachmentTypes';import { useAttachmentLink } from './LogLink';import { useLocalize } from '~/hooks';import { cn } from '~/utils';-import store from '~/store';interface ToolMermaidArtifactProps {attachment: TAttachment;@@ -27,7 +26,8 @@ const ToolMermaidArtifact = memo(({ attachment, text }: ToolMermaidArtifactPropsconst localize = useLocalize();const file = attachment as TFile & TAttachmentMetadata;const claimKey = useId();- const [claim, setClaim] = useRecoilState(store.toolArtifactClaim(toolArtifactKey(file)));+ const { useToolArtifactClaim } = useMessagePartsHost();+ const [claim, setClaim] = useToolArtifactClaim(toolArtifactKey(file));const isMyClaim = claim === claimKey;/* Once the diagram collapses into its trigger row, that row carries the* filename and the download itself, so this header would repeat bothdiff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/host.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/host.test.tsxnew file mode 100644index 0000000000..f5e132faa9--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/host.test.tsx@@ -0,0 +1,175 @@+import React from 'react';+import { render, screen, fireEvent } from '@testing-library/react';+import type { TAttachment } from 'librechat-data-provider';+import type {+ MessagePartArtifactPanel,+ MessagePartMessage,+ MessagePartsHost,+ PtcTrace,+} from '~/hooks/Chat/contract';+import type { Artifact } from '~/common';+import { MessagePartsHostProvider, appMessagePartsHost } from '~/hooks/Chat/parts';+import ToolArtifactCard from '../ToolArtifactCard';+import PtcToolTrace from '../PtcToolTrace';+import TextPart from '../Text';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));+jest.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));+jest.mock('~/hooks/MCP', () => ({ useMCPServerNames: () => [] }));+jest.mock('~/hooks/Messages/useSmoothStreaming', () => () => false);+jest.mock('~/components/Chat/Messages/Content/Markdown', () => ({+ __esModule: true,+ default: ({ content }: { content: string }) => <div data-testid="markdown">{content}</div>,+}));+jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({+ __esModule: true,+ default: ({ content }: { content: string }) => <div data-testid="markdown-lite">{content}</div>,+}));+jest.mock('../LogLink', () => ({+ useAttachmentLink: () => ({ handleDownload: jest.fn() }),+}));++/** A host backed by plain values: rendering under it must not touch Recoil, Jotai or app providers. */+function createHost(overrides: Partial<MessagePartsHost> = {}): MessagePartsHost {+ const message: MessagePartMessage = { messageId: 'msg-1', isSubmitting: false };+ return {+ ...appMessagePartsHost,+ useMessage: () => message,+ useFontSize: () => 'text-base',+ useShowThinking: () => false,+ useUserTextPreferences: () => ({+ usernameDisplay: false,+ enableUserMsgMarkdown: false,+ collapseLongUserMessages: false,+ }),+ useUser: () => undefined,+ useFileMap: () => undefined,+ useToast: () => jest.fn(),+ useSandboxStarting: () => false,+ usePtcTrace: () => ({ entries: [], dropped: 0 }),+ useToolArtifactClaim: () => [null, jest.fn()],+ usePendingSteers: () => [],+ useSteerEscalating: () => false,+ usePaneConversationId: () => null,+ useLiveAppliedSteer: () => [false, jest.fn()],+ ...overrides,+ };+}++function createPanel(overrides: Partial<MessagePartArtifactPanel> = {}): MessagePartArtifactPanel {+ return {+ currentArtifactId: null,+ registered: undefined,+ register: jest.fn(),+ open: jest.fn(),+ close: jest.fn(),+ consumeJustResolved: jest.fn(() => false),+ ...overrides,+ };+}++const artifact = {+ id: 'artifact-1',+ type: 'text/html',+ title: 'report.html',+ content: '<p>hi</p>',+} as Artifact;++const attachment = {+ file_id: 'file-1',+ filename: 'report.html',+ filepath: '/files/report.html',+ messageId: 'msg-1',+} as unknown as TAttachment;++describe('message parts host', () => {+ it('renders user text from the host preferences without an app store', () => {+ render(+ <MessagePartsHostProvider host={createHost()}>+ <TextPart text="plain *words*" isCreatedByUser={true} showCursor={false} />+ </MessagePartsHostProvider>,+ );+ expect(screen.queryByTestId('markdown-lite')).toBeNull();+ expect(screen.getByText('plain *words*')).toHaveClass('whitespace-pre-wrap');+ });++ it('honors the host markdown preference for user text', () => {+ const host = createHost({+ useUserTextPreferences: () => ({+ usernameDisplay: false,+ enableUserMsgMarkdown: true,+ collapseLongUserMessages: false,+ }),+ });+ render(+ <MessagePartsHostProvider host={host}>+ <TextPart text="plain *words*" isCreatedByUser={true} showCursor={false} />+ </MessagePartsHostProvider>,+ );+ expect(screen.getByTestId('markdown-lite')).toHaveTextContent('plain *words*');+ });++ it('reads the PTC trace for its own message and tool call from the host', () => {+ const trace: PtcTrace = {+ entries: [{ callId: 'c1', name: 'search_code', status: 'success' }],+ dropped: 0,+ };+ const usePtcTrace = jest.fn(() => trace);+ render(+ <MessagePartsHostProvider host={createHost({ usePtcTrace })}>+ <PtcToolTrace toolCallId="call-1" />+ </MessagePartsHostProvider>,+ );+ expect(usePtcTrace).toHaveBeenCalledWith('msg-1', 'call-1');+ expect(screen.getByText(/search_code/)).toBeInTheDocument();+ });++ it('auto-opens an artifact card mounted while its message streams', () => {+ const panel = createPanel();+ const host = createHost({+ useMessage: () => ({ messageId: 'msg-1', isSubmitting: true }),+ useArtifactPanel: () => panel,+ });+ render(+ <MessagePartsHostProvider host={host}>+ <ToolArtifactCard attachment={attachment} artifact={artifact} />+ </MessagePartsHostProvider>,+ );+ expect(panel.register).not.toHaveBeenCalled();+ expect(panel.open).toHaveBeenCalledWith('artifact-1');+ });++ it('registers as the claim holder and toggles the panel through the host', () => {+ const panel = createPanel({ currentArtifactId: 'artifact-1' });+ const setClaim = jest.fn();+ const host = createHost({+ useArtifactPanel: () => panel,+ useToolArtifactClaim: () => [null, setClaim],+ });+ const { rerender } = render(+ <MessagePartsHostProvider host={host}>+ <ToolArtifactCard attachment={attachment} artifact={artifact} />+ </MessagePartsHostProvider>,+ );+ expect(setClaim).toHaveBeenCalledWith(expect.any(String));+ expect(panel.open).not.toHaveBeenCalled();+ expect(panel.consumeJustResolved).toHaveBeenCalledWith('msg-1', 'file-1');++ fireEvent.click(screen.getByRole('button', { expanded: true }));+ expect(panel.close).toHaveBeenCalledTimes(1);++ const claimKey = setClaim.mock.calls[0][0] as string;+ const claimed = createHost({+ useArtifactPanel: () => panel,+ useToolArtifactClaim: () => [claimKey, setClaim],+ });+ rerender(+ <MessagePartsHostProvider host={claimed}>+ <ToolArtifactCard attachment={attachment} artifact={artifact} />+ </MessagePartsHostProvider>,+ );+ expect(panel.register).toHaveBeenCalledWith(artifact);+ });+});diff --git a/client/src/components/Chat/Messages/MessagesView.tsx b/client/src/components/Chat/Messages/MessagesView.tsxindex d5d666813a..7f6cd4f929 100644--- a/client/src/components/Chat/Messages/MessagesView.tsx+++ b/client/src/components/Chat/Messages/MessagesView.tsx@@ -11,6 +11,7 @@ import {useConversationSeen,} from '~/hooks';import { MessagesViewProvider, useChatContext, useFileMapContext } from '~/Providers';+import { MessagePartsHostProvider, appMessagePartsHost } from '~/hooks/Chat/parts';import { RowMountProvider, useProgressiveRowMount } from '~/hooks/Messages';import { useChatSurface } from '~/components/Chat/Subagents/surface';import useThreadRows from '~/hooks/Messages/useThreadRows';@@ -228,7 +229,9 @@ export default function MessagesView({}) {return (<MessagesViewProvider>- <MessagesViewContent messagesTree={messagesTree} messages={messages} />+ <MessagePartsHostProvider host={appMessagePartsHost}>+ <MessagesViewContent messagesTree={messagesTree} messages={messages} />+ </MessagePartsHostProvider></MessagesViewProvider>);}diff --git a/client/src/hooks/Chat/contract.ts b/client/src/hooks/Chat/contract.tsindex 64bb0111c5..39626452e5 100644--- a/client/src/hooks/Chat/contract.ts+++ b/client/src/hooks/Chat/contract.ts@@ -1,4 +1,5 @@import type {+ TFile,TPreset,TMessage,TConversation,@@ -6,6 +7,7 @@ import type {ChatTransportRequest,} from 'librechat-data-provider';import type { SetStateAction, Dispatch, MouseEvent } from 'react';+import type { TShowToast } from '@librechat/client';import type {ArmSteerParams,ArmSteerResponse,@@ -18,7 +20,17 @@ import type {AgentQueuedTurnReceipt,EnqueueAgentQueuedTurnRequest,} from '~/data-provider';-import type { NewConversationParams, TOptionSettings, ExtendedFile, TAskFunction } from '~/common';+import type {+ NewConversationParams,+ TOptionSettings,+ ExtendedFile,+ TAskFunction,+ Artifact,+} from '~/common';+import type { PendingSteer } from '~/store/families';+import type { PtcTrace } from '~/store/ptc';++export type { PtcTrace, PtcTraceEntry } from '~/store/ptc';/** Options accepted by {@link ChatConversationContract.newConversation}: the shared params plus* the two flags only the root pane's generator honors. */@@ -226,3 +238,98 @@ export interface Transport {queuedTurnId: string;}) => Promise<AgentQueuedTurnReceipt>;}++/** The message a part renders in, as its host reports it. */+export type MessagePartMessage = {+ /** Id of the message that owns the part, or `''` outside a message. */+ messageId: string;+ /** Whether that message is still generating. */+ isSubmitting?: boolean;+ /** Whether that message is the tail of the active branch. */+ isLatestMessage?: boolean;+ /** Content type of the part after this one, when known. */+ nextType?: string;+};++/** How the viewer prefers user-authored text to display. */+export type MessagePartsUserTextPreferences = {+ /** Whether user-authored text renders as markdown. */+ enableUserMsgMarkdown: boolean;+ /** Whether long user-authored text collapses behind a toggle. */+ collapseLongUserMessages: boolean;+ /** Whether user turns are labeled with the user's name. */+ usernameDisplay: boolean;+};++/** The signed-in user as the parts label it; `undefined` on a public share. */+export type MessagePartsUser = { name?: string; username?: string } | undefined;++/** Shows a transient notification. */+export type MessagePartsToast = (toast: TShowToast) => void;++/** The artifact panel as one tool artifact card drives it. */+export type MessagePartArtifactPanel = {+ /** The artifact the panel is focused on, if any. */+ currentArtifactId: string | null;+ /** The panel's stored entry for the card's artifact, if registered. */+ registered: Artifact | undefined;+ /** Stores or replaces the card's artifact in the panel. Stable across renders. */+ register: (artifact: Artifact) => void;+ /** Focuses an artifact and reveals the panel. Stable across renders. */+ open: (artifactId: string) => void;+ /** Clears the focus and hides the panel. Stable across renders. */+ close: () => void;+ /**+ * Reads and clears the one-shot "deferred preview just resolved" flag for a file in a message.+ * Stable across renders.+ */+ consumeJustResolved: (messageId: string, fileId: string) => boolean;+};++/**+ * Everything the message part components read from the app, supplied by the view that renders+ * them through `MessagePartsHostProvider`. Members are hooks, called unconditionally by the parts+ * that need them, so keyed reads subscribe to one key only. A host must stay the same object for+ * the life of the tree it wraps. Setters are typed as React dispatchers, so the contract names no+ * state library.+ */+export type MessagePartsHost = {+ /** The message the calling part renders in. */+ useMessage: () => MessagePartMessage;+ /** The viewer's font size utility, applied to reasoning and summary text. */+ useFontSize: () => string;+ /** Whether the viewer wants reasoning expanded by default. */+ useShowThinking: () => boolean;+ /** How the viewer prefers user-authored text to display. */+ useUserTextPreferences: () => MessagePartsUserTextPreferences;+ /** The signed-in user. */+ useUser: () => MessagePartsUser;+ /** The user's uploaded files keyed by file id, used to hydrate attachment metadata. */+ useFileMap: () => Record<string, TFile> | undefined;+ /** The notification function. */+ useToast: () => MessagePartsToast;+ /** Whether the sandbox for a code tool call is still starting. */+ useSandboxStarting: (toolCallId: string) => boolean;+ /** Live inner-call trace of one programmatic tool call in one message. */+ usePtcTrace: (messageId: string, toolCallId: string) => PtcTrace;+ /**+ * Which mounted card owns the row for a tool artifact, so one file renders once across tool+ * calls and messages. The key is the artifact id.+ */+ useToolArtifactClaim: (+ artifactId: string,+ ) => [string | null, Dispatch<SetStateAction<string | null>>];+ /** The artifact panel, scoped to one artifact. */+ useArtifactPanel: (artifactId: string) => MessagePartArtifactPanel;+ /** Steers sent to a conversation that the server has not confirmed yet. */+ usePendingSteers: (conversationId: string) => PendingSteer[];+ /** Whether a steer in a conversation is being escalated to an interrupt. */+ useSteerEscalating: (conversationId: string) => boolean;+ /** The conversation a pane is showing, or `null`. */+ usePaneConversationId: (index: number) => string | null;+ /**+ * Whether a steer was just applied live (and should animate in), plus a stable function that+ * clears that mark for a steer id once the part has seen it.+ */+ useLiveAppliedSteer: (steerId: string) => [boolean, (steerId: string) => void];+};diff --git a/client/src/hooks/Chat/parts.tsx b/client/src/hooks/Chat/parts.tsxnew file mode 100644index 0000000000..f37cce9033--- /dev/null+++ b/client/src/hooks/Chat/parts.tsx@@ -0,0 +1,133 @@+import { createContext, useCallback, useContext, useMemo } from 'react';+import { useAtomValue, useSetAtom } from 'jotai';+import { useToastContext } from '@librechat/client';+import {+ useRecoilCallback,+ useRecoilState,+ useRecoilValue,+ useResetRecoilState,+ useSetRecoilState,+} from 'recoil';+import type { ReactNode } from 'react';+import type {+ MessagePartArtifactPanel,+ MessagePartsUserTextPreferences,+ MessagePartMessage,+ MessagePartsHost,+} from './contract';+import type { Artifact } from '~/common';+import {+ liveAppliedSteerFamily,+ liveAppliedSteerIdsAtom,+ escalatingSteerFamily,+} from '~/store/steer';+import store, { ptcTraceByToolCallId, ptcTraceKey, sandboxStartingByToolCallId } from '~/store';+import { useMessageContext, useFileMapContext } from '~/Providers';+import { showThinkingAtom } from '~/store/showThinking';+import { fontSizeAtom } from '~/store/fontSize';++function useAppMessage(): MessagePartMessage {+ const { messageId, isSubmitting, isLatestMessage, nextType } = useMessageContext();+ return { messageId, isSubmitting, isLatestMessage, nextType };+}++function useAppUserTextPreferences(): MessagePartsUserTextPreferences {+ const usernameDisplay = useRecoilValue<boolean>(store.UsernameDisplay);+ const enableUserMsgMarkdown = useRecoilValue<boolean>(store.enableUserMsgMarkdown);+ const collapseLongUserMessages = useRecoilValue<boolean>(store.collapseLongUserMessages);+ return useMemo(+ () => ({ usernameDisplay, enableUserMsgMarkdown, collapseLongUserMessages }),+ [usernameDisplay, enableUserMsgMarkdown, collapseLongUserMessages],+ );+}++function useAppArtifactPanel(artifactId: string): MessagePartArtifactPanel {+ const setVisible = useSetRecoilState(store.artifactsVisibility);+ const setArtifacts = useSetRecoilState(store.artifactsState);+ const setCurrentArtifactId = useSetRecoilState(store.currentArtifactId);+ const resetCurrentArtifactId = useResetRecoilState(store.currentArtifactId);+ const currentArtifactId = useRecoilValue(store.currentArtifactId);+ const registered = useRecoilValue(store.artifactByIdSelector(artifactId));+ const register = useCallback(+ (artifact: Artifact) => setArtifacts((prev) => ({ ...(prev ?? {}), [artifact.id]: artifact })),+ [setArtifacts],+ );+ const open = useCallback(+ (id: string) => {+ setCurrentArtifactId(id);+ setVisible(true);+ },+ [setCurrentArtifactId, setVisible],+ );+ const close = useCallback(() => {+ resetCurrentArtifactId();+ setVisible(false);+ }, [resetCurrentArtifactId, setVisible]);+ /* A snapshot read, so the card does not subscribe to other files' or messages' flags. */+ const consumeJustResolved = useRecoilCallback(+ ({ snapshot, reset }) =>+ (messageId: string, fileId: string) => {+ const signal = store.previewJustResolved([messageId, fileId]);+ const flagged = snapshot.getLoadable(signal).valueMaybe() ?? false;+ if (flagged) {+ reset(signal);+ }+ return flagged;+ },+ [],+ );+ return { currentArtifactId, registered, register, open, close, consumeJustResolved };+}++function useAppLiveAppliedSteer(steerId: string): [boolean, (steerId: string) => void] {+ const isLiveApplied = useAtomValue(liveAppliedSteerFamily(steerId));+ const setLiveAppliedIds = useSetAtom(liveAppliedSteerIdsAtom);+ const consume = useCallback(+ (id: string) =>+ setLiveAppliedIds((prev) => (prev.includes(id) ? prev.filter((item) => item !== id) : prev)),+ [setLiveAppliedIds],+ );+ return [isLiveApplied, consume];+}++/** The host the app's own views supply: the Recoil and Jotai stores and the app providers. */+export const appMessagePartsHost: MessagePartsHost = {+ useMessage: useAppMessage,+ useFontSize: () => useAtomValue(fontSizeAtom),+ useShowThinking: () => useAtomValue(showThinkingAtom),+ useUserTextPreferences: useAppUserTextPreferences,+ /* The atom rather than the auth context: AuthContextProvider mirrors the user into it, and the+ * public share route mounts outside that provider. */+ useUser: () => useRecoilValue(store.user),+ useFileMap: () => useFileMapContext(),+ useToast: () => useToastContext().showToast,+ useSandboxStarting: (toolCallId) => useAtomValue(sandboxStartingByToolCallId(toolCallId)),+ usePtcTrace: (messageId, toolCallId) =>+ useRecoilValue(+ ptcTraceByToolCallId(toolCallId && messageId ? ptcTraceKey(messageId, toolCallId) : ''),+ ),+ useToolArtifactClaim: (artifactId) => useRecoilState(store.toolArtifactClaim(artifactId)),+ useArtifactPanel: useAppArtifactPanel,+ usePendingSteers: (conversationId) =>+ useRecoilValue(store.pendingSteersByConvoId(conversationId)),+ useSteerEscalating: (conversationId) => useAtomValue(escalatingSteerFamily(conversationId)),+ usePaneConversationId: (index) => useRecoilValue(store.conversationIdByIndex(index)),+ useLiveAppliedSteer: useAppLiveAppliedSteer,+};++const MessagePartsHostContext = createContext<MessagePartsHost>(appMessagePartsHost);++/** Supplies the host the message parts read from. Without one, parts read the app's stores. */+export function MessagePartsHostProvider({+ host,+ children,+}: {+ host: MessagePartsHost;+ children: ReactNode;+}) {+ return (+ <MessagePartsHostContext.Provider value={host}>{children}</MessagePartsHostContext.Provider>+ );+}++export const useMessagePartsHost = () => useContext(MessagePartsHostContext);diff --git a/e2e/specs/mock/scenarios/message-parts-host.spec.ts b/e2e/specs/mock/scenarios/message-parts-host.spec.tsnew file mode 100644index 0000000000..6cab256366--- /dev/null+++ b/e2e/specs/mock/scenarios/message-parts-host.spec.ts@@ -0,0 +1,212 @@+import { expect, test } from '@playwright/test';+import type { Page, Route } from '@playwright/test';+import {+ sendMessageAndWaitForCompletion,+ selectMockEndpoint,+ getAccessToken,+ messagesView,+ thinkPrompt,+ thinkText,+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+} from '../helpers';++/**+ * Message parts read app state through the host the chat view supplies, and fall back to the+ * same app state where no host is mounted (the public share view). Each scenario drives a part+ * whose reads moved onto the host and checks what the user sees.+ */++const NO_PARENT = '00000000-0000-0000-0000-000000000000';+const unique = (prefix: string) => `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;+const escapeRe = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');++async function setPreference(page: Page, key: string, value: boolean) {+ await page.evaluate(([k, v]) => localStorage.setItem(k, JSON.stringify(v)), [+ key,+ value,+ ] as const);+ await page.reload();+}++async function startChat(page: Page, text: string): Promise<string> {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, text);+ await expect(page).toHaveURL(/\/c\/(?!new)[0-9a-fA-F-]{36}$/);+ return new URL(page.url()).pathname.split('/').pop() ?? '';+}++const thoughtsButton = (page: Page) =>+ messagesView(page)+ .getByRole('button', { name: /Thoughts/ })+ .first();++test.describe('message parts host', () => {+ test.afterEach(async ({ page }) => {+ await page.unrouteAll();+ });++ test('chat reasoning opens by the show-thinking preference @scenario:chat-reasoning-follows-show-thinking', async ({+ page,+ }) => {+ test.setTimeout(60000);+ const label = unique('host-think');+ await startChat(page, thinkPrompt(label));++ await setPreference(page, 'showThinking', true);+ await expect(thoughtsButton(page)).toHaveAttribute('aria-expanded', 'true', {+ timeout: 15000,+ });+ await expect(messagesView(page).getByText(thinkText(label))).toBeVisible();++ await setPreference(page, 'showThinking', false);+ await expect(thoughtsButton(page)).toHaveAttribute('aria-expanded', 'false', {+ timeout: 15000,+ });+ });++ test('user text renders by the markdown preference @scenario:user-text-follows-markdown-preference', async ({+ page,+ }) => {+ test.setTimeout(60000);+ const word = unique('bold');+ const source = `**${word}** words`;+ await startChat(page, source);+ const view = messagesView(page);++ await setPreference(page, 'enableUserMsgMarkdown', true);+ await expect(view.locator('strong', { hasText: word })).toBeVisible({ timeout: 15000 });++ await setPreference(page, 'enableUserMsgMarkdown', false);+ await expect(view.getByText(source, { exact: true })).toBeVisible({ timeout: 15000 });+ await expect(view.locator('strong', { hasText: word })).toHaveCount(0);+ });++ test('a tool artifact row opens and closes the artifact panel @scenario:tool-artifact-row-toggles-panel', async ({+ page,+ }) => {+ test.setTimeout(60000);+ const conversationId = unique('e2e-host-artifact');+ const messageId = `${conversationId}-msg`;+ const fileId = `${conversationId}-html`;+ const toolCallId = `${conversationId}-tool`;+ const filename = 'report.html';+ const now = new Date(0).toISOString();+ const message = {+ messageId,+ conversationId,+ parentMessageId: NO_PARENT,+ isCreatedByUser: false,+ sender: 'Assistant',+ endpoint: 'Mock Provider A',+ model: 'mock-model-a',+ text: '',+ content: [+ {+ type: 'tool_call',+ tool_call: {+ id: toolCallId,+ name: 'execute_code',+ args: '{}',+ output: 'ok',+ progress: 1,+ },+ },+ ],+ attachments: [+ {+ file_id: fileId,+ filename,+ filepath: `/uploads/e2e/${fileId}__${filename}`,+ type: 'execute_code',+ source: 'local',+ bytes: 16,+ messageId,+ conversationId,+ toolCallId,+ status: 'ready',+ text: '<h1>report</h1>',+ textFormat: 'html',+ },+ ],+ createdAt: now,+ updatedAt: now,+ };+ const conversation = {+ conversationId,+ title: 'Host artifact row',+ endpoint: 'Mock Provider A',+ endpointType: 'custom',+ model: 'mock-model-a',+ createdAt: now,+ updatedAt: now,+ };+ const convoIdRe = escapeRe(conversationId);+ await page.route(new RegExp(`/api/convos/${convoIdRe}(?:\\?.*)?$`), (route: Route) =>+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(conversation),+ }),+ );+ await page.route(new RegExp(`/api/messages/${convoIdRe}(?:\\?.*)?$`), (route: Route) =>+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify([message]),+ }),+ );++ await page.goto(`/c/${conversationId}`, { timeout: 30000 });+ const row = messagesView(page).getByRole('button', {+ name: new RegExp(`^${escapeRe(filename)} HTML`),+ });+ await expect(row).toBeVisible({ timeout: 15000 });+ await expect(row).toHaveCount(1);+ await expect(row).toHaveAttribute('aria-expanded', 'false');++ await row.click();+ await expect(row).toHaveAttribute('aria-expanded', 'true');+ await expect(page.locator('#artifact-viewer')).toBeVisible();++ /* At phone width the panel is a full-screen sheet over the row, so it closes from its own+ * control; elsewhere the selected row is the close toggle. */+ const viewport = page.viewportSize();+ if (viewport != null && viewport.width < 768) {+ await page+ .locator('#artifact-viewer')+ .getByRole('button', { name: 'Close', exact: true })+ .click();+ } else {+ await row.click();+ }+ await expect(row).toHaveAttribute('aria-expanded', 'false');+ });++ test('a shared link renders parts without a host @scenario:shared-link-renders-parts-without-host', async ({+ page,+ }) => {+ test.setTimeout(90000);+ const label = unique('host-share');+ const conversationId = await startChat(page, thinkPrompt(label));+ const token = await getAccessToken(page);+ const response = await page.request.post(`/api/share/${conversationId}`, {+ headers: { Authorization: `Bearer ${token}` },+ data: {},+ });+ expect(response.ok()).toBeTruthy();+ const { shareId } = (await response.json()) as { shareId?: string };+ expect(shareId).toBeTruthy();++ await page.goto(`/share/${shareId}`, { timeout: 10000 });+ await setPreference(page, 'showThinking', true);+ const view = messagesView(page);+ await expect(view).toBeVisible({ timeout: 20000 });+ await expect(thoughtsButton(page)).toHaveAttribute('aria-expanded', 'true', {+ timeout: 15000,+ });+ await expect(view.getByText(thinkText(label))).toBeVisible();+ await expect(view.getByText(`E2E reply ${label}`)).toBeVisible();+ });+});