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.

4.7 KB
Raw Blame
import { type ItemType } from '@lobehub/ui';
import { Icon } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
import { LibraryBig } from 'lucide-react';
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';

import FileIcon from '@/components/FileIcon';
import RepoIcon from '@/components/LibIcon';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { densityTokens, sidebarRow } from '@/styles/density.stylex';

import { useAgentId } from '../../hooks/useAgentId';
import CheckboxItem from '../components/CheckboxWithLoading';

// Cap so the widest library/file row (icon + label + checkbox + paddings) stays within the
// submenu's 320px footer-driven width, keeping it level with the skill submenu instead of
// growing past it.
const labelMaxWidth = 'min(210px, 45vw)';

const styles = stylex.create({
  viewMore: {
    cursor: 'pointer',
    display: 'flex',
    gap: densityTokens['--lobe-density-content-gap'],
    alignItems: 'center',
    // width 320 + margin-inline -12 anchors the submenu to 320px (matching the skill
    // submenu) and lets the row span full width; padding-inline 12 lines its icon/text
    // up with the menu items above.
    width: '320px',
    minHeight: sidebarRow.controlHeight,
    // The footer wrapper adds padding-block: 8px top & bottom; the top keeps it separated
    // from the list, but the bottom leaves a dead gap against the popup edge β€” cancel it.
    marginBlockEnd: '-8px',
    marginInline: '-12px',
    paddingInline: densityTokens['--lobe-density-content-gap'],
    borderStyle: 'none',
    borderRadius: sidebarRow.radius,
    fontSize: sidebarRow.textFontSize,
    color: cssVar.colorText,
    backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
    backgroundImage: { 'default': 'none', ':hover': 'none' },
    transition: `background 150ms ${cssVar.motionEaseOut}`,
  },
  viewMoreLabel: { flex: '1', textAlign: 'start' },
});

export interface KnowledgeControls {
  enabledCount: number;
  footer: ReactNode;
  items: ItemType[];
}

export const useControls = ({
  openAttachKnowledgeModal,
}: {
  openAttachKnowledgeModal: () => void;
}) => {
  const { t } = useTranslation('chat');
  const agentId = useAgentId();

  const files = useAgentStore((s) => agentByIdSelectors.getAgentFilesById(agentId)(s), isEqual);
  const knowledgeBases = useAgentStore(
    (s) => agentByIdSelectors.getAgentKnowledgeBasesById(agentId)(s),
    isEqual,
  );

  const [toggleFile, toggleKnowledgeBase] = useAgentStore((s) => [
    s.toggleFile,
    s.toggleKnowledgeBase,
  ]);
  const enabledCount =
    files.filter((item) => item.enabled).length +
    knowledgeBases.filter((item) => item.enabled).length;

  const libraryItems = knowledgeBases.map((item) => ({
    icon: <RepoIcon />,
    key: item.id,
    label: (
      <CheckboxItem
        checked={item.enabled}
        hasPadding={false}
        id={item.id}
        label={item.name}
        labelMaxWidth={labelMaxWidth}
        onUpdate={async (id, enabled) => {
          await toggleKnowledgeBase(id, enabled);
        }}
      />
    ),
  }));

  const fileItems = files.map((item) => ({
    icon: <FileIcon fileName={item.name} fileType={item.type} size={20} />,
    key: item.id,
    label: (
      <CheckboxItem
        checked={item.enabled}
        hasPadding={false}
        id={item.id}
        label={item.name}
        labelMaxWidth={labelMaxWidth}
        onUpdate={async (id, enabled) => {
          await toggleFile(id, enabled);
        }}
      />
    ),
  }));

  // Flat list (no "Libraries" / "Files" group headers): libraries first, then files.
  const relatedGroups: ItemType[] = [
    ...libraryItems,
    ...(libraryItems.length > 0 && fileItems.length > 0 ? [{ type: 'divider' as const }] : []),
    ...fileItems,
  ];

  // The footer is the only entry into the full library / file picker, so it stays
  // rendered when nothing is attached yet β€” otherwise the submenu shows "no related
  // files or libraries" with no way to attach the first one.
  const footer = (
    <button
      {...stylex.props(styles.viewMore)}
      type="button"
      onClick={(event) => {
        event.stopPropagation();
        openAttachKnowledgeModal();
      }}
    >
      <Icon color={cssVar.colorTextSecondary} icon={LibraryBig} size={14} />
      <span {...stylex.props(styles.viewMoreLabel)}>
        {relatedGroups.length > 0 ? t('knowledgeBase.viewMore') : t('knowledgeBase.related.browse')}
      </span>
    </button>
  );

  return { enabledCount, footer, items: relatedGroups } satisfies KnowledgeControls;
};