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.

18.2 KB
Raw Blame
'use client';

import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import type { ConversationContext, TaskDetailActivity } from '@lobechat/types';
import type { DropdownItem } from '@lobehub/ui';
import {
  ActionIcon,
  confirmModal,
  copyToClipboard,
  cssVar,
  DropdownMenu,
  Flexbox,
  FloatingPanel,
  Freeze,
  Tag,
  Text,
  toast,
} from '@lobehub/ui';
import {
  Copy,
  ExternalLink,
  Maximize2,
  Minimize2,
  MoreHorizontal,
  Share2,
  Trash,
} from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import ChatList from '@/features/Conversation/ChatList';
import { ConversationProvider } from '@/features/Conversation/ConversationProvider';
import { TaskCardScopeProvider } from '@/features/Conversation/Markdown/plugins/Task';
import MessageItem from '@/features/Conversation/Messages';
import { PortalContent } from '@/features/Portal/router';
import { useShareModal } from '@/features/ShareModal';
import { LazySharePopover as SharePopover } from '@/features/SharePopover/lazy';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { useServerConfigStore } from '@/store/serverConfig';
import { serverConfigSelectors } from '@/store/serverConfig/selectors';
import { useTaskStore } from '@/store/task';
import { taskActivitySelectors, taskDetailSelectors } from '@/store/task/selectors';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
import { electronStylish } from '@/styles/electron';
import { isForbiddenError } from '@/utils/forbiddenError';
import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';

import AssigneeAvatar from '../../features/AssigneeAvatar';
import { useTopicDrawerArtifactPortal } from '../../hooks/useTopicDrawerArtifactPortal';
import TaskAcceptanceWaitNotice from '../TaskAcceptanceWaitNotice';
import FeedbackInput from './FeedbackInput';

const SHARE_ICON_SIZE = { blockSize: 32, size: 16 } as const;
const DEFAULT_PANEL_HEIGHT = 'min(640px, calc(100dvh - 16px))';
const DEFAULT_PANEL_WIDTH = 640;
const EXPANDED_PANEL_HEIGHT = 'calc(100dvh - 16px)';
const EXPANDED_PANEL_WIDTH = 'min(960px, calc(100vw - 16px))';

/** Identifies the conversation and optional Task activity hosted by a run drawer. */
export interface TopicChatDrawerBodyProps {
  /** The assignee that owns this Topic's messages and runtime. */
  agentId: string;
  /** Whether the follow-up composer starts expanded. @default false */
  defaultInputExpanded?: boolean;
  /** Whether to hide the collapse action once the composer is expanded. @default false */
  disableInputCollapse?: boolean;
  /** Expand and focus the reply composer whenever this changes — bumped when the
      drawer is opened with conversational intent (e.g. the brief's "Continue
      chat"). */
  inputFocusRequest?: number;
  /**
   * The run to resume streaming from. Hosts that embed the body outside the
   * drawer pass it themselves; the drawer falls back to its own topic's run.
   */
  runningOperation?: TaskDetailActivity['runningOperation'];
  /** The explicit Topic to render, independent of the active chat route. */
  topicId: string;
}

/**
 * Renders a Task run conversation with its follow-up composer.
 *
 * Use when:
 * - Hosting the floating Task drawer or an embedded run conversation.
 *
 * Expects:
 * - An explicit Topic and assignee; optional activity belongs to that same Topic.
 *
 * Returns:
 * - The isolated conversation surface, reconnecting to its active gateway operation.
 */
export const TopicChatDrawerBody = memo<TopicChatDrawerBodyProps>(
  ({
    agentId,
    defaultInputExpanded,
    disableInputCollapse,
    inputFocusRequest,
    runningOperation,
    topicId,
  }) => {
    const isLogin = useUserStore(authSelectors.isLogin);
    const useHydrateAgentConfig = useAgentStore((s) => s.useHydrateAgentConfig);

    useHydrateAgentConfig(isLogin, agentId);

    const context = useMemo<ConversationContext>(
      () => ({
        agentId,
        isolatedTopic: true,
        scope: 'main',
        topicId,
      }),
      [agentId, topicId],
    );

    const operationState = useOperationState(context);

    const drawerActivity = useTaskStore((s) => {
      const activity = taskActivitySelectors.activeDrawerTopicActivity(s);
      return activity?.id === topicId ? activity : undefined;
    });
    const currentRunningOperation = runningOperation ?? drawerActivity?.runningOperation;
    // Pass this drawer's agent explicitly — the run drawer also mounts on the
    // home surface, where the chat store's `activeAgentId` is unset.
    useGatewayReconnect(topicId, currentRunningOperation, agentId);

    const itemContent = useCallback(
      (index: number, id: string) => <MessageItem disableEditing id={id} index={index} key={id} />,
      [],
    );

    return (
      <ConversationProvider context={context} operationState={operationState}>
        <TaskCardScopeProvider value={true}>
          <Flexbox height={'100%'} style={{ overflow: 'hidden' }}>
            <Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>
              <ChatList disableActionsBar itemContent={itemContent} />
            </Flexbox>
            <Flexbox gap={8} paddingBlock={'0 12px'} paddingInline={12} style={{ flexShrink: 0 }}>
              {/* A run whose agent stopped but whose acceptance round has not
                  settled still reads as running; say what it waits on. */}
              <TaskAcceptanceWaitNotice
                activity={drawerActivity}
                runningOperation={currentRunningOperation}
              />
              <FeedbackInput
                defaultExpanded={defaultInputExpanded}
                disableCollapse={disableInputCollapse}
                focusRequest={inputFocusRequest}
              />
            </Flexbox>
          </Flexbox>
        </TaskCardScopeProvider>
      </ConversationProvider>
    );
  },
);

TopicChatDrawerBody.displayName = 'TopicChatDrawerBody';

/** Configures how the floating run drawer presents itself on its host surface. */
export interface TopicChatDrawerProps {
  /** Whether each opening starts in the expanded reading size. @default false */
  defaultExpanded?: boolean;
}

const TopicChatDrawer = memo<TopicChatDrawerProps>(({ defaultExpanded = false }) => {
  const { t } = useTranslation(['chat', 'common', 'verify']);
  const navigate = useWorkspaceAwareNavigate();
  const [expanded, setExpanded] = useState(defaultExpanded);
  const topicId = useTaskStore(taskDetailSelectors.activeTopicDrawerTopicId);
  const activeTaskId = useTaskStore((s) => s.activeTaskId);
  const agentId = useTaskStore(taskDetailSelectors.topicDrawerAgentId);
  const drawerTitle = useTaskStore(taskDetailSelectors.topicDrawerTitle);
  const fallbackRunningOperation = useTaskStore((s) => s.activeTopicDrawerRunningOperation);
  const inputFocusRequest = useTaskStore(taskDetailSelectors.topicDrawerFocusRequest);
  const activity = useTaskStore(taskActivitySelectors.activeDrawerTopicActivity);
  const closeTopicDrawer = useTaskStore((s) => s.closeTopicDrawer);
  const deleteTopic = useTaskStore((s) => s.deleteTopic);
  const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);
  const showArtifactPortal = useTopicDrawerArtifactPortal();
  const closeArtifact = useChatStore((s) => s.closeArtifact);
  const closeFilePreview = useChatStore((s) => s.closeFilePreview);
  const isFilePreview = useChatStore(chatPortalSelectors.showFilePreview);
  // The drawer hosts either an artifact or a file preview opened from its run.
  const closeHostedPortal = isFilePreview ? closeFilePreview : closeArtifact;

  // The portal state is global: an artifact or preview left open when this
  // drawer closes would make the next opening of the same topic land on it
  // instead of the conversation, so the drawer takes it down with it.
  const handleClose = useCallback(() => {
    if (showArtifactPortal) closeHostedPortal();
    closeTopicDrawer();
  }, [closeHostedPortal, closeTopicDrawer, showArtifactPortal]);

  // A request to write ("Continue chat") needs the conversation and its
  // composer. Each request is handled once, so an artifact the user opens
  // afterwards from inside the conversation is left alone.
  const handledFocusRequestRef = useRef(inputFocusRequest);
  useEffect(() => {
    if (!inputFocusRequest || inputFocusRequest === handledFocusRequestRef.current) return;
    handledFocusRequestRef.current = inputFocusRequest;
    if (showArtifactPortal) closeHostedPortal();
  }, [closeHostedPortal, inputFocusRequest, showArtifactPortal]);
  const enableTopicLinkShare = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
  const { allowed: canShare, reason } = usePermission('edit_own_content');
  const { allowed: canEditTask } = usePermission('create_content');
  const appOrigin = useAppOrigin();
  const activeWorkspaceSlug = useActiveWorkspaceSlug();

  // Hydrate task detail when the drawer is opened outside of TaskDetailPage
  // (e.g. from a brief on home) so the header has agentId / status / seq.
  useFetchTaskDetail(topicId ? activeTaskId : undefined);

  const open = !!topicId && !!agentId;

  // Each opening starts from the host's default size; a toggle only lasts for
  // the run the user is looking at.
  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) setExpanded(defaultExpanded);
  }

  const shareContext = useMemo<Partial<ConversationContext>>(
    () => ({ agentId: agentId ?? undefined, topicId: topicId ?? undefined }),
    [agentId, topicId],
  );
  const { openShareModal } = useShareModal({ context: shareContext });

  // Without an origin the URL is relative — the system browser has nothing to
  // resolve it against.
  const topicPageUrl =
    appOrigin && agentId && topicId
      ? `${appOrigin}${buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(agentId, topicId), activeWorkspaceSlug)}`
      : undefined;

  const handleCopyTopicId = useCallback(() => {
    if (topicId) void copyToClipboard(topicId);
  }, [topicId]);

  const handleCopyOperationId = useCallback(() => {
    if (activity?.operationId) void copyToClipboard(activity.operationId);
  }, [activity?.operationId]);

  const handleOpenAgentTopic = useCallback(() => {
    if (!agentId || !topicId) return;
    closeTopicDrawer();
    navigate(AGENT_CHAT_TOPIC_URL(agentId, topicId));
  }, [agentId, closeTopicDrawer, navigate, topicId]);

  // The drawer stays open until `deleteTopic` actually succeeds: closing
  // first would drop the user back onto whatever was behind the panel with
  // no feedback if the mutation then fails (permission, network, or a topic
  // that's already gone). Only a confirmed delete tears the panel down.
  const handleDelete = useCallback(() => {
    if (!topicId) return;
    const targetTopicId = topicId;
    confirmModal({
      cancelText: t('cancel', { ns: 'common' }),
      content: t('taskDetail.topicMenu.deleteConfirm.content', {
        defaultValue:
          'This run and its messages will be permanently deleted. This action cannot be undone.',
      }),
      okButtonProps: { danger: true },
      okText: t('taskDetail.topicMenu.delete', { defaultValue: 'Delete Run' }),
      onOk: async () => {
        try {
          await deleteTopic(targetTopicId);
          closeTopicDrawer();
        } catch (error) {
          toast.error(
            isForbiddenError(error)
              ? t('manageOnlyCreator', { ns: 'common' })
              : t('operationFailed', { ns: 'common' }),
          );
        }
      },
      title: t('taskDetail.topicMenu.deleteConfirm.title', { defaultValue: 'Delete Run?' }),
    });
  }, [closeTopicDrawer, deleteTopic, t, topicId]);

  const menuItems = useMemo<DropdownItem[]>(
    () => [
      {
        disabled: !agentId || !topicId,
        icon: ExternalLink,
        key: 'openAgentTopic',
        label: t('taskDetail.topicMenu.openAgentTopic'),
        onClick: handleOpenAgentTopic,
      },
      { type: 'divider' },
      {
        disabled: !topicId,
        icon: Copy,
        key: 'copyTopicId',
        label: t('taskDetail.topicMenu.copyId', { defaultValue: 'Copy Topic ID' }),
        onClick: handleCopyTopicId,
      },
      {
        disabled: !activity?.operationId,
        icon: Copy,
        key: 'copyOperationId',
        label: t('taskDetail.topicMenu.copyOperationId', { defaultValue: 'Copy Operation ID' }),
        onClick: handleCopyOperationId,
      },
      { type: 'divider' },
      {
        danger: true,
        // Mirrors the run row's menu: a running topic already has an explicit
        // Stop affordance, so delete here stays scoped to finished runs, and
        // is also gated on edit permission like the server's `task.deleteTopic`.
        // `activity` can be briefly (or, for a topic without a parent task,
        // permanently) unresolved while the task detail hydrates — an unknown
        // status is treated as ineligible (same as running) rather than
        // defaulting to enabled.
        disabled: !topicId || !canEditTask || !activity?.status || activity.status === 'running',
        icon: Trash,
        key: 'delete',
        label: t('taskDetail.topicMenu.delete', { defaultValue: 'Delete Run' }),
        onClick: handleDelete,
      },
    ],
    [
      activity?.operationId,
      activity?.status,
      agentId,
      canEditTask,
      handleCopyOperationId,
      handleCopyTopicId,
      handleDelete,
      handleOpenAgentTopic,
      t,
      topicId,
    ],
  );

  const title = (
    <Flexbox
      horizontal
      align={'center'}
      className={electronStylish.nodrag}
      flex={1}
      gap={8}
      style={{ maxWidth: '100%', minWidth: 0, overflow: 'hidden' }}
    >
      <AssigneeAvatar agentId={agentId} size={20} />
      {activity?.sourceTaskIdentifier && (
        <Tag
          size={'small'}
          style={{ flex: 'none' }}
          title={t('taskDetail.topicSource', {
            identifier: activity.sourceTaskIdentifier,
          })}
        >
          {activity.sourceTaskIdentifier}
        </Tag>
      )}
      <Text ellipsis style={{ flex: '0 1 auto', minWidth: 0 }} weight={500}>
        {activity?.title || drawerTitle || t('taskDetail.topicDrawer.untitled')}
      </Text>
      {activity?.seq != null && (
        <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>
          #{activity.seq}
        </Text>
      )}
      <DropdownMenu items={menuItems}>
        <ActionIcon icon={MoreHorizontal} size={'small'} />
      </DropdownMenu>
    </Flexbox>
  );

  const shareIcon = (
    <ActionIcon
      disabled={!canShare}
      icon={Share2}
      size={SHARE_ICON_SIZE}
      title={canShare ? t('share', { ns: 'common' }) : reason}
      onClick={enableTopicLinkShare || !canShare ? undefined : openShareModal}
    />
  );

  const actions = !topicId ? null : (
    <Flexbox horizontal align={'center'} className={electronStylish.nodrag} gap={4}>
      <ActionIcon
        icon={expanded ? Minimize2 : Maximize2}
        size={SHARE_ICON_SIZE}
        title={t(expanded ? 'taskDetail.topicDrawer.collapse' : 'taskDetail.topicDrawer.expand')}
        onClick={() => setExpanded((value) => !value)}
      />
      {enableTopicLinkShare && canShare ? (
        <SharePopover agentId={agentId ?? undefined} topicId={topicId} onOpenModal={openShareModal}>
          {shareIcon}
        </SharePopover>
      ) : (
        shareIcon
      )}
      <ActionIcon
        disabled={!topicPageUrl}
        icon={ExternalLink}
        size={SHARE_ICON_SIZE}
        title={t('report.actions.openInBrowser', { ns: 'verify' })}
        onClick={() => {
          if (!topicPageUrl) return;
          openTrustedExternalUrl(topicPageUrl);
        }}
      />
    </Flexbox>
  );

  // Freeze title/actions/body during the close animation so the panel keeps
  // its last rendered state instead of flashing to the empty/"untitled" view
  // while topicId/agentId clear.
  return (
    <FloatingPanel
      actions={<Freeze frozen={!open}>{actions}</Freeze>}
      getContainer={false}
      height={expanded ? EXPANDED_PANEL_HEIGHT : DEFAULT_PANEL_HEIGHT}
      mask={false}
      minHeight={320}
      minWidth={360}
      open={open}
      placement={'bottomRight'}
      title={<Freeze frozen={!open}>{title}</Freeze>}
      width={expanded ? EXPANDED_PANEL_WIDTH : DEFAULT_PANEL_WIDTH}
      styles={{
        body: { padding: 0 },
        panel: {
          background: cssVar.colorBgContainer,
          // Leave room for whatever the panel reserves when it yields the
          // bottom edge to a toast; the library's own cap assumes a 16px
          // offset and this panel sits at 8.
          maxHeight: 'calc(100dvh - 16px - var(--floating-panel-reserve-block-end, 0px))',
        },
        title: {
          boxSizing: 'border-box',
          maxWidth: '100%',
          minWidth: 0,
          overflow: 'hidden',
        },
      }}
      onClose={handleClose}
    >
      {/* `open` already proves both ids. The body deliberately does NOT wait for a
          task: a run opened from the home inbox may have no parent task at all,
          and gating on one renders a titled but empty panel. */}
      <Freeze frozen={!open}>
        {open &&
          (showArtifactPortal ? (
            <Flexbox height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>
              <PortalContent onClose={closeHostedPortal} />
            </Flexbox>
          ) : (
            <TopicChatDrawerBody
              agentId={agentId!}
              inputFocusRequest={inputFocusRequest}
              runningOperation={activity?.runningOperation ?? fallbackRunningOperation}
              topicId={topicId!}
            />
          ))}
      </Freeze>
    </FloatingPanel>
  );
});

TopicChatDrawer.displayName = 'TopicChatDrawer';

export default TopicChatDrawer;