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.

5.7 KB
Raw Blame
import { type UserMemoryEffort } from '@lobechat/types';
import { Center, Divider, Flexbox, Icon } from '@lobehub/ui';
import { BrainOffIcon } from '@lobehub/ui/icons';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { type LucideIcon } from 'lucide-react';
import { Brain } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';

import LevelSlider from '@/features/ModelSwitchPanel/components/ControlsForm/LevelSlider';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
import { densityTokens } from '@/styles/density.stylex';

import { useAgentId } from '../../hooks/useAgentId';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import { useMemoryEnabled } from './useMemoryEnabled';

const MEMORY_EFFORT_LEVELS: readonly UserMemoryEffort[] = ['low', 'medium', 'high'];

const styles = stylex.create({
  active: { backgroundColor: cssVar.colorFillTertiary, backgroundImage: 'none' },
  description: { fontSize: '12px', color: cssVar.colorTextDescription },
  icon: {
    borderWidth: '1px',
    borderStyle: 'solid',
    borderColor: cssVar.colorFillTertiary,
    borderRadius: cssVar.borderRadius,
    backgroundColor: cssVar.colorBgElevated,
    backgroundImage: 'none',
  },
  option: {
    cursor: 'pointer',
    width: '100%',
    paddingBlock: '8px',
    paddingInline: '8px',
    borderRadius: cssVar.borderRadius,
    transition: 'background-color 0.2s',
    backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
    backgroundImage: { 'default': null, ':hover': 'none' },
  },
  title: {
    fontSize: densityTokens['--lobe-density-font-size'],
    fontWeight: 500,
    color: cssVar.colorText,
  },
});

interface ToggleOption {
  description: string;
  icon: LucideIcon;
  label: string;
  value: 'off' | 'on';
}

const ToggleItem = memo<ToggleOption>(({ value, description, icon, label }) => {
  const agentId = useAgentId();
  const { updateAgentChatConfig } = useUpdateAgentConfig();
  const isEnabled = useMemoryEnabled(agentId);
  const { allowed: canCreate } = usePermission('create_content');

  const isActive = value === 'on' ? isEnabled : !isEnabled;

  return (
    <Flexbox
      horizontal
      align={'flex-start'}
      className={stylex.props(styles.option, isActive && styles.active).className}
      gap={12}
      style={{
        cursor: canCreate ? undefined : 'not-allowed',
        opacity: canCreate ? undefined : 0.5,
      }}
      onClick={async () => {
        if (!canCreate) return;
        await updateAgentChatConfig({ memory: { enabled: value === 'on' } });
      }}
    >
      <Center className={stylex.props(styles.icon).className} flex={'none'} height={32} width={32}>
        <Icon icon={icon} />
      </Center>
      <Flexbox flex={1}>
        <div {...stylex.props(styles.title)}>{label}</div>
        <div {...stylex.props(styles.description)}>{description}</div>
      </Flexbox>
    </Flexbox>
  );
});

/**
 * Agent-level memory effort override. Rendered next to the Pinned/Auto/Disable
 * policy of the memory capability row in the chat-input Tools popover, so moving
 * the memory entry out of the "+" menu keeps its tuning reachable. It owns the
 * separator above itself and disappears entirely while memory is off, so a host
 * panel never ends up with a divider that separates nothing.
 */
export const MemoryEffortControl = memo<{ showDivider?: boolean }>(({ showDivider = true }) => {
  const { t } = useTranslation('chat');
  const agentId = useAgentId();
  const { updateAgentChatConfig } = useUpdateAgentConfig();
  const isEnabled = useMemoryEnabled(agentId);
  const { allowed: canCreate } = usePermission('create_content');
  const effort = useAgentStore((s) => chatConfigByIdSelectors.getMemoryToolEffortById(agentId)(s));

  if (!isEnabled) return null;

  return (
    <>
      {showDivider && <Divider style={{ margin: 0 }} />}
      <Flexbox horizontal align={'center'} gap={16} padding={8}>
        <Flexbox flex={1} gap={4} style={{ minWidth: 100 }}>
          <div {...stylex.props(styles.title)}>{t('memory.effort.title')}</div>
          <div {...stylex.props(styles.description)}>{t('memory.effort.desc')}</div>
        </Flexbox>
        <Flexbox
          flex={1}
          style={{
            opacity: canCreate ? undefined : 0.5,
            pointerEvents: canCreate ? undefined : 'none',
          }}
        >
          <LevelSlider<UserMemoryEffort>
            defaultValue="medium"
            levels={MEMORY_EFFORT_LEVELS}
            value={effort}
            marks={{
              0: t('memory.effort.low.title'),
              1: t('memory.effort.medium.title'),
              2: t('memory.effort.high.title'),
            }}
            onChange={async (value) => {
              if (!canCreate) return;
              await updateAgentChatConfig({ memory: { effort: value, enabled: true } });
            }}
          />
        </Flexbox>
      </Flexbox>
    </>
  );
});

MemoryEffortControl.displayName = 'MemoryEffortControl';

const Controls = memo(() => {
  const { t } = useTranslation('chat');

  const toggleOptions: ToggleOption[] = [
    {
      description: t('memory.off.desc'),
      icon: BrainOffIcon,
      label: t('memory.off.title'),
      value: 'off',
    },
    {
      description: t('memory.on.desc'),
      icon: Brain,
      label: t('memory.on.title'),
      value: 'on',
    },
  ];

  return (
    <Flexbox gap={4}>
      {toggleOptions.map((option) => (
        <ToggleItem {...option} key={option.value} />
      ))}
      <MemoryEffortControl />
    </Flexbox>
  );
});

export default Controls;