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.

10.1 KB
Raw Blame
import { Button, createStaticStyles, cssVar, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
import dayjs from 'dayjs';
import { SquareArrowOutUpRight } from 'lucide-react';
import { memo, type ReactNode, useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { ExperimentDetail } from '@/features/AgentGoals/Experiments/Detail';
import { isExperiment } from '@/features/AgentGoals/Experiments/model';
import GateDetail from '@/features/AgentGoals/ProcessControl/BatchGate/GateDetail';
import PlanDetail from '@/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail';
import {
  coordinatorGateReason,
  coordinatorReasonCopies,
  viewGateKind,
} from '@/features/AgentGoals/ProcessControl/coordinatorCopy';
import {
  buildGoalGraphView,
  type GoalNodeView,
} from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';
import {
  findBatchGate,
  findBatchPlan,
} from '@/features/AgentGoals/ProcessControl/Graph/batchModel';
import { KindDot } from '@/features/AgentGoals/ProcessControl/shared';
import {
  useFrontierActions,
  useGoalNodeSelect,
} from '@/features/AgentGoals/ProcessControl/useGoalProcessActions';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { goalSelectors, useGoalStore } from '@/store/goal';

/**
 * Drill-down for one Goal Graph node. Everything rendered here is derived from
 * the `goal.graph` snapshot — shared by SWR key with whichever host opened it. A
 * Work node links onward to its Task detail (the deep half of the chain:
 * node → task → topic conversation).
 */

const styles = createStaticStyles(({ css }) => ({
  attempt: css`
    padding-block: 6px;

    & + & {
      border-block-start: 1px dashed ${cssVar.colorBorderSecondary};
    }
  `,
  label: css`
    font-size: 12px;
    font-weight: 600;
    color: ${cssVar.colorTextSecondary};
  `,
  linkRow: css`
    cursor: pointer;
    border-radius: ${cssVar.borderRadiusSM};

    &:hover {
      background: ${cssVar.colorFillQuaternary};
    }
  `,
  mono: css`
    font-family: ${cssVar.fontFamilyCode};
    font-variant-numeric: tabular-nums;
  `,
}));

const Section = memo<{ children: ReactNode; title: string }>(({ children, title }) => (
  <Flexbox gap={6}>
    <span className={styles.label}>{title}</span>
    {children}
  </Flexbox>
));

Section.displayName = 'GoalNodePortalSection';

/** The complete ledger — unlike the frontier row, no rank gate hides it here. */
const AttemptLedger = memo<{ view: GoalNodeView }>(({ view }) => {
  const { t } = useTranslation('chat');
  if (view.attempts.length === 0) return null;

  return (
    <Section title={t('goalProcess.attempts.title')}>
      <Flexbox gap={0}>
        {view.attempts.map((attempt) => (
          <Flexbox
            horizontal
            align={'baseline'}
            className={styles.attempt}
            gap={10}
            key={attempt.index}
          >
            <Text className={styles.mono} fontSize={12} style={{ flex: 'none' }} type={'secondary'}>
              {dayjs(attempt.startedAt).format('MM-DD HH:mm')}
            </Text>
            <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>
              {t('goalProcess.attempts.nth', { index: attempt.index })}
            </Text>
            <Text
              fontSize={12}
              style={{ flex: 'none' }}
              type={
                attempt.outcome === 'passed'
                  ? 'success'
                  : attempt.outcome === 'failed'
                    ? 'danger'
                    : 'secondary'
              }
            >
              {t(`goalProcess.attempts.${attempt.outcome}` as const)}
            </Text>
            <Text fontSize={12} style={{ flex: 1, minWidth: 0 }} type={'secondary'}>
              {attempt.reason ?? ''}
            </Text>
          </Flexbox>
        ))}
      </Flexbox>
    </Section>
  );
});

AttemptLedger.displayName = 'GoalNodePortalAttempts';

const NodeLinkRow = memo<{ onClick: () => void; text: string; view: GoalNodeView }>(
  ({ onClick, text, view }) => (
    <Flexbox
      horizontal
      align={'center'}
      className={styles.linkRow}
      gap={6}
      paddingBlock={4}
      paddingInline={4}
      onClick={onClick}
    >
      <KindDot kind={view.node.kind} />
      <Text ellipsis fontSize={12} type={'secondary'}>
        {text}
      </Text>
    </Flexbox>
  ),
);

NodeLinkRow.displayName = 'GoalNodePortalLink';

const Body = memo(() => {
  const { t } = useTranslation('chat');
  const view = useChatStore(chatPortalSelectors.goalNodeView);
  const openTaskDetail = useChatStore((s) => s.openTaskDetail);
  const { decide } = useFrontierActions(view?.goalId ?? '');
  // Fetched here, not assumed from the goal page: the drill-down also opens
  // from the conversation portal, where nothing else holds the snapshot.
  const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
  useFetchGoalGraph(view?.goalId);
  const snapshot = useGoalStore(goalSelectors.goalGraph(view?.goalId ?? ''));

  const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);
  // Linked nodes land where a click on the map would: a Task shows the Task
  // itself, anything else its drill-down.
  const openNode = useGoalNodeSelect(view?.goalId ?? '', graph);
  if (!view || !graph || !snapshot) return null;

  const nodeView = graph.byId[view.nodeId];
  if (!nodeView) return null;
  const { node } = nodeView;
  if (isExperiment(graph, nodeView))
    return (
      <ExperimentDetail graph={graph} snapshot={snapshot} view={nodeView}>
        <AttemptLedger view={nodeView} />
      </ExperimentDetail>
    );
  const isFinding = node.kind === 'finding';
  // A batch's release gate is judged by the coordinator, not asked of a person:
  // its panel shows the verdicts and their checks instead of a bare decision.
  const batchGate = node.kind === 'decision' ? findBatchGate(graph, node.id) : undefined;
  // A batch's plan is a skill: it opens as one, full height, with its versions.
  const batchPlan = node.kind === 'finding' ? findBatchPlan(graph, node.id) : undefined;
  if (batchPlan)
    return <PlanDetail graph={graph} model={batchPlan.model} round={batchPlan.round} />;

  // Coordinator gates localize; arbitrary gates keep their stored copy.
  const gateKind = node.kind === 'decision' ? viewGateKind(nodeView) : undefined;
  const rawGateReason = gateKind ? coordinatorGateReason(nodeView.decision?.question) : undefined;
  const gateReasonCopies = coordinatorReasonCopies(rawGateReason);
  const gateReasonText = gateReasonCopies
    ? gateReasonCopies.map((copy) => t(copy.key as any, copy.params)).join('; ')
    : rawGateReason;

  return (
    <Flexbox flex={1} gap={16} padding={16} style={{ minHeight: 0, overflowY: 'auto' }}>
      {batchGate && (
        <GateDetail
          decide={decide}
          graph={graph}
          model={batchGate.model}
          round={batchGate.round}
          onOpenNode={(nodeId) => openNode(nodeId)}
        />
      )}

      {node.description &&
        !batchGate &&
        (isFinding ? (
          // A finding's description is the run's handoff — real Markdown, so
          // render it as such instead of pre-wrapped source text. `flex-shrink: 0`
          // is load-bearing: Markdown's root is `overflow: hidden`, so as a flex
          // item its automatic minimum size collapses to 0 and a long handoff
          // would be squeezed (and clipped) to fit instead of scrolling the panel.
          <Markdown headerMultiple={0.25} style={{ flexShrink: 0 }}>
            {node.description}
          </Markdown>
        ) : (
          <Section
            title={
              node.kind === 'task'
                ? t('goalProcess.node.instruction')
                : t('goalProcess.node.description')
            }
          >
            <Text fontSize={13} style={{ lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>
              {node.description}
            </Text>
          </Section>
        ))}

      {node.kind === 'decision' && nodeView.decision && !batchGate && (
        <Section title={t('goalProcess.gate.decisionPointLabel')}>
          {/* State the problem itself; the resolution options carry the choices. */}
          <Text fontSize={13}>{gateReasonText ?? nodeView.decision.question}</Text>
        </Section>
      )}

      <AttemptLedger view={nodeView} />

      {nodeView.findings.length > 0 && (
        <Section title={t('goalProcess.node.producedFindings')}>
          <Flexbox gap={2}>
            {nodeView.findings.map((finding) => {
              const findingView = graph.byId[finding.id];
              if (!findingView) return null;
              return (
                <NodeLinkRow
                  key={finding.id}
                  text={finding.title}
                  view={findingView}
                  onClick={() => openNode(finding.id)}
                />
              );
            })}
          </Flexbox>
        </Section>
      )}

      {nodeView.producedBy && graph.byId[nodeView.producedBy.id] && (
        <Section title={t('goalProcess.node.producedByTitle')}>
          <NodeLinkRow
            text={nodeView.producedBy.title}
            view={graph.byId[nodeView.producedBy.id]}
            onClick={() => openNode(nodeView.producedBy!.id)}
          />
        </Section>
      )}

      {nodeView.blockers.length > 0 && (
        <Section title={t('goalProcess.node.blockers')}>
          <Flexbox gap={2}>
            {nodeView.blockers.map((blocker) => {
              const blockerView = graph.byId[blocker.id];
              if (!blockerView) return null;
              return (
                <NodeLinkRow
                  key={blocker.id}
                  text={blocker.title}
                  view={blockerView}
                  onClick={() => openNode(blocker.id)}
                />
              );
            })}
          </Flexbox>
        </Section>
      )}

      {node.taskId && (
        <Button
          icon={<Icon icon={SquareArrowOutUpRight} />}
          size={'small'}
          style={{ alignSelf: 'flex-start' }}
          onClick={() => openTaskDetail(node.taskId!)}
        >
          {t('goalProcess.node.openTask')}
        </Button>
      )}
    </Flexbox>
  );
});

export default Body;