Skip to content

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

6.2 KB
Raw Blame
import { createContext, useContext } from 'react';
import type { Dispatch, ReactNode, SetStateAction } from 'react';
import type { Agent, TFile } from 'librechat-data-provider';
import type { TShowToast } from '@librechat/client';

/** 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;
  /** Conversation of that message, when it has one. */
  conversationId?: string | null;
  /** Position of the part in the message's content, when it renders one part. */
  partIndex?: number;
};

/** 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 = { id?: string; name?: string; username?: string } | undefined;

/** Shows a transient notification. */
export type MessagePartsToast = (toast: TShowToast) => void;

/** What a part asks the host's markdown renderer to draw. */
export type MessagePartsMarkdownProps = {
  /** The markdown source. */
  content: string;
  /** `full` for assistant text, `lite` for user-authored text rendered as markdown. */
  variant: 'full' | 'lite';
  /** Whether the text belongs to the tail of the active branch. */
  isLatestMessage: 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; `render*` members are slots that return
 * the app's own elements, for renderers too large to move (markdown) or owned elsewhere (icons).
 * 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.
 *
 * It is an interface so an app can declare the members of parts it has not handed to this
 * package yet, by augmenting `@librechat/chat/react`.
 */
export interface MessagePartsHost {
  /** The message the calling part renders in. */
  useMessage: () => MessagePartMessage;
  /** Renders markdown with the app's renderer. */
  renderMarkdown: (props: MessagePartsMarkdownProps) => ReactNode;
  /** Whether streamed text fades in word by word: the viewer's setting, unless motion is reduced. */
  useSmoothStreaming: () => boolean;
  /** An agent the viewer can see, by id. */
  useAgent: (agentId: string) => Agent | undefined;
  /** Renders an agent's avatar; `undefined` when the agent is unknown. */
  renderAgentIcon: (agent: Agent | undefined) => ReactNode;
  /** The viewer's font size utility, applied to reasoning and summary text. */
  useFontSize: () => string;
  /** Whether the viewer wants reasoning expanded by default. */
  useShowThinking: () => boolean;
  /** Whether the viewer wants tool cards and tool groups expanded by default. */
  useAutoExpandTools: () => boolean;
  /** Whether the viewer wants LaTeX in markdown rendered as math. */
  useLaTeXParsing: () => boolean;
  /** The direction chat text is typed in; `auto` resolves it from the text itself. */
  useChatDirection: () => 'auto' | 'ltr' | 'rtl';
  /** 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;
  /**
   * 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>>];
  /** 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];
}

const MessagePartsHostContext = createContext<MessagePartsHost | null>(null);

let defaultHost: MessagePartsHost | null = null;

/**
 * Registers the host that parts rendered outside any `MessagePartsHostProvider` read, the way
 * `react-i18next` registers its instance. An app registers its own once, when the module that
 * builds it loads; a provider always wins over it.
 */
export function setDefaultMessagePartsHost(host: MessagePartsHost): void {
  defaultHost = host;
}

/** Supplies the host the message parts read from. */
export function MessagePartsHostProvider({
  host,
  children,
}: {
  host: MessagePartsHost;
  children: ReactNode;
}): ReactNode {
  return (
    <MessagePartsHostContext.Provider value={host}>{children}</MessagePartsHostContext.Provider>
  );
}

/** The host of the nearest provider, or the registered default. */
export function useMessagePartsHost(): MessagePartsHost {
  const host = useContext(MessagePartsHostContext) ?? defaultHost;
  if (host == null) {
    throw new Error(
      'Message parts need a host: render them inside MessagePartsHostProvider or register one with setDefaultMessagePartsHost.',
    );
  }
  return host;
}