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.

22.5 KB
Raw Blame
import { ActionIcon, createStaticStyles, cx, Flexbox } from '@lobehub/ui';
import dayjs from 'dayjs';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { Fragment, memo, type ReactNode, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import {
  useHomeUsageWidget,
  useHomeUsageWidgetActive,
} from '@/business/client/features/HomeUsageWidget';
import AsyncError from '@/components/AsyncError';
import { BriefCardSkeleton } from '@/features/DailyBrief/BriefCardSkeleton';
import GroupBlock from '@/features/Home/components/GroupBlock';
import { homeType } from '@/features/Home/components/homeType';
import RailCard from '@/features/Home/components/RailCard';
import { useHomeSpacing } from '@/features/Home/homeDensity';
import Recommendations, { useRecommendationsVisible } from '@/features/Recommendations';
// Direct module import, not the feature barrel: home must not pull the whole
// acceptance workspace into its chunk for one hook.
import { useCacheScope } from '@/libs/swr/useCacheScope';
import { useBriefStore } from '@/store/brief';
import { briefListSelectors, briefNewsSelectors } from '@/store/brief/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useGoalStore } from '@/store/goal';
import { useUserStore } from '@/store/user';
import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/selectors';
import { useDensityTokens } from '@/styles/density';

import GoalsRailCard from './GoalsRailCard';
import { filterHiddenWidgetSections } from './hiddenWidgets';
import { buildHomeGoalEntries } from './homeGoals';
import { resolveInboxBlockState } from './inboxBlockState';
import InboxBriefCard from './InboxBriefCard';
import MarkAllReadButton from './MarkAllReadButton';
import NeedsYouRailCard from './NeedsYouRailCard';
import { resolveShownNewsOffset, shouldShowNewsItemTime } from './newsDayOffset';
import NewsList from './NewsList';
import { ownsRailSections } from './railSectionPlacement';
import RunningTasksCard from './RunningTasksCard';
import { filterMyInboxTopics } from './scopeTogglePlacement';
import { arrangeDayNews, splitBriefs } from './splitBriefs';
import UnreadTopicList from './UnreadTopicList';
import { useHomeInboxTopics } from './useHomeInboxTopics';

const styles = createStaticStyles(({ css }) => ({
  subtitle: css`
    margin-inline-start: 8px;
  `,
}));

/**
 * Mounted only while the rail has settled with nothing to show, so the page
 * hears "empty" once the feeds have answered and "not empty" as soon as any
 * card returns β€” including when the rail unmounts.
 */
const RailEmptyReporter = ({ onChange }: { onChange: (empty: boolean) => void }) => {
  useEffect(() => {
    onChange(true);
    return () => onChange(false);
  }, [onChange]);

  return null;
};

interface InboxSection {
  /** Header action revealed on hover (GroupBlock's action slot). */
  action?: ReactNode;
  /** Keep the action visible without hover β€” e.g. mid-interaction day paging. */
  actionAlwaysVisible?: boolean;
  /** Trailing marker on the heading, e.g. the team-view "only mine" chip. */
  badge?: ReactNode;
  /** Section folded to its heading. Needs `onCollapsedChange` to be operable. */
  collapsed?: boolean;
  count?: number;
  key: string;
  /** Omitted when the section labels itself (the running card names its own count). */
  label?: string;
  /** A refresh is in flight over rows already on screen (see GroupBlock `loading`). */
  loading?: boolean;
  node: ReactNode;
  onCollapsedChange?: (collapsed: boolean) => void;
  /** Section carries its own card shell β€” the rail renders it verbatim. */
  selfShelled?: boolean;
  subtitle?: string;
}

/**
 * The home inbox: everything the agents did while you were away, sorted by
 * whether it needs you.
 *
 * - **Goals** β€” the standing exception to "while you were away": goals run for
 *   days, so the ones still open (waiting on you, or working) are listed here
 *   rather than left to the agent page nobody visits mid-flight.
 * - **Needs you** β€” decision briefs blocking an agent. Run failures are not
 *   decisions; they go to the notification center instead.
 * - **Unread** β€” runs that finished while you were away, each showing the agent's
 *   last reply so the answer is right there.
 * - **Running** β€” collapsed to one line, showing who is working; a healthy run
 *   needs nothing from you.
 * - **News** β€” `insight` + `result` briefs (reports of finished work); read them
 *   or don't.
 * In a workspace this page stays the viewer's own: everyone's runs live on the
 * team tab of Home (`HomeTeamBoard`).
 *
 * Sections are siblings, never nested: each names itself and carries its own
 * count, and one absent section never hides another's heading.
 */
interface HomeInboxProps {
  hideNeedsYou?: boolean;
  /** Running activity belongs in the main column above recent topics. */
  hideRunning?: boolean;
  hideUnread?: boolean;
  /**
   * Main column only: the rail is collapsed, so the sections it owns (goals,
   * news) fold into this column instead of disappearing with it.
   */
  inlineRail?: boolean;
  /**
   * Rail only: told `true` once the rail's feeds have loaded and it has no card
   * to show, and `false` when a card appears, so the page can hand its space to
   * the main column without guessing from a loading rail.
   */
  onRailEmptyChange?: (empty: boolean) => void;
  variant?: 'default' | 'main' | 'rail';
}

const HomeInbox = memo<HomeInboxProps>((props) => {
  const {
    hideNeedsYou,
    hideRunning,
    hideUnread,
    inlineRail,
    onRailEmptyChange,
    variant = 'default',
  } = props;
  const isRail = variant === 'rail';
  const isMain = variant === 'main';
  const showRailSections = ownsRailSections({ inlineRail, variant });
  const { t } = useTranslation('home');
  const { contentGap } = useDensityTokens();
  const { blockGap } = useHomeSpacing();
  const { t: tCommon } = useTranslation('common');
  const isLogin = useUserStore(authSelectors.isLogin);
  const myId = useUserStore(userProfileSelectors.userId);

  // Briefs are per-user AND per-workspace rows: a list left over from the
  // previous workspace holds ids this one cannot resolve, and every action on it
  // would fail silently. The `briefList` replica partitions by identity scope
  // and clears its view on a scope switch, so the selectors only ever surface
  // the active scope's feed.
  const cacheScope = useCacheScope();
  const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);
  const briefsSWR = useFetchBriefs(isLogin);
  const briefs = useBriefStore(briefListSelectors.briefs);
  const isBriefsInit = useBriefStore(briefListSelectors.isBriefsInit);

  // The news digest is day-scoped: it fetches only briefs *created* on the
  // viewed local day (today by default), resolved or not, with β€Ή β€Ί paging into
  // earlier days. This replaces slicing news out of the unresolved feed, which
  // let week-old unread reports masquerade as "today's brief".
  const [newsDayOffset, setNewsDayOffset] = useState(0);
  // Recomputed every render on purpose (no memo): a Home left mounted across
  // local midnight must start querying the new day on its next render instead
  // of serving yesterday under a "Daily brief" label until remount.
  const newsDay = dayjs().subtract(newsDayOffset, 'day').format('YYYY-MM-DD');
  const useFetchNewsByDay = useBriefStore((s) => s.useFetchNewsByDay);
  const newsSync = useFetchNewsByDay(isLogin === true && showRailSections, newsDay);
  // While a page flip is in flight the previous day stays on screen. Only the
  // day *key* is remembered here β€” the row itself is read from the replica,
  // which clears on a scope switch, so another identity's digest never shows.
  // A restored empty day is not the server's answer (it may just be stale), so
  // it is not paintable β€” no "nothing today" copy β€” until confirmed.
  const requestedNews = useBriefStore(briefNewsSelectors.paintableNewsDay(newsDay));
  const [settledNewsDay, setSettledNewsDay] = useState(newsDay);
  if (requestedNews && settledNewsDay !== newsDay) setSettledNewsDay(newsDay);
  const newsData = useBriefStore(
    briefNewsSelectors.paintableNewsDay(requestedNews ? newsDay : settledNewsDay),
  );
  const dayNews = newsData?.news;
  const hasEarlierNews = newsData?.hasEarlier ?? false;
  // The previous day's payload shows while a page flip is in flight, so
  // everything the user SEES (title, empty copy, arrow gating) must derive
  // from the payload's own day β€” not from `newsDayOffset`, which has already
  // moved on. Otherwise a slow flip renders "Yesterday's brief" over today's
  // items. Clicks navigate relative to the shown day for the same reason:
  // WYSIWYG paging self-heals any offset/data divergence.
  const shownNewsOffset = newsData ? resolveShownNewsOffset(newsData.day) : 0;

  // Goals are the one home feed that is not about today: they run for days, so
  // the dashboard is where you check on them.
  const showGoals = isLogin === true && showRailSections;
  const useFetchHomeGoals = useGoalStore((s) => s.useFetchHomeGoals);
  const goalsSWR = useFetchHomeGoals(showGoals, cacheScope);
  // Read the replica view, not the hook: the persisted roll-up paints the rail
  // on the first frame and the sync only confirms it, so a cache hit no longer
  // renders one empty frame before the revalidate lands.
  const goals = useGoalStore((s) => s.homeGoalsByScope[cacheScope]?.goals);
  // The goal rail reads the goal's own lifecycle state (`goals.status`), so it
  // no longer needs a separate acceptance read to decide each pile.
  const goalEntries = useMemo(
    () => (showGoals ? buildHomeGoalEntries(goals) : []),
    [goals, showGoals],
  );

  const goalsCollapsed = useGlobalStore(systemStatusSelectors.homeGoalsCollapsed);
  const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);

  const topics = useHomeInboxTopics(isLogin);
  const recommendationsVisible = useRecommendationsVisible();
  const hiddenWidgets = useGlobalStore(systemStatusSelectors.hiddenHomeWidgets);

  // Business-slot widget: `enabled` false while it's toggled off or its column
  // isn't on the page, so the slot implementation can skip its fetches.
  const usageActive = useHomeUsageWidgetActive();
  const usageNode = useHomeUsageWidget(
    isLogin === true && usageActive && showRailSections && !hiddenWidgets.includes('usage'),
  );

  const { needsYou } = useMemo(() => splitBriefs(briefs), [briefs]);
  // Urgent briefs already waiting in "Needs you" leave the digest; the rest
  // lead with urgent, then normal, then info.
  const news = useMemo(() => arrangeDayNews(dayNews ?? [], briefs), [dayNews, briefs]);

  // Topics are workspace-wide from the server; this page only shows the
  // viewer's own, and the team tab owns everyone's.
  const unreadTopics = useMemo(
    () => filterMyInboxTopics(topics.unread, myId),
    [topics.unread, myId],
  );
  const runningTopics = useMemo(
    () => filterMyInboxTopics(topics.running, myId),
    [topics.running, myId],
  );

  if (!isLogin) return null;

  // The cached feed is on screen while the server confirms it: say so on the
  // section heading instead of hiding the rows behind a skeleton.
  const briefsRefreshing = isBriefsInit && briefsSWR.isValidating;

  const blockState = resolveInboxBlockState({
    hasError: Boolean(briefsSWR.error),
    hiddenWidgets,
    hideNeedsYou,
    isBriefsInit,
    isLoading: Boolean(briefsSWR.isLoading),
    isMain,
  });

  // The brief feed is the primary content; a first-load failure blocks the whole
  // surface. No fabricated section heading β€” we don't know what's under it yet.
  if (blockState === 'error') {
    return (
      <AsyncError
        error={briefsSWR.error}
        variant={'block'}
        onRetry={() => {
          void briefsSWR.mutate();
        }}
      />
    );
  }

  // First load: bare skeletons, no group heading (loading must not assert a
  // "Needs you" section that may turn out empty). Recommendations keep their own.
  if (blockState === 'skeleton') {
    return (
      <Flexbox gap={contentGap}>
        <BriefCardSkeleton />
        <BriefCardSkeleton />
        <Recommendations variant={variant} />
      </Flexbox>
    );
  }

  const sections: InboxSection[] = [];

  // A goal feed failure must not be silent: without this the card just vanishes,
  // which is indistinguishable from having no open goals β€” the one reading a
  // long-running goal surface can least afford.
  if (showGoals && goalsSWR.error && goals === undefined)
    sections.push({
      key: 'goals-error',
      label: t('inbox.goals.title'),
      node: (
        <AsyncError
          error={goalsSWR.error}
          variant={'inline'}
          onRetry={() => void goalsSWR.mutate()}
        />
      ),
    });

  // First: a goal is the longest-lived thing on the page, and the only one whose
  // absence from the rail leaves it with no home at all.
  if (goalEntries.length > 0)
    sections.push({
      collapsed: goalsCollapsed,
      count: goalEntries.length,
      key: 'goals',
      label: t('inbox.goals.title'),
      node: <GoalsRailCard bare={isRail} entries={goalEntries} />,
      onCollapsedChange: (next) =>
        updateSystemStatus({ homeGoalsCollapsed: next }, 'toggleHomeGoals'),
    });

  if (!isMain && !hideNeedsYou && needsYou.length > 0)
    sections.push(
      // The rail paginates instead of stacking and owns its header. Keep the
      // page-level scope control in that header alongside the pager.
      isRail
        ? {
            key: 'needsYou',
            node: <NeedsYouRailCard briefs={needsYou} />,
            selfShelled: true,
          }
        : {
            count: needsYou.length,
            key: 'needsYou',
            label: t('inbox.needsYou.title'),
            loading: briefsRefreshing,
            node: (
              <Flexbox gap={contentGap}>
                {needsYou.map((brief) => (
                  <InboxBriefCard brief={brief} key={brief.id} />
                ))}
              </Flexbox>
            ),
          },
    );

  // A topic-feed failure must not be silent: without this the unread / running
  // sections would just vanish and the inbox would look empty-but-fine.
  if (topics.error)
    sections.push({
      key: 'topics-error',
      label: t('inbox.unread.title'),
      node: <AsyncError error={topics.error} variant={'inline'} onRetry={topics.reload} />,
    });

  if (!hideUnread && unreadTopics.length > 0)
    sections.push({
      count: unreadTopics.length,
      key: 'unread',
      label: t('inbox.unread.title'),
      loading: topics.isRefreshing,
      node: (
        <UnreadTopicList
          bare={isRail}
          topics={unreadTopics}
          onFollowUpSent={topics.promoteToRunning}
        />
      ),
    });

  if (isMain) {
    if (briefsSWR.error && !isBriefsInit && !briefsSWR.isLoading) {
      sections.push({
        key: 'needsYou-error',
        label: t('inbox.needsYou.title'),
        node: (
          <AsyncError
            error={briefsSWR.error}
            variant={'inline'}
            onRetry={() => void briefsSWR.mutate()}
          />
        ),
      });
    } else if (!isBriefsInit) {
      sections.push({ key: 'needsYou-loading', node: <BriefCardSkeleton /> });
    } else if (!hideNeedsYou && needsYou.length > 0) {
      sections.push({
        count: needsYou.length,
        key: 'needsYou',
        label: t('inbox.needsYou.title'),
        loading: briefsRefreshing,
        node: (
          <Flexbox gap={contentGap}>
            {needsYou.map((brief) => (
              <InboxBriefCard brief={brief} key={brief.id} />
            ))}
          </Flexbox>
        ),
      });
    }
  }

  // No title: the card already says "3 tasks running" on its own head. Keep
  // this in the main flow immediately before Recent topics; the rail is for
  // glanceable reports, not live work the user may want to open.
  if (!hideRunning && !isRail && runningTopics.length > 0)
    sections.push({
      key: 'running',
      node: <RunningTasksCard bare={isRail} running={runningTopics} />,
    });

  // A first-load failure of the day feed must not make the whole section
  // vanish β€” an absent "Daily brief" is indistinguishable from having no
  // briefs, so surface the error with a retry like the topic feed does.
  if (showRailSections && newsSync.error && !dayNews)
    sections.push({
      key: 'news-error',
      label: t('inbox.news.title'),
      node: (
        <AsyncError
          error={newsSync.error}
          variant={'inline'}
          onRetry={() => void newsSync.revalidate()}
        />
      ),
    });

  // Shown once the day feed has loaded, whenever there is anything to show *or*
  // anywhere to go: an empty today must still expose the pager when earlier
  // days hold briefs, and a browsed-to empty day must keep the way back.
  // Everything below renders from `shownNewsOffset` / the payload's own day β€”
  // see the comment at `shownNewsOffset` for why `newsDayOffset` must not be
  // used for display.
  const unresolvedNews = news.filter((brief) => !brief.resolvedAt);
  const showNewsSection =
    showRailSections && !!dayNews && (news.length > 0 || shownNewsOffset > 0 || hasEarlierNews);
  if (showNewsSection) {
    const newsDate = dayjs(newsData!.day);
    const newsLabel =
      shownNewsOffset === 0
        ? t('inbox.news.title')
        : shownNewsOffset === 1
          ? t('inbox.news.titleYesterday')
          : t('inbox.news.titleDay', {
              date: newsDate.format(
                tCommon(
                  newsDate.isSame(dayjs(), 'year') ? 'time.formatThisYear' : 'time.formatOtherYear',
                ),
              ),
            });

    sections.push({
      action: (
        <Flexbox horizontal align={'center'} gap={4}>
          {unresolvedNews.length > 0 && <MarkAllReadButton news={unresolvedNews} />}
          <ActionIcon
            disabled={!hasEarlierNews}
            icon={ChevronLeftIcon}
            size={'small'}
            title={t('inbox.news.prevDay')}
            onClick={() => setNewsDayOffset(shownNewsOffset + 1)}
          />
          <ActionIcon
            disabled={shownNewsOffset === 0}
            icon={ChevronRightIcon}
            size={'small'}
            title={t('inbox.news.nextDay')}
            onClick={() => setNewsDayOffset(Math.max(0, shownNewsOffset - 1))}
          />
        </Flexbox>
      ),
      // Mid-paging (or on an empty day) the arrows are the section's only
      // controls β€” they must not vanish when the pointer leaves the header.
      actionAlwaysVisible: shownNewsOffset > 0 || news.length === 0,
      count: news.length || undefined,
      key: 'news',
      label: newsLabel,
      node:
        news.length === 0 ? (
          <span className={homeType.supporting}>
            {t(shownNewsOffset === 0 ? 'inbox.news.emptyToday' : 'inbox.news.emptyDay')}
          </span>
        ) : (
          <NewsList bare={isRail} news={news} showTime={shouldShowNewsItemTime(shownNewsOffset)} />
        ),
      subtitle: t('inbox.news.subtitle'),
    });
  }

  // The rail's LAST card, below even the suggestions: usage is passive
  // reference data, glanceable but never urgent, so it sits under everything
  // that reports actual work. Same shell as every other rail widget.
  const usageCard =
    usageNode &&
    (isRail ? (
      <RailCard title={t('inbox.usage.title')}>{usageNode}</RailCard>
    ) : (
      <GroupBlock title={t('inbox.usage.title')}>{usageNode}</GroupBlock>
    ));

  const visibleSections = filterHiddenWidgetSections(sections, hiddenWidgets);

  if (visibleSections.length === 0) {
    if (isMain) return null;

    if (isRail) {
      if (recommendationsVisible || usageCard)
        return (
          <Flexbox gap={contentGap}>
            {recommendationsVisible && <Recommendations variant={'rail'} />}
            {usageCard}
          </Flexbox>
        );

      // Still waiting on a feed that may yet fill the rail: keep its place
      // with the loading skeleton rather than collapse it and slide the page
      // back when the cards land.
      const railFeedsSettled =
        (!showGoals || goals !== undefined || Boolean(goalsSWR.error)) &&
        (!showRailSections || Boolean(dayNews) || Boolean(newsSync.error));

      if (!railFeedsSettled)
        return (
          <Flexbox gap={contentGap}>
            <BriefCardSkeleton />
            <BriefCardSkeleton />
          </Flexbox>
        );

      return onRailEmptyChange ? <RailEmptyReporter onChange={onRailEmptyChange} /> : null;
    }

    // With no titled block above it, the bare recommendations list doesn't need
    // the full section gap below the input area β€” offset the parent's gap so it
    // sits closer to the input.
    return (
      <>
        {recommendationsVisible && (
          <Flexbox style={{ marginBlockStart: -24 }}>
            <Recommendations />
          </Flexbox>
        )}
        {usageCard}
      </>
    );
  }

  return (
    <Flexbox gap={isRail ? contentGap : blockGap}>
      {visibleSections.map(
        ({
          action,
          actionAlwaysVisible,
          badge,
          collapsed,
          count,
          key,
          label,
          loading,
          node,
          onCollapsedChange,
          selfShelled,
          subtitle,
        }) => {
          if (selfShelled) return <Fragment key={key}>{node}</Fragment>;

          if (isRail)
            return (
              <RailCard
                action={action}
                collapsed={collapsed}
                count={count}
                key={key}
                loading={loading}
                title={
                  label && (
                    <>
                      {label}
                      {badge}
                    </>
                  )
                }
                onCollapsedChange={onCollapsedChange}
              >
                {node}
              </RailCard>
            );

          if (!label) return <Flexbox key={key}>{node}</Flexbox>;

          return (
            <GroupBlock
              action={action}
              actionAlwaysVisible={actionAlwaysVisible}
              collapsed={collapsed}
              count={count}
              key={key}
              loading={loading}
              title={
                <>
                  {label}
                  {subtitle && (
                    <span className={cx(homeType.meta, styles.subtitle)}>Β· {subtitle}</span>
                  )}
                  {badge}
                </>
              }
              onCollapsedChange={onCollapsedChange}
            >
              {node}
            </GroupBlock>
          );
        },
      )}

      {!isMain && <Recommendations variant={variant} />}
      {usageCard}
    </Flexbox>
  );
});

export default HomeInbox;