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.

8.1 KB
Raw Blame
'use client';

import { Block, createStaticStyles, cssVar, Empty, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { MessagesSquare } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useParams } from 'react-router';
import urlJoin from 'url-join';

import AsyncBoundary from '@/components/AsyncBoundary';
import Loading from '@/components/Loading/BrandTextLoading';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useAgentStore } from '@/store/agent';
import { densityVars } from '@/styles/densityVars';

import { lessonSectionLabel } from '../helpers';
import { useExpertiseDomain, useExpertiseLesson } from '../hooks';

const styles = createStaticStyles(({ css }) => ({
  body: css`
    overflow-y: auto;
    display: flex;
  `,
  sections: css`
    overflow: hidden;
    width: min(100%, 760px);
  `,
  sectionItem: css`
    display: grid;
    grid-template-columns: 72px minmax(0, 1fr);
    gap: ${densityVars.sectionGap};

    padding-block: 14px;
    padding-inline: ${densityVars.cardPadding};

    & + & {
      border-block-start: 1px solid ${cssVar.colorBorderSecondary};
    }
  `,
  title: css`
    max-width: 880px;
    text-wrap: balance;
  `,
  hitTitle: css`
    min-width: 0;
  `,
}));

/** Labels a lesson section, falling back to the raw key when no polarity declares it. */
const SectionLabel = memo<{ sectionKey: string }>(({ sectionKey }) => {
  const { t } = useTranslation('selfLearning');
  const label = lessonSectionLabel(sectionKey);
  return <>{label ? t(label) : sectionKey}</>;
});

SectionLabel.displayName = 'ExpertiseSectionLabel';

const LessonDetail = memo(() => {
  const { t } = useTranslation('selfLearning');
  const { domainId, lessonId } = useParams();
  const activeAgentId = useAgentStore((s) => s.activeAgentId);
  const {
    data: domain,
    error: domainError,
    revalidate: revalidateDomain,
  } = useExpertiseDomain(domainId);
  const { data, error, isLoading, notFound, revalidate } = useExpertiseLesson(lessonId);
  const domainPath =
    activeAgentId && domainId
      ? urlJoin('/agent', activeAgentId, 'self-evolving', domainId)
      : undefined;
  const experiencePath = domainPath ? urlJoin(domainPath, 'experience') : undefined;
  const sections = data?.lesson.sections.filter(
    (section) =>
      section.key !== 'rule' ||
      section.body.trim().toLocaleLowerCase() !== data.lesson.title.trim().toLocaleLowerCase(),
  );

  return (
    <Flexbox height={'100%'} width={'100%'}>
      <NavHeader
        styles={{ left: { paddingInlineStart: 24 } }}
        left={
          activeAgentId ? (
            <AgentBreadcrumb
              agentId={activeAgentId}
              title={t('title')}
              extraItems={[
                <Link key={'domain'} to={domainPath ?? '#'}>
                  {domain?.domain.title ?? '…'}
                </Link>,
                <Link key={'experience'} to={experiencePath ?? '#'}>
                  {t('experience.title')}
                </Link>,
                data?.lesson.code ?? '…',
              ]}
            />
          ) : null
        }
      />
      <Flexbox className={styles.body} flex={1} width={'100%'}>
        <WideScreenContainer>
          <AsyncBoundary
            data={data}
            empty={<Empty title={t('rules.detail.notFound')} />}
            error={error}
            errorVariant={'page'}
            isEmpty={notFound && !data}
            isLoading={isLoading}
            loading={<Loading debugId={'SelfLearningLesson'} />}
            onRetry={() => void revalidate()}
          >
            {data && (
              <Flexbox gap={20} paddingBlock={'14px 64px'}>
                <Flexbox gap={10}>
                  <Text fontSize={12} type={'secondary'} weight={600}>
                    {t('rules.detail.eyebrow', { code: data.lesson.code })}
                  </Text>
                  <Text className={styles.title} fontSize={26} lineHeight={1.35} weight={700}>
                    {data.lesson.title}
                  </Text>
                  <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
                    <Text fontSize={12.5} type={'secondary'}>
                      {t('rules.detail.meta', {
                        hits: data.lesson.hitCount,
                        runs: data.lesson.hitRunCount,
                      })}
                    </Text>
                    {data.lesson.layer && <Tag>{data.lesson.layer}</Tag>}
                  </Flexbox>
                  {!!domainError && (
                    <Text fontSize={12.5} type={'danger'}>
                      {t('rules.detail.domainUnavailable')} ·{' '}
                      <Text as={'button'} type={'info'} onClick={() => void revalidateDomain()}>
                        {t('rules.detail.retry')}
                      </Text>
                    </Text>
                  )}
                </Flexbox>

                <Block className={styles.sections} padding={0} variant={'outlined'}>
                  {sections?.map((section) => (
                    <div className={styles.sectionItem} key={section.key}>
                      <Text fontSize={12} type={'secondary'} weight={600}>
                        <SectionLabel sectionKey={section.key} />
                      </Text>
                      <Text fontSize={14} lineHeight={1.65}>
                        {section.body}
                      </Text>
                    </div>
                  ))}
                </Block>

                <Flexbox gap={10}>
                  <Text fontSize={15} weight={600}>
                    {t('rules.detail.examples')}
                  </Text>
                  {data.hits.length === 0 ? (
                    <Empty
                      description={t('rules.detail.noExamplesDesc')}
                      title={t('rules.detail.noExamples')}
                    />
                  ) : (
                    data.hits.map((hit, index) => (
                      <Block
                        gap={6}
                        key={`${hit.createdAt}-${index}`}
                        padding={14}
                        variant={'outlined'}
                      >
                        <Flexbox horizontal align={'flex-start'} gap={12} justify={'space-between'}>
                          <Text className={styles.hitTitle} fontSize={13} lineHeight={1.65}>
                            {hit.example}
                          </Text>
                          <Tag color={hit.outcome === 'pass' ? 'green' : 'red'}>
                            {t(`rules.detail.outcome.${hit.outcome}`)}
                          </Tag>
                        </Flexbox>
                        {hit.note && (
                          <Text fontSize={12} type={'secondary'}>
                            {hit.note}
                          </Text>
                        )}
                        {hit.subjectType === 'topic' && activeAgentId ? (
                          <Link to={urlJoin('/agent', activeAgentId, hit.subjectId)}>
                            <Flexbox horizontal align={'center'} gap={5}>
                              <Icon
                                color={cssVar.colorTextSecondary}
                                icon={MessagesSquare}
                                size={13}
                              />
                              <Text fontSize={12} type={'secondary'}>
                                {hit.runTitle ?? `#${hit.runIndex}`}
                              </Text>
                            </Flexbox>
                          </Link>
                        ) : (
                          <Text fontSize={11} type={'secondary'}>
                            {hit.runTitle ?? `#${hit.runIndex}`}
                          </Text>
                        )}
                      </Block>
                    ))
                  )}
                </Flexbox>
              </Flexbox>
            )}
          </AsyncBoundary>
        </WideScreenContainer>
      </Flexbox>
    </Flexbox>
  );
});

LessonDetail.displayName = 'LessonDetail';

export default LessonDetail;