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

11.4 KB
Raw Blame
import { memo, useMemo, useRef, useState } from 'react';
import { hasLiveRunPause } from '@librechat/chat';
import { Clock, TextQuote, X } from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { Button, TooltipAnchor } from '@librechat/client';
import { QueryKeys, type TMessage } from 'librechat-data-provider';
import { EscalateNowButton, getMessageRowWidthClass } from '@librechat/chat/components';
import {
  useSteerCancel,
  useSteerMoveToQueue,
  useSteerRehome,
  useSteerEscalate,
  useSteerRecovery,
} from '@librechat/chat/react';
import type { SteerReceiptState } from '@librechat/chat/components';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import { useGetMessagesByConvoId } from '~/data-provider';
import { cn, isLegacyDeliveryUncertain } from '~/utils';
import { useLatestMessage } from '~/hooks/Messages';
import { useLocalize } from '~/hooks';
import SteerPart from './SteerPart';

/**
 * Steers that have not been confirmed by the server yet, rendered at the tail
 * of the streaming reply (the place the words will land) instead of in a
 * floating overlay over the composer. Confirmation swaps them for the real
 * `ContentTypes.STEER` part (`useResumableSSE` removes the pending entry), so
 * the row's whole job is to hold the position and admit it is provisional.
 */
interface PendingSteersProps {
  conversationId: string;
  /** The pane rendering this tree: its sibling selection picks the branch the
   *  pause check reads, which another pane's selection would get wrong. */
  index?: number;
  fullWidth?: boolean;
}

function PendingSteers({ conversationId, index = 0, fullWidth = false }: PendingSteersProps) {
  const localize = useLocalize();
  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 = useSteerEscalating(conversationId);
  /* Resolve the cache to the branch the user is viewing before applying the
     shared pause predicate. The cache contains every sibling branch, while
     `useLatestMessage` follows the same selection state as the message view. */
  const queryClient = useQueryClient();
  const cachedMessages =
    queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationId]) ?? [];
  const latestMessage = useLatestMessage(index, conversationId);
  const paneConversationId = usePaneConversationId(index);
  const { data: fallbackPaused } = useGetMessagesByConvoId<boolean>(conversationId, {
    select: hasLiveRunPause,
  });
  /* A one-message cache is necessarily the active branch. Until the
     conversation atom reaches useLatestMessage, retain the query's established
     single-branch result so a live question cannot re-enable escalation. The
     branch tail is keyed by the pane's conversation, which can still name the
     previous chat while this one renders from cache; until the pane owns this
     conversation, a pause on any branch keeps escalation off. */
  const resolvePaused = (): boolean => {
    if (cachedMessages.length > 1) {
      if (paneConversationId === conversationId && latestMessage != null) {
        return hasLiveRunPause(latestMessage);
      }
      return cachedMessages.some((message) => hasLiveRunPause(message));
    }
    if (fallbackPaused != null) {
      return fallbackPaused;
    }
    return cachedMessages.length === 1 && hasLiveRunPause(cachedMessages[0]);
  };
  /** Arming removes the control that was activated, so the row's Cancel button
   *  (which survives the `preempt` flip) is where keyboard focus goes next. */
  const cancelButtonRefs = useRef(new Map<string, HTMLButtonElement | null>());
  const interruptPending = useMemo(
    () => escalating || steers.some((steer) => steer.preempt === true && steer.status !== 'failed'),
    [escalating, steers],
  );

  if (steers.length === 0) {
    return null;
  }
  const paused = resolvePaused();

  const queueSteer = async (steer: (typeof steers)[number]) => {
    if (movingId != null) {
      return;
    }
    setMovingId(steer.steerId);
    try {
      const outcome = await moveToQueue(steer);
      if (outcome === 'applied') {
        showToast({ message: localize('com_ui_steer_already_applied'), status: 'info' });
      } else if (outcome === 'failed') {
        showToast({ message: localize('com_ui_steer_cancel_failed'), status: 'error' });
      }
    } finally {
      setMovingId(null);
    }
  };
  /** A definitively rejected steer can be corrected: the whole message comes
   *  back through the shared recovery boundary, so its attachments, quoted
   *  excerpts and skill picks come with it. Withheld while delivery is
   *  uncertain, like every other action that assumes the server does not hold
   *  these words. */
  const editFailedSteer = (steer: (typeof steers)[number]) => {
    if (rehomeSteer(steer, { rejectedByServer: true }) === 'queue') {
      showToast({ message: localize('com_ui_steer_moved_to_queue'), status: 'info' });
    }
  };
  const cancelPendingSteer = async (steer: (typeof steers)[number]) => {
    if (movingId != null) {
      return;
    }
    setMovingId(steer.steerId);
    try {
      const outcome = await cancelSteer(steer);
      if (outcome === 'applied') {
        showToast({ message: localize('com_ui_steer_already_applied'), status: 'info' });
      } else if (outcome === 'failed') {
        showToast({ message: localize('com_ui_steer_cancel_failed'), status: 'error' });
      }
    } finally {
      setMovingId(null);
    }
  };

  return (
    <div
      role="list"
      aria-label={localize('com_ui_steer_in_flight')}
      className={cn('mx-auto min-w-0 px-4', getMessageRowWidthClass({ fullWidth }))}
      data-testid="pending-steers"
    >
      {steers.map((steer) => {
        const deliveryUncertain = steer.deliveryUncertain === true;
        const retrySafe = !isLegacyDeliveryUncertain(steer);
        const quoteCount = steer.quotes?.length ?? 0;
        let receiptState: SteerReceiptState = 'delivered';
        if (steer.status === 'sending') {
          receiptState = 'sending';
        } else if (steer.preempt === true) {
          receiptState = 'interrupting';
        }
        return (
          <div
            key={steer.steerId}
            role="listitem"
            className={cn(steer.status !== 'failed' && 'opacity-60')}
          >
            <SteerPart
              steer={steer.text}
              files={steer.files}
              steerId={steer.steerId}
              createdAt={steer.createdAt}
              receiptState={steer.status === 'failed' ? null : receiptState}
            />
            {steer.status === 'failed' ? (
              <div className="-mt-2 mb-2 flex flex-wrap items-center justify-end gap-3 text-xs">
                {quoteCount > 0 && (
                  <span className="text-text-secondary flex items-center gap-0.5">
                    <TextQuote className="h-3.5 w-3.5" aria-hidden="true" />
                    <span aria-hidden="true">{quoteCount}</span>
                    <span className="sr-only">
                      {localize('com_ui_queued_quote_count', { 0: String(quoteCount) })}
                    </span>
                  </span>
                )}
                <span className="text-text-destructive">
                  {localize(
                    deliveryUncertain
                      ? 'com_ui_steer_delivery_uncertain'
                      : 'com_ui_steer_failed_inline',
                  )}
                </span>
                {retrySafe && (
                  <Button type="button" onClick={() => retry(steer.steerId)} variant="text-action">
                    {localize('com_ui_retry')}
                  </Button>
                )}
                {!deliveryUncertain && (
                  <Button
                    type="button"
                    onClick={() => editFailedSteer(steer)}
                    variant="text-action"
                  >
                    {localize('com_ui_edit')}
                  </Button>
                )}
                {!deliveryUncertain && (
                  <Button
                    type="button"
                    onClick={() => sendAsNew(steer.steerId)}
                    variant="text-action"
                  >
                    {localize('com_ui_send_as_new')}
                  </Button>
                )}
              </div>
            ) : (
              <div className="text-text-secondary -mt-2 mb-2 flex flex-wrap items-center justify-end gap-0.5 text-xs">
                {/* Only a `pending` steer can be armed: `sending` has no server id
                    yet, and one already interrupting has nothing left to escalate. */}
                {steer.status === 'pending' && steer.preempt !== true && (
                  <EscalateNowButton
                    surface="bubble"
                    messageText={steer.text}
                    disabled={paused === true || interruptPending}
                    onClick={() =>
                      escalate(
                        {
                          steerId: steer.steerId,
                          generationCreatedAt: steer.generationCreatedAt,
                        },
                        () => cancelButtonRefs.current.get(steer.steerId)?.focus(),
                      )
                    }
                  />
                )}
                {steer.status === 'pending' && (
                  <TooltipAnchor
                    description={localize('com_ui_convert_to_queue')}
                    render={
                      <Button
                        type="button"
                        variant="message-action"
                        aria-label={localize('com_ui_convert_to_queue')}
                        disabled={movingId != null}
                        onClick={() => void queueSteer(steer)}
                      >
                        <Clock className="h-[19px] w-[19px]" aria-hidden="true" />
                      </Button>
                    }
                  />
                )}
                {(steer.status === 'pending' || steer.status === 'sending') && (
                  <TooltipAnchor
                    description={localize('com_ui_cancel')}
                    render={
                      <Button
                        type="button"
                        variant="message-action"
                        aria-label={localize('com_ui_cancel')}
                        ref={(node) => {
                          if (node == null) {
                            cancelButtonRefs.current.delete(steer.steerId);
                            return;
                          }
                          cancelButtonRefs.current.set(steer.steerId, node);
                        }}
                        disabled={movingId != null}
                        onClick={() => void cancelPendingSteer(steer)}
                      >
                        <X className="h-[19px] w-[19px]" aria-hidden="true" />
                      </Button>
                    }
                  />
                )}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

export default memo(PendingSteers);