Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

9.3 KB
Raw Blame
'use client';

import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';
import { memo, Suspense, useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { useBusinessConversationAnalytics } from '@/business/client/hooks/useBusinessConversationAnalytics';
import { RenderProfiler } from '@/components/RenderProfiler';
import AgentHome from '@/features/AgentHome';
import { useSlugRouteSendGuard } from '@/features/AgentRoute/useSlugRouteSendGuard';
import {
  TopicMigrationPlaceholder,
  useTopicMigrationPending,
} from '@/features/AgentTransferMigration';
import ChatMiniMap from '@/features/ChatMiniMap';
import { ChatList, ConversationProvider } from '@/features/Conversation';
import { useMessageDeepLink } from '@/features/Conversation/ChatList/hooks/useMessageDeepLink';
import ComposerDraftReceiver from '@/features/Conversation/ComposerDraftReceiver';
import { useChatFollowUp } from '@/features/Conversation/hooks/useChatFollowUp';
import { useTopicDetailSendGuard } from '@/features/Conversation/hooks/useTopicDetailSendGuard';
import {
  ForwardMessageDispatcher,
  MessageForwardFooter,
} from '@/features/Conversation/MessageForward';
import SplitDropZone from '@/features/Conversation/SplitDropZone';
import { useAgentContext } from '@/features/Conversation/useAgentContext';
import { mergeConversationHooks } from '@/features/Conversation/utils/mergeConversationHooks';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
import { useScheduledRunWatch } from '@/hooks/useScheduledRunWatch';
import { useTopicRunEvents } from '@/hooks/useTopicRunEvents';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { threadSelectors, topicSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';

import ExposeMainEditor from './ExposeMainEditor';
import HeterogeneousChatInput from './HeterogeneousChatInput';
import LocateMessageFromUrl from './LocateMessageFromUrl';
import MainChatInput from './MainChatInput';
import MessageFromUrl from './MainChatInput/MessageFromUrl';
import ThreadHydration from './ThreadHydration';
import { useActionsBarConfig } from './useActionsBarConfig';

const styles = createStaticStyles(({ css }) => ({
  // When the chat column is wide enough for the header to float above the
  // full-bleed list (see Conversation/Header), this in-list spacer keeps the
  // first message clear of it while still letting content scroll underneath.
  // A list row is used instead of scroller padding, which breaks virtua's
  // offset math. Height matches the 44px NavHeader.
  floatingHeaderSpacer: css`
    height: 0;

    @container agent-chat-layout (min-width: 1200px) {
      height: 44px;
    }
  `,
}));

/**
 * ConversationArea
 *
 * Main conversation area component using the new ConversationStore architecture.
 * Uses ChatList from @/features/Conversation and MainChatInput for custom features.
 */
const Conversation = memo(() => {
  const { t } = useTranslation('chat');
  const context = useAgentContext();
  const messageDeepLink = useMessageDeepLink();

  // Get raw dbMessages from ChatStore for this context
  // ConversationStore will parse them internally to generate displayMessages
  const chatKey = messageMapKey(context);

  // Get operation state from ChatStore for reactive updates
  const operationState = useOperationState(context);

  // Get actionsBar config with branching support from ChatStore
  const actionsBarConfig = useActionsBarConfig();

  // Heterogeneous agents (Claude Code, etc.) use a simplified input β€” their
  // toolchain/memory/model are managed by the external runtime, so LobeHub's
  // model/tools/memory/KB/MCP/runtime-mode pickers don't apply.
  const isHeterogeneousAgent = useAgentStore(
    agentByIdSelectors.isAgentHeterogeneousById(context.agentId),
  );

  // Subagent threads (spawned by an external agent's subagent tool call) are
  // read-only β€” the parent agent drives their execution, so hide the input.
  const isSubagentThread = useChatStore(threadSelectors.isActiveThreadSubagent);

  // Auto-reconnect to running Gateway operation on topic load
  const runningOperation = useChatStore((s) =>
    context.topicId
      ? topicSelectors.getTopicById(context.topicId)(s)?.metadata?.runningOperation
      : undefined,
  );
  useGatewayReconnect(context.topicId, runningOperation, context.agentId);
  // A run started on another device pushes here, so it streams without a refetch.
  useTopicRunEvents(context.topicId, context.agentId);

  // While the topic is parked as `scheduled`, pull the cron dispatch into the
  // store when `runAt` passes β€” nothing pushes it, and the reconnect above
  // can't fire until the synced `runningOperation` lands in the topic map.
  useScheduledRunWatch(context.topicId);

  const agentChatConfig = useAgentStore(chatConfigByIdSelectors.getChatConfigById(context.agentId));
  const chatFollowUpHooks = useChatFollowUp({
    agentChatConfig,
    conversationKey: chatKey,
    threadId: context.threadId ?? undefined,
    topicId: context.topicId ?? undefined,
  });
  const businessAnalyticsHooks = useBusinessConversationAnalytics(context);
  // First in the chain: a send on an unconfirmed `/agent/<slug>` must not reach
  // the agent painted from the local copy before the server confirms it.
  const slugRouteSendGuard = useSlugRouteSendGuard();
  // A run reads the topic's pinned model and routing from the store, so a send
  // into a topic the store has not loaded yet waits for its detail.
  const topicDetailSendGuard = useTopicDetailSendGuard(context.topicId);

  // A topic still awaiting its transfer backfill shows a placeholder instead
  // of an empty (not-yet-migrated) history, and blocks sending β€” the server
  // could not assemble the missing context anyway. Opening it jumps it to the
  // front of the backfill queue, so the wait is typically a few seconds.
  const { job: migrationJob, topicPending } = useTopicMigrationPending(
    { agentId: context.agentId },
    context.topicId,
  );

  const hooks = useMemo(
    () =>
      mergeConversationHooks(
        slugRouteSendGuard,
        topicDetailSendGuard,
        businessAnalyticsHooks,
        chatFollowUpHooks,
      ),
    [slugRouteSendGuard, topicDetailSendGuard, businessAnalyticsHooks, chatFollowUpHooks],
  );

  return (
    <ConversationProvider
      actionsBar={actionsBarConfig}
      context={context}
      hooks={hooks}
      operationState={operationState}
    >
      <SplitDropZone>
        <Flexbox
          flex={1}
          width={'100%'}
          style={{
            overflowX: 'hidden',
            overflowY: 'auto',
            position: 'relative',
          }}
        >
          {topicPending ? (
            <TopicMigrationPlaceholder agentId={context.agentId} topicId={context.topicId} />
          ) : (
            <RenderProfiler region={'messages'}>
              <ChatList
                printable
                headerSlot={<div aria-hidden className={styles.floatingHeaderSpacer} />}
                messageDeepLink={messageDeepLink}
                welcome={<AgentHome />}
                footerSlot={
                  isSubagentThread ? (
                    <Flexbox
                      horizontal
                      align={'center'}
                      justify={'center'}
                      paddingBlock={6}
                      paddingInline={16}
                    >
                      <span
                        style={{
                          color: cssVar.colorTextDescription,
                          fontSize: 12,
                          textAlign: 'center',
                        }}
                      >
                        {t('thread.subagentReadOnlyHint')}
                      </span>
                    </Flexbox>
                  ) : undefined
                }
              />
            </RenderProfiler>
          )}
        </Flexbox>
      </SplitDropZone>
      {!isSubagentThread && !topicPending && (
        <MessageForwardFooter>
          {isHeterogeneousAgent ? <HeterogeneousChatInput /> : <MainChatInput />}
        </MessageForwardFooter>
      )}
      {topicPending && (
        <Flexbox horizontal align={'center'} justify={'center'} paddingBlock={6} paddingInline={16}>
          <span style={{ color: cssVar.colorTextDescription, fontSize: 12, textAlign: 'center' }}>
            {t(
              migrationJob?.type === 'copy'
                ? 'transferMigration.inputDisabledHintCopy'
                : 'transferMigration.inputDisabledHint',
            )}
          </span>
        </Flexbox>
      )}
      <ExposeMainEditor />
      <ComposerDraftReceiver />
      <ThreadHydration />
      <ChatMiniMap />
      <ForwardMessageDispatcher />
      <LocateMessageFromUrl />
      {/* Held back while the topic is still migrating: the composer above is
          already disabled, and letting `?message=` through would send into the
          not-yet-migrated history this screen is waiting for. The param stays
          in the URL, so the send fires once the backfill lands. */}
      {!topicPending && (
        <Suspense>
          <MessageFromUrl />
        </Suspense>
      )}
    </ConversationProvider>
  );
});

Conversation.displayName = 'ConversationArea';

export default Conversation;