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.

16.2 KB
Raw Blame
'use client';

import {
  ActionIcon,
  Button,
  Collapsible,
  createStaticStyles,
  cssVar,
  Flexbox,
  Icon,
  Spin,
  Text,
  Tooltip,
} from '@lobehub/ui';
import dayjs from 'dayjs';
import {
  BadgeCheck,
  ChevronRight,
  ChevronsDownUp,
  ChevronsUpDown,
  ExternalLink,
  RotateCcw,
  Trash,
} from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import {
  type AcceptanceCheck,
  checkDisplayTitle,
  checkHeadMeta,
  CriterionList,
  CriterionRow,
  groupChecks,
  shouldGroupChecks,
  useAcceptanceBundle,
  useAcceptanceBySubject,
} from '@/features/Acceptance';
import {
  AcceptanceBundleGate,
  AcceptanceScope,
} from '@/features/Acceptance/Viewer/AcceptanceScope';
import AcceptanceCheckInventory from '@/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory';
import AcceptanceDecision from '@/features/Acceptance/Viewer/Review/AcceptanceDecision';
import { openAcceptanceDeleteConfirm } from '@/features/Acceptance/Workspace/AcceptanceDeleteConfirm';
import { usePermission } from '@/hooks/usePermission';
import { verifyService } from '@/services/verify';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
import { useVerifyStore } from '@/store/verify';
import { densityVars } from '@/styles/densityVars';

import GoalRoundTimeline from './GoalRoundTimeline';
import { resolveTaskAcceptanceRequirement } from './resolveTaskAcceptanceProjection';
import { TaskAcceptanceHeader } from './TaskAcceptanceHeader';
import TaskVerifyConfig from './TaskVerifyConfig';

const styles = createStaticStyles(({ css }) => ({
  error: css`
    padding-block: 8px;
    padding-inline: ${densityVars.contentGap};
    border-radius: ${cssVar.borderRadiusLG};
    background: ${cssVar.colorErrorBg};
  `,
  group: css`
    & + & {
      border-block-start: 1px solid ${cssVar.colorBorderSecondary};
    }
  `,
  groupHeader: css`
    cursor: pointer;
    padding-block: 8px;
    padding-inline: ${densityVars.contentGap};
  `,
}));

interface AcceptanceErrorProps {
  onRetry: () => void;
}

const AcceptanceError = memo<AcceptanceErrorProps>(({ onRetry }) => {
  const { t } = useTranslation('chat');

  return (
    <Flexbox horizontal align={'center'} className={styles.error} gap={8}>
      <Text fontSize={12} style={{ flex: 1 }} type={'danger'}>
        {t('taskDetail.acceptance.loadError')}
      </Text>
      <Button icon={<Icon icon={RotateCcw} />} size={'small'} type={'text'} onClick={onRetry}>
        {t('taskDetail.acceptance.retry')}
      </Button>
    </Flexbox>
  );
});

AcceptanceError.displayName = 'TaskAcceptanceError';

interface CompactCheckRowProps {
  check: AcceptanceCheck;
  onOpen: () => void;
}

const CompactCheckRow = memo<CompactCheckRowProps>(({ check, onOpen }) => {
  const { t } = useTranslation('verify');
  const meta = checkHeadMeta(check);

  return (
    <CriterionRow
      data-task-acceptance-check={check.id}
      icon={<Icon color={meta.color} icon={meta.icon} size={16} style={{ flex: 'none' }} />}
      seq={check.seq}
      title={checkDisplayTitle(check.title, t('acceptance.checks.holisticTitle'))}
      onOpen={onOpen}
    />
  );
});

CompactCheckRow.displayName = 'TaskAcceptanceCompactCheckRow';

interface TaskAcceptanceProps {
  /**
   * `result` — the task result panel. The reader there has just read the
   * delivery and wants to judge it on the spot, so this mounts the real
   * Acceptance checklist and decision bar (the same atoms the acceptance page
   * assembles) instead of a compact preview that only links out. The round
   * timeline and the 验收目标 contract stay behind the report link.
   */
  variant?: 'default' | 'result';
}

const TaskAcceptance = memo<TaskAcceptanceProps>(({ variant = 'default' }) => {
  const { t } = useTranslation(['chat', 'verify']);
  const openAcceptance = useChatStore((state) => state.openAcceptance);
  const openAcceptanceCheck = useChatStore((state) => state.openAcceptanceCheck);
  const showTaskAgentPanel = useGlobalStore((state) => state.toggleTaskAgentPanel);
  const { allowed: canEditTask } = usePermission('create_content');
  const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
  const taskDatabaseId = useTaskStore(taskDetailSelectors.activeTaskDatabaseId);
  const taskName = useTaskStore(taskDetailSelectors.activeTaskName);
  const automationMode = useTaskStore(taskDetailSelectors.activeTaskAutomationMode);
  const verify = useTaskStore(taskDetailSelectors.activeTaskVerifyConfig);
  const [sectionExpanded, setSectionExpanded] = useState(true);
  const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(() => new Set());
  const [requirementExpanded, setRequirementExpanded] = useState(false);

  const {
    data: acceptanceSubject,
    error: subjectError,
    isLoading: subjectLoading,
    mutate: mutateSubject,
  } = useAcceptanceBySubject('task', automationMode ? null : (taskDatabaseId ?? null));
  const {
    data: bundle,
    error: bundleError,
    isLoading: bundleLoading,
    mutate: mutateBundle,
  } = useAcceptanceBundle(acceptanceSubject?.id ?? null);

  // Task detail intentionally renders the Acceptance's cross-round union. The
  // count may grow when later rounds introduce checks; that history is part of
  // the delivery record rather than a mismatch with the original configuration.
  const checks = useMemo(() => bundle?.checks ?? [], [bundle?.checks]);
  const requirement = resolveTaskAcceptanceRequirement(
    verify?.requirement,
    bundle?.acceptance.requirement,
  );
  const openCheck = (acceptanceId: string, checkId: string) => {
    showTaskAgentPanel(true);
    openAcceptanceCheck(acceptanceId, checkId);
  };

  // Same destination as a check, one level up: the report belongs in the panel
  // beside the task, not on a page that replaces it.
  const openReport = (acceptanceId: string) => {
    showTaskAgentPanel(true);
    openAcceptance(acceptanceId);
  };

  const grouped = shouldGroupChecks(checks.length);
  const groups = useMemo(
    () =>
      grouped ? groupChecks(checks, t('acceptance.group.uncategorized', { ns: 'verify' })) : [],
    [checks, grouped, t],
  );
  const groupKeys = groups.map((group) => group.key);
  const allGroupsCollapsed =
    groupKeys.length > 0 && groupKeys.every((key) => collapsedGroups.has(key));
  // A recurring task (schedule / heartbeat) never gets a verify plan on the
  // server — its ticks are not deliveries. Offering the Verifier config or an
  // acceptance section here would advertise a contract that never runs.
  if (automationMode) return null;

  if (subjectLoading) return <Spin size="middle" />;
  // Before the first Acceptance round exists, the configured criteria ARE the
  // delivery acceptance. Keep them in this single slot; once a round exists,
  // replace the definitions with their live/result projection below.
  if (!acceptanceSubject && !subjectError) return <TaskVerifyConfig />;

  // Removing the acceptance drops the aggregate (round reports detach) AND
  // clears the task's verify config — otherwise the section would fall back to
  // the configured-criteria view and the next run would recreate the aggregate.
  // Ordering makes the two writes safe without a server transaction: the config
  // is cleared FIRST (a failure aborts before anything is destroyed), and only
  // then is the aggregate deleted (a failure there leaves it intact for retry).
  // The inverse order could delete the record while the stale config survives
  // to recreate it on the next run.
  const handleRemoveAcceptance = () => {
    if (!acceptanceSubject || !taskId) return;
    openAcceptanceDeleteConfirm({
      description: t('taskDetail.acceptance.removeConfirm.content'),
      ids: [acceptanceSubject.id],
      title: taskName || requirement || t('taskDetail.acceptance.untitled'),
      onDelete: async (purge) => {
        await useTaskStore.getState().updateVerifyConfig(taskId, {
          enabled: false,
          requirement: null,
          verifyCriteriaIds: null,
        });
        await verifyService.deleteAcceptance(acceptanceSubject.id, purge);
        useVerifyStore.getState().removeAcceptancesFromLists([acceptanceSubject.id]);
        void useVerifyStore.getState().refreshAcceptanceLists();
        await mutateSubject();
      },
    });
  };

  // `acceptance.remove` only authorizes the acceptance creator (or a workspace
  // owner, cloud-side), not everyone who can edit the task — so the affordance
  // follows the bundle's isOwner rather than dead-ending in FORBIDDEN.
  const reportButton = acceptanceSubject && (
    <Flexbox horizontal align={'center'} gap={4}>
      <Button
        icon={<Icon icon={ExternalLink} />}
        size={'small'}
        type={'text'}
        onClick={() => openReport(acceptanceSubject.id)}
      >
        {t('taskDetail.acceptance.openReport')}
      </Button>
      {canEditTask && bundle?.isOwner && (
        <ActionIcon
          icon={Trash}
          size={'small'}
          title={t('taskDetail.acceptance.remove')}
          onClick={handleRemoveAcceptance}
        />
      )}
    </Flexbox>
  );

  // The result panel mounts the live checklist itself — rows expand in place,
  // reviews land here, and the decision bar closes the loop without a detour
  // through the acceptance page. Its own 验收检查清单 header replaces the
  // section header; the report link rides in the inventory toolbar.
  if (variant === 'result' && acceptanceSubject && !subjectError) {
    // Signed off is finished: the verdict moves up beside the title, and the
    // decision bar — which has nothing left to offer — stops covering the
    // evidence below it.
    const accepted = bundle?.acceptance.status === 'accepted';
    const acceptedAt = accepted ? bundle?.acceptance.completedAt : undefined;
    const acceptedBadge = accepted && (
      <Tooltip
        title={t('acceptance.banner.accepted', {
          ns: 'verify',
          time: acceptedAt ? dayjs(acceptedAt).format('YYYY-MM-DD HH:mm') : '',
        })}
      >
        <Flexbox data-task-acceptance-accepted horizontal align={'center'} gap={4}>
          <Icon color={cssVar.colorSuccess} icon={BadgeCheck} size={14} />
          <Text fontSize={12} style={{ color: cssVar.colorSuccess, whiteSpace: 'nowrap' }}>
            {t('taskDetail.acceptanceState.accepted')}
          </Text>
        </Flexbox>
      </Tooltip>
    );
    return (
      <AcceptanceScope embedded acceptanceId={acceptanceSubject.id}>
        <AcceptanceBundleGate height={160}>
          <Flexbox gap={16}>
            <AcceptanceCheckInventory titleExtra={acceptedBadge} toolbar={reportButton} />
            {!accepted && <AcceptanceDecision />}
          </Flexbox>
        </AcceptanceBundleGate>
      </AcceptanceScope>
    );
  }

  const header = (
    <TaskAcceptanceHeader
      count={checks.length}
      // The section shows the rounds and the checklist; the report is the full
      // record behind them — reachable from the block it belongs to, instead
      // of only from the status row at the top of the page.
      extra={reportButton}
      isOpen={sectionExpanded}
      onToggle={() => setSectionExpanded((expanded) => !expanded)}
    />
  );

  if (subjectError) {
    return (
      <Flexbox gap={8}>
        {header}
        <Flexbox>
          <AcceptanceError onRetry={() => void mutateSubject()} />
        </Flexbox>
      </Flexbox>
    );
  }

  return (
    <Flexbox gap={8}>
      {header}
      <Collapsible open={sectionExpanded}>
        <Flexbox gap={16}>
          {bundleLoading && <Spin size="middle" />}
          {bundleError ? <AcceptanceError onRetry={() => void mutateBundle()} /> : null}
          {bundle && (
            <>
              <GoalRoundTimeline rounds={bundle.rounds} />
              {requirement && (
                <Flexbox gap={6}>
                  <Text fontSize={12} type={'secondary'}>
                    {t('taskDetail.acceptance.goal')}
                  </Text>
                  {/* The contract, not the result. A goal-dispatched task carries
                      a generated paragraph here, and printing it in full pushed
                      the checks — the thing the reader came for — below the
                      fold. Two lines, and the rest on demand. */}
                  <Text
                    ellipsis={requirementExpanded ? undefined : { rows: 2 }}
                    style={{ cursor: 'pointer' }}
                    title={requirement}
                    onClick={() => setRequirementExpanded((open) => !open)}
                  >
                    {requirement}
                  </Text>
                </Flexbox>
              )}
              <Flexbox gap={8}>
                <Flexbox horizontal align={'center'} gap={8}>
                  <Text fontSize={12} type={'secondary'}>
                    {t('taskDetail.acceptance.checklist')}
                  </Text>
                  <Flexbox flex={1} />
                  {grouped && groupKeys.length > 0 && (
                    <ActionIcon
                      icon={allGroupsCollapsed ? ChevronsUpDown : ChevronsDownUp}
                      size={'small'}
                      title={
                        allGroupsCollapsed
                          ? t('taskDetail.acceptance.expandAll')
                          : t('taskDetail.acceptance.collapseAll')
                      }
                      onClick={() =>
                        setCollapsedGroups(allGroupsCollapsed ? new Set() : new Set(groupKeys))
                      }
                    />
                  )}
                </Flexbox>
                <CriterionList>
                  {grouped
                    ? groups.map((group) => {
                        const collapsed = collapsedGroups.has(group.key);

                        return (
                          <Flexbox className={styles.group} key={group.key}>
                            <Flexbox
                              horizontal
                              align={'center'}
                              className={styles.groupHeader}
                              gap={8}
                              onClick={() =>
                                setCollapsedGroups((previous) => {
                                  const next = new Set(previous);
                                  if (next.has(group.key)) next.delete(group.key);
                                  else next.add(group.key);
                                  return next;
                                })
                              }
                            >
                              <Text fontSize={12}>{group.label}</Text>
                              <Text fontSize={11} type={'secondary'}>
                                {group.checks.length}
                              </Text>
                              <Flexbox flex={1} />
                              <Icon
                                color={cssVar.colorTextDescription}
                                icon={ChevronRight}
                                size={13}
                                style={{
                                  transform: collapsed ? 'none' : 'rotate(90deg)',
                                  transition: 'transform 0.2s',
                                }}
                              />
                            </Flexbox>
                            {!collapsed &&
                              group.checks.map((check) => (
                                <CompactCheckRow
                                  check={check}
                                  key={check.id}
                                  onOpen={() => openCheck(bundle.acceptance.id, check.id)}
                                />
                              ))}
                          </Flexbox>
                        );
                      })
                    : checks.map((check) => (
                        <CompactCheckRow
                          check={check}
                          key={check.id}
                          onOpen={() => openCheck(bundle.acceptance.id, check.id)}
                        />
                      ))}
                </CriterionList>
              </Flexbox>
            </>
          )}
        </Flexbox>
      </Collapsible>
    </Flexbox>
  );
});

TaskAcceptance.displayName = 'TaskAcceptance';

export default TaskAcceptance;