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.

14.4 KB
Raw Blame
import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import type { ChatTopicStatus } from '@lobechat/types';
import { type DropdownItem } from '@lobehub/ui';
import { copyToClipboard, Icon, toast } from '@lobehub/ui';
import { useLatest, useUnmountedRef } from 'ahooks';
import {
  Archive,
  ArchiveRestore,
  ExternalLink,
  FolderInput,
  Forward,
  Hash,
  Link2,
  LucideCopy,
  MessageSquareText,
  PanelRight,
  PanelTop,
  PencilLine,
  Pin,
  PinOff,
  Share,
  Stethoscope,
  Trash,
  Wand2,
} from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { useTopicBugReportMenuItem } from '@/business/client/hooks/useTopicBugReportMenuItem';
import { openRenameModal } from '@/components/RenameModal';
import { isDesktop } from '@/const/version';
import { createMoveTopicsModal } from '@/features/AgentTopicManager/MoveTopicsModal';
import { createTopicForwardModal } from '@/features/Conversation/MessageForward/TopicForwardModal';
import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
import { useFavoriteMenuItem } from '@/features/Favorites';
import { usePrivateAgentLinkNotice } from '@/features/PrivateAgentLinkNotice';
import { getProjectTopicPath } from '@/features/Projects/Layout/navigation';
import { openShareModal } from '@/features/ShareModal';
import { openTopicDoctorModal } from '@/features/TopicDoctorModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useActiveLocation } from '@/hooks/useActiveLocation';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { usePermission } from '@/hooks/usePermission';
import { topicService } from '@/services/topic';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
import { isForbiddenError } from '@/utils/forbiddenError';

import { useScopedTopic, useScopedTopics } from '../../useScopedTopics';
import { buildTopicPrompt } from './buildTopicPrompt';

export interface TopicItemDropdownMenuProps {
  completionLabel?: string;
  fav?: boolean;
  id?: string;
  status?: ChatTopicStatus | null;
  title: string;
}

export const useTopicItemDropdownMenu = ({
  completionLabel,
  fav,
  id,
  status,
  title,
}: TopicItemDropdownMenuProps) => {
  const { t } = useTranslation(['topic', 'common', 'chat']);

  const navigate = useWorkspaceAwareNavigate();
  const activeWorkspaceId = useActiveWorkspaceId();
  const { pathname } = useActiveLocation();
  const routeTopicId = pathname.match(/\/project\/[^/]+\/topic\/([^/]+)\/?$/)?.[1];
  // Read after awaits: the user may open another topic, or leave the project
  // (unmounting this sidebar), while an archive is in flight.
  const routeTopicIdRef = useLatest(routeTopicId);
  const unmountedRef = useUnmountedRef();
  const activeWorkspaceSlug = useActiveWorkspaceSlug();
  const notifyPrivateAgentLink = usePrivateAgentLinkNotice();
  const { allowed: canCreateTopic } = usePermission('create_content');
  const { allowed: canEditTopic } = usePermission('edit_own_content');

  const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
  const openTopicInPortal = useChatStore((s) => s.openTopicInPortal);
  const scopedTopic = useScopedTopic(id);
  const { scope, refresh } = useScopedTopics();
  const fallbackAgentId = useAgentStore((s) => s.activeAgentId);
  const activeAgentId = scopedTopic?.agentId ?? fallbackAgentId;
  // Project rows carry their agent's provider type, since a cold project visit
  // never loads each row agent's config into the store.
  const isHeterogeneous = useAgentStore(
    (s) =>
      !!scopedTopic?.agentHeterogeneousProviderType ||
      (!!activeAgentId &&
        !!agentSelectors.getAgentConfigById(activeAgentId)(s)?.agencyConfig?.heterogeneousProvider),
  );
  const addTab = useElectronStore((s) => s.addTab);
  const appOrigin = useAppOrigin();
  const enableTopicBugReport = useUserStore(labPreferSelectors.enableTopicBugReport);
  const bugReportItem = useTopicBugReportMenuItem({ agentId: activeAgentId, topicId: id });
  // Pin (`fav`) orders the topic list; a favorite adds the topic to the home
  // sidebar's Favorites section. A topic still titled `...` is being named, so
  // it waits for its real title before it can be added.
  const favoriteMenuItem = useFavoriteMenuItem(
    id && activeAgentId
      ? {
          path: AGENT_CHAT_TOPIC_URL(activeAgentId, id),
          snapshotReady: !!title && title !== '...',
          targetId: id,
          title,
          type: 'topic',
        }
      : undefined,
    { showHotkey: false },
  );

  const [
    autoRenameTopicTitle,
    duplicateTopic,
    removeTopic,
    favoriteTopic,
    markTopicCompleted,
    unmarkTopicCompleted,
    updateTopicTitle,
  ] = useChatStore((s) => [
    s.autoRenameTopicTitle,
    s.duplicateTopic,
    s.removeTopic,
    s.favoriteTopic,
    s.markTopicCompleted,
    s.unmarkTopicCompleted,
    s.updateTopicTitle,
  ]);

  const isCompleted = status === 'completed';
  const toggleCompleted = useCallback(async () => {
    if (!id) return;
    if (isCompleted) await unmarkTopicCompleted(id);
    else await markTopicCompleted(id);
    if (scope) {
      if (!isCompleted && !unmountedRef.current && routeTopicIdRef.current === id)
        navigate(`/project/${scope.projectId}`);
      await refresh();
    }
  }, [
    id,
    isCompleted,
    markTopicCompleted,
    unmarkTopicCompleted,
    scope,
    routeTopicIdRef,
    unmountedRef,
    navigate,
    refresh,
  ]);

  const handleOpenShareModal = useCallback(() => {
    if (!id) return;

    void openShareModal({ context: { threadId: null, topicId: id } });
  }, [id]);

  const dropdownMenu = useCallback(() => {
    if (!id) return [];

    return [
      {
        disabled: !canEditTopic,
        icon: <Icon icon={isCompleted ? ArchiveRestore : Archive} />,
        key: 'markCompleted',
        label:
          completionLabel ??
          (isCompleted ? t('actions.unmarkCompleted') : t('actions.markCompleted')),
        onClick: toggleCompleted,
        sfSymbol: isCompleted ? 'tray.and.arrow.up' : 'archivebox',
      },
      {
        disabled: !canEditTopic,
        icon: <Icon icon={fav ? PinOff : Pin} />,
        key: 'favorite',
        label: fav ? t('actions.unpin') : t('actions.pin'),
        onClick: async () => {
          await favoriteTopic(id, !fav);
          if (scope) await refresh();
        },
        sfSymbol: fav ? 'pin.slash' : 'pin',
      },
      ...(favoriteMenuItem ? [favoriteMenuItem] : []),
      {
        type: 'divider' as const,
      },
      {
        disabled: !canEditTopic,
        icon: <Icon icon={Wand2} />,
        key: 'autoRename',
        label: t('actions.autoRename'),
        onClick: async () => {
          await autoRenameTopicTitle(id, scopedTopic?.agentId ?? undefined);
          if (scope) await refresh();
        },
        sfSymbol: 'wand.and.stars',
      },
      {
        disabled: !canEditTopic,
        icon: <Icon icon={PencilLine} />,
        key: 'rename',
        label: t('rename', { ns: 'common' }),
        onClick: () => {
          openRenameModal({
            defaultValue: title,
            description: t('renameModal.description', { ns: 'topic' }),
            onSave: async (newTitle) => {
              try {
                await updateTopicTitle(id, newTitle);
                if (scope) await refresh();
              } catch (error) {
                toast.error(
                  isForbiddenError(error)
                    ? t('manageOnlyCreator', { ns: 'common' })
                    : t('operationFailed', { ns: 'common' }),
                );
              }
            },
            title: t('renameModal.title', { ns: 'topic' }),
          });
        },
        sfSymbol: 'pencil',
      },
      {
        type: 'divider' as const,
      },
      ...(isDesktop
        ? [
            {
              icon: <Icon icon={PanelTop} />,
              key: 'openInNewTab',
              label: t('actions.openInNewTab'),
              onClick: () => {
                if (!activeAgentId) return;
                const url = buildWorkspaceAwarePath(
                  AGENT_CHAT_TOPIC_URL(activeAgentId, id),
                  activeWorkspaceSlug,
                );
                addTab(url);
                navigate(url, { escape: true });
              },
            },
          ]
        : []),
      {
        icon: <Icon icon={PanelRight} />,
        key: 'openOnRight',
        label: t('openOnRight', { ns: 'common' }),
        onClick: () => {
          openTopicInPortal(id);
        },
      },
      ...(isDesktop
        ? [
            {
              icon: <Icon icon={ExternalLink} />,
              key: 'openInNewWindow',
              label: t('actions.openInNewWindow'),
              onClick: () => {
                if (activeAgentId) openTopicInNewWindow(activeAgentId, id);
              },
            },
            {
              type: 'divider' as const,
            },
          ]
        : [{ type: 'divider' as const }]),
      {
        icon: <Icon icon={Hash} />,
        key: 'copySessionId',
        label: t('actions.copySessionId'),
        onClick: async () => {
          await copyToClipboard(id);
          toast.success(t('actions.copySessionIdSuccess'));
        },
      },
      {
        icon: <Icon icon={Link2} />,
        key: 'copyLink',
        label: t('actions.copyLink'),
        onClick: async () => {
          if (!activeAgentId) return;
          const url = `${appOrigin}${buildWorkspaceAwarePath(
            AGENT_CHAT_TOPIC_URL(activeAgentId, id),
            activeWorkspaceSlug,
          )}`;
          await copyToClipboard(url);
          // A private agent's topic link opens for nobody else in the workspace.
          if (!(await notifyPrivateAgentLink(activeAgentId)))
            toast.success(t('actions.copyLinkSuccess'));
        },
      },
      {
        icon: <Icon icon={MessageSquareText} />,
        key: 'copyTopicPrompt',
        label: t('actions.copyTopicPrompt'),
        onClick: async () => {
          await copyToClipboard(buildTopicPrompt({ id, title, workspaceId: activeWorkspaceId }));
          toast.success(t('actions.copyTopicPromptSuccess'));
        },
      },
      {
        type: 'divider' as const,
      },
      {
        disabled: !canCreateTopic,
        icon: <Icon icon={LucideCopy} />,
        key: 'duplicate',
        label: t('actions.duplicate'),
        onClick: async () => {
          if (!scope) return duplicateTopic(id);
          const loadingToast = toast.loading(t('duplicateLoading', { ns: 'topic' }));
          try {
            const newId = await topicService.cloneTopic(
              id,
              t('duplicateTitle', { ns: 'chat', title }),
            );
            await refresh();
            navigate(getProjectTopicPath(scope.projectId, newId));
            toast.success(t('duplicateSuccess', { ns: 'topic' }));
          } finally {
            loadingToast.close();
          }
        },
      },
      {
        disabled: !canEditTopic,
        icon: <Icon icon={Share} />,
        key: 'share',
        label: t('shareModal.title', { ns: 'chat' }),
        onClick: handleOpenShareModal,
        sfSymbol: 'square.and.arrow.up',
      },
      {
        disabled: !canCreateTopic || !activeAgentId,
        icon: <Icon icon={Forward} />,
        key: 'forwardToAgent',
        label: t('actions.forwardToAgent'),
        onClick: () => {
          if (!activeAgentId) return;
          createTopicForwardModal({ sourceAgentId: activeAgentId, topicId: id, topicTitle: title });
        },
      },
      {
        disabled: !canEditTopic,
        icon: <Icon icon={FolderInput} />,
        key: 'moveToAgent',
        label: t('actions.moveToAgent'),
        onClick: () => {
          createMoveTopicsModal({ sourceAgentId: activeAgentId, topicIds: [id] });
        },
      },
      {
        type: 'divider' as const,
      },
      {
        disabled: !canEditTopic,
        icon: <Icon icon={Stethoscope} />,
        key: 'diagnose',
        label: t('actions.diagnose'),
        onClick: () => {
          openTopicDoctorModal({ agentId: activeAgentId, topicId: id });
        },
        sfSymbol: 'stethoscope',
      },
      ...(enableTopicBugReport && bugReportItem ? [bugReportItem] : []),
      {
        type: 'divider' as const,
      },
      {
        danger: true,
        disabled: !canEditTopic,
        icon: <Icon icon={Trash} />,
        key: 'delete',
        label: t('delete', { ns: 'common' }),
        onClick: () => {
          void confirmRemoveTopic({
            onConfirm: async (removeFiles) => {
              try {
                await removeTopic(id, removeFiles);
                if (scope) {
                  if (routeTopicId === id) navigate(`/project/${scope.projectId}`);
                  await refresh();
                }
              } catch (error) {
                toast.error(
                  isForbiddenError(error)
                    ? t('manageOnlyCreator', { ns: 'common' })
                    : t('operationFailed', { ns: 'common' }),
                );
              }
            },
            topicIds: [id],
          });
        },
        sfSymbol: 'trash',
      },
    ].filter(Boolean) as DropdownItem[];
  }, [
    routeTopicId,
    scope,
    scopedTopic,
    refresh,
    id,
    fav,
    isCompleted,
    completionLabel,
    title,
    canCreateTopic,
    canEditTopic,
    activeAgentId,
    activeWorkspaceId,
    activeWorkspaceSlug,
    appOrigin,
    bugReportItem,
    enableTopicBugReport,
    autoRenameTopicTitle,
    duplicateTopic,
    favoriteMenuItem,
    favoriteTopic,
    toggleCompleted,
    removeTopic,
    updateTopicTitle,
    openTopicInNewWindow,
    openTopicInPortal,
    addTab,
    navigate,
    notifyPrivateAgentLink,
    t,
    handleOpenShareModal,
  ]);
  // Heterogeneous agents (Claude Code / Codex) run task-like topics that get
  // archived once done, so their sidebar rows surface archive as a one-click action.
  const canInlineArchive = !!id && canEditTopic && isHeterogeneous;

  return { canInlineArchive, dropdownMenu, isCompleted, toggleCompleted };
};