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.

26.7 KB
Raw Blame
import { AGENT_CHAT_TOPIC_URL, DEFAULT_INBOX_AVATAR } from '@lobechat/const';
import type { ChatTopicMetadata, ChatTopicStatus } from '@lobechat/types';
import { formatElapsedClockTime } from '@lobechat/utils';
import {
  getTopicMetadataWorkingDirectoryEffectivePath,
  getTopicMetadataWorkingDirectorySourcePath,
} from '@lobechat/utils/client/topic';
import {
  createStaticStyles,
  cssVar,
  Flexbox,
  Icon,
  Popover,
  Skeleton,
  Tag,
  Text,
  Tooltip,
  useTheme,
} from '@lobehub/ui';
import dayjs from 'dayjs';
import isEqual from 'fast-deep-equal';
import { MessageSquareDashed, TargetIcon } from 'lucide-react';
import type { CSSProperties, DragEvent, RefObject } from 'react';
import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import AgentAvatar from '@/components/AgentAvatar';
import DotsLoading from '@/components/DotsLoading';
import { TOPIC_STATUS_VISUALS } from '@/components/ExecutionStatus';
import RingLoadingIcon from '@/components/RingLoading';
import UnreadDot from '@/components/UnreadDot';
import { isDesktop } from '@/const/version';
import { getPlatformIcon } from '@/features/AgentChannel/const';
import { TopicMigrationIndicator } from '@/features/AgentTransferMigration';
import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';
import { useHasDraft } from '@/features/ChatInput/draftStorage';
import { startTopicDrag } from '@/features/ChatInput/InputEditor/ReferTopic/topicDragData';
import NavItem from '@/features/NavPanel/components/NavItem';
import { getProjectTopicPath } from '@/features/Projects/Layout/navigation';
import TopicCreatorAvatar, { useTopicCreator } from '@/features/TopicCreatorAvatar';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { getWorkingDirectoryName } from '@/helpers/workingDirectoryPath';
import { useTopicOnlyMine } from '@/hooks/useTopicOnlyMine';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';

import { useTopicHoverPrefetch } from '../../hooks/topicHoverPrefetch/useTopicHoverPrefetch';
import { markSidebarTopicActivation } from '../../hooks/useScrollActiveTopicIntoView';
import { useTopicNavigation } from '../../hooks/useTopicNavigation';
import ThreadList from '../../TopicListContent/ThreadList';
import { useTopicListScope } from '../../TopicListScope';
import { useScopedTopic } from '../../useScopedTopics';
import Actions from './Actions';
import TopicItemContextMenu from './ContextMenu';
import { getTopicMetaCard } from './metaCardData';
import MetaHoverCard from './MetaHoverCard';

// Base UI Popover plays an opacity/scale enter+exit transition driven by these
// CSS vars on the positioner. Zero them so the meta hover card appears instantly
// instead of easing in β€” the hover-intent delay (`mouseEnterDelay`) still gates
// when it shows. `styles.root` maps to the positioner (inline style β†’ wins over
// the library's default without a specificity fight).
const META_HOVER_CARD_STYLES = {
  content: { padding: 12 },
  root: {
    '--lobe-popover-animation-duration': '0ms',
    '--lobe-popover-animation-duration-exit': '0ms',
  } as CSSProperties,
};

const styles = createStaticStyles(({ css }) => ({
  markerIcon: css`
    position: relative;
    display: inline-flex;
    flex: none;
  `,
  runningElapsedTime: css`
    flex: none;

    min-width: 42px;

    font-size: 12px;
    font-variant-numeric: tabular-nums;
    line-height: 1;
    color: ${cssVar.colorTextTertiary};
    text-align: end;
  `,
}));

/**
 * The mobile surface renders its topic list in a modal and never mounts the
 * working sidebar β€” the desktop host of a topic's thread list. Without nesting
 * the rows under the topic row, mobile users can't reach an existing subtopic
 * at all, so the nesting lives here on that surface only.
 *
 * Scoped to the route's topic (`showThreadList`): opening a thread under an
 * inactive topic would call `openThreadInPortal` while `activeTopicId` still
 * points at another topic, so the thread would resolve against the wrong topic's
 * context β€” and every mounted list would fetch its own threads.
 *
 * Read per call rather than once at module load so a test can stub `__MOBILE__`.
 */
const isMobileSurface = () => typeof __MOBILE__ !== 'undefined' && __MOBILE__;
// Nesting cue: keeps the rows visually under their topic row.
const NESTED_THREAD_LIST_INDENT = 32;

const getWorkingDirectoryDisplay = (metadata: ChatTopicMetadata | undefined) => {
  const config = metadata?.workingDirectoryConfig;
  const workingDirectory = getTopicMetadataWorkingDirectoryEffectivePath(metadata);
  if (!workingDirectory) return;

  const branch = config?.git?.branch;
  const dirName = getWorkingDirectoryName(workingDirectory);
  if (!dirName) return;

  const sourcePath = getTopicMetadataWorkingDirectorySourcePath(metadata);
  const sourceName =
    sourcePath && sourcePath !== workingDirectory ? getWorkingDirectoryName(sourcePath) : undefined;
  const pathLabel = sourceName && sourceName !== dirName ? `${sourceName}/${dirName}` : dirName;

  return {
    label: branch ? `${pathLabel} Β· ${branch}` : pathLabel,
    repoType: config?.repoType ?? (isDesktop ? undefined : 'github'),
  };
};

interface RunningElapsedTimeProps {
  agentId?: string;
  /**
   * Server-side start of the topic's current run (list query's
   * `runStartedAt`). Fallback for topics that are running on the server but
   * have no local operation β€” after a page refresh only the ACTIVE topic is
   * reconnected into the in-memory store, so every other running row would
   * otherwise render no timer at all.
   */
  runStartedAt?: Date | string | number | null;
  topicId: string;
}

const RunningElapsedTime = memo<RunningElapsedTimeProps>(({ agentId, runStartedAt, topicId }) => {
  const localStartTime = useChatStore(
    agentId
      ? operationSelectors.getVisibleAgentRuntimeStartTimeByContext({ agentId, topicId })
      : () => undefined,
  );

  // Prefer the in-memory operation: it tracks the local run precisely and
  // updates the moment a run starts/stops. The server stamp only covers the
  // refresh case above. Normalize like the server fallback does β€” the value
  // crosses the wire as an ISO string.
  const serverStartTimeMs = runStartedAt == null ? undefined : new Date(runStartedAt).getTime();
  const startTime =
    localStartTime ?? (Number.isFinite(serverStartTimeMs) ? serverStartTimeMs : undefined);

  const [now, setNow] = useState(() => Date.now());

  useEffect(() => {
    if (!startTime) return;

    setNow(Date.now());
    const timer = setInterval(() => setNow(Date.now()), 1000);

    return () => clearInterval(timer);
  }, [startTime]);

  if (!startTime) return null;

  return (
    <span className={styles.runningElapsedTime}>{formatElapsedClockTime(now - startTime)}</span>
  );
});

RunningElapsedTime.displayName = 'RunningElapsedTime';

interface TopicItemProps {
  fav?: boolean;
  /** A goal was planned in this conversation β€” marks the row's identity slot. */
  hasGoal?: boolean;
  id?: string;
  metadata?: ChatTopicMetadata;
  /**
   * Server-side start of the topic's current run (list query's
   * `runStartedAt`). Lets running topics that have no local operation
   * (refreshed, non-active) still show an elapsed timer β€” see
   * `RunningElapsedTime`.
   */
  runStartedAt?: Date | string | number | null;
  /** Show the topic's project directory as a second line under the title. Used by
   * the by-status grouping, where the row otherwise carries no project context
   * (by-project mode already puts the directory in the group header).
   */
  showWorkingDirectory?: boolean;
  status?: ChatTopicStatus | null;
  /**
   * Group headers that already identify the owning agent (the by-agent
   * grouping) suppress the row's leading agent avatar β€” the identity lives in
   * the header, and the row keeps its status/identity icons instead.
   */
  suppressAgentAvatar?: boolean;
  title: string;
  /** Creator of the topic; drives the workspace creator avatar. */
  userId?: string;
}

type TopicNavigationActions = Pick<
  ReturnType<typeof useTopicNavigation>,
  'focusTopicPopup' | 'navigateToTopic'
>;

interface TopicItemRowProps extends TopicItemProps {
  defaultTopicActive: boolean;
  isTopicActive: boolean;
  navRef: RefObject<TopicNavigationActions>;
  /** Route's topic β€” only its row may carry its thread list (see the mobile mount). */
  showThreadList: boolean;
}

const TopicItemRow = memo<TopicItemRowProps>(
  ({
    id,
    title,
    fav,
    hasGoal,
    metadata,
    runStartedAt,
    status,
    showWorkingDirectory,
    userId,
    defaultTopicActive,
    isTopicActive,
    navRef,
    showThreadList,
    suppressAgentAvatar,
  }) => {
    const scopedTopic = useScopedTopic(id);
    const scope = useTopicListScope();
    const inboxId = useAgentStore(builtinAgentSelectors.inboxAgentId);
    const { t } = useTranslation('topic');
    const { isDarkMode } = useTheme();
    // Rows render by the dozen, so agent-level reads share ONE subscription.
    // Only workspace-shared (`public`) agents get the creator avatar β€” a
    // workspace-private agent's topics all belong to the viewer.
    const [fallbackAgentId, isSharedAgent] = useAgentStore((s) => [
      s.activeAgentId,
      agentSelectors.currentAgentVisibility(s) === 'public',
    ]);
    const activeAgentId = scopedTopic?.agentId ?? fallbackAgentId;
    const activeWorkspaceSlug = useActiveWorkspaceSlug();
    // Creator of the topic β€” resolves only inside an active workspace; drives
    // the identity-first icon layout below.
    // "Only my topics" makes the viewer's own rows self-evident, so the creator
    // avatar carries no information there β€” drop it and fall back to the
    // personal-mode row. A teammate's topic can still be listed (the active
    // topic is retained under the filter) and keeps its ownership cue. Bot
    // topics still resolve their initiator via `botCreator`.
    const onlyMine = useTopicOnlyMine();
    const currentUserId = useUserStore(userProfileSelectors.userId);
    const hideOwnCreator = onlyMine && userId === currentUserId;
    const creatorUserId = isSharedAgent && !metadata?.bot && !hideOwnCreator ? userId : undefined;
    const author = useTopicCreator(creatorUserId, metadata?.botCreator);

    const loadingRingColor = isDarkMode
      ? cssVar.colorWarningBorder
      : `color-mix(in srgb, ${cssVar.colorWarning} 45%, transparent)`;

    // Construct href for cmd+click support
    const href = useMemo(() => {
      if (!activeAgentId || !id) return undefined;
      return buildWorkspaceAwarePath(
        scope ? getProjectTopicPath(scope.projectId, id) : AGENT_CHAT_TOPIC_URL(activeAgentId, id),
        activeWorkspaceSlug,
      );
    }, [activeAgentId, activeWorkspaceSlug, id, scope]);

    const [isLoading, isUnreadCompleted, hasLocalRunningRuntime, isRuntimeVisiblyRunning] =
      useChatStore((s) => [
        !!id && operationSelectors.isTopicVisiblyRunning(id)(s),
        !!id && operationSelectors.isTopicUnreadCompleted(id)(s),
        !!id &&
          !!activeAgentId &&
          operationSelectors.isAgentRuntimeRunningByContext({
            agentId: activeAgentId,
            topicId: id,
          })(s),
        !!id &&
          !!activeAgentId &&
          operationSelectors.isAgentRuntimeVisiblyRunningByContext({
            agentId: activeAgentId,
            topicId: id,
          })(s),
      ]);

    const handleDragStart = useCallback(
      (event: DragEvent) => {
        if (!id) return;
        startTopicDrag(event, { topicId: id, topicTitle: title });
      },
      [id, title],
    );

    // A plain click only switches the topic. Opening a new tab takes an explicit
    // gesture (Cmd/Ctrl+click, middle click, or the context menu): a double
    // click used to open one, and a lagging UI turned repeated clicks into
    // unwanted tabs.
    const handleClick = useCallback(() => {
      if (id) markSidebarTopicActivation(id);
      void navRef.current.navigateToTopic(id);
    }, [id, navRef]);

    const isFailed = status === 'failed';
    const isRunning = status === 'running';
    const isScheduled = status === 'scheduled';
    const isWaitingForHuman = status === 'waitingForHuman';
    // Post-visible-output tail: the user-visible answer is complete but the run
    // is still doing terminal bookkeeping (unread persist, title summary) β€”
    // #16518 intentionally masks the running icon during this window.
    const isMaskedRunningTail = isRunning && hasLocalRunningRuntime && !isRuntimeVisiblyRunning;
    const shouldShowRunningIcon = isLoading || (isRunning && !isMaskedRunningTail);

    // By-status grouping mixes topics from different projects, so surface each
    // topic's working directory as a muted second line. Data is already on the
    // topic (`metadata.workingDirectoryConfig` / `workingDirectory`) β€” no fetch.
    // On web it's a github repo URL; on desktop a local path.
    const workingDirectoryDisplay = useMemo(
      () => (showWorkingDirectory ? getWorkingDirectoryDisplay(metadata) : undefined),
      [metadata, showWorkingDirectory],
    );
    const workingDirectoryNode = workingDirectoryDisplay ? (
      <Flexbox horizontal align={'center'} gap={4} style={{ overflow: 'hidden' }}>
        <DirIcon repoType={workingDirectoryDisplay.repoType} size={13} />
        <Text ellipsis fontSize={12} style={{ color: cssVar.colorTextDescription }}>
          {workingDirectoryDisplay.label}
        </Text>
      </Flexbox>
    ) : undefined;

    // Surface the unread dot right away during the masked tail instead of a
    // blank icon gap until markTopicUnread's persisted 'unread' lands. Skipped
    // while the user is viewing the topic, like markTopicUnread's own guard.
    const isRunningTailUnread = isMaskedRunningTail && !isTopicActive;

    // `status` is the row's own copy: a project list keeps its topics outside
    // the chat store, so `isUnreadCompleted` never sees them there.
    const hasUnread = id && (isUnreadCompleted || status === 'unread' || isRunningTailUnread);
    const hoverPrefetchHandlers = useTopicHoverPrefetch({
      agentId: activeAgentId,
      status,
      topicId: id,
    });

    useEffect(() => {
      if (!activeAgentId || !id || !isUnreadCompleted || hasLocalRunningRuntime) return;

      void useChatStore
        .getState()
        .prefetchMessages({ agentId: activeAgentId, scope: 'main', topicId: id });
    }, [activeAgentId, hasLocalRunningRuntime, id, isUnreadCompleted]);

    // Surface a WeChat-style red "[Draft]" hint when this topic holds unsent
    // input. Drafts live in localStorage keyed by messageMapKey; the default
    // topic (no id) maps to the new-topic draft. `useHasDraft` re-renders the
    // row only when the draft appears or clears.
    const draftKey = useMemo(
      () => (activeAgentId ? messageMapKey({ agentId: activeAgentId, topicId: id }) : undefined),
      [activeAgentId, id],
    );
    const hasDraft = useHasDraft(draftKey);
    const draftPrefix = hasDraft ? (
      <Text fontSize={12} style={{ color: cssVar.colorError, flex: 'none' }}>
        {t('draft')}
      </Text>
    ) : undefined;
    // On a two-line row (title + working directory) the hint sits under the
    // leading avatar instead, so it no longer eats into the title width.
    const draftBelowIcon = hasDraft ? (
      <Text
        fontSize={10}
        style={{ color: cssVar.colorError, flex: 'none', lineHeight: 1, whiteSpace: 'nowrap' }}
      >
        {t('draft')}
      </Text>
    ) : undefined;

    // Codex-style hover detail card: when the topic carries git context, hovering
    // the row reveals a card on the right with repo / branch / worktree / PR / CI β€”
    // keeping the row itself clean.
    const metaCard = useMemo(() => getTopicMetaCard(metadata), [metadata]);

    // For default topic (no id)
    if (!id) {
      return (
        <NavItem
          active={defaultTopicActive}
          slots={{ titlePrefix: draftPrefix }}
          titleColor={cssVar.colorText}
          icon={
            isLoading ? (
              <RingLoadingIcon
                ringColor={loadingRingColor}
                size={14}
                style={{ color: cssVar.colorWarning }}
              />
            ) : (
              <Icon color={cssVar.colorTextDescription} icon={MessageSquareDashed} size={'small'} />
            )
          }
          title={
            <Flexbox horizontal align={'center'} flex={1} gap={6}>
              {t('defaultTitle')}
              <Tag
                size={'small'}
                style={{
                  color: cssVar.colorTextDescription,
                  fontSize: 10,
                }}
              >
                {t('temp')}
              </Tag>
            </Flexbox>
          }
          onClick={handleClick}
        />
      );
    }

    // Execution / attention state. In workspace mode this moves to the row's
    // trailing side so the leading slot can carry the creator identity.
    const statusIconNode = (() => {
      // A scheduled topic hasn't run yet β€” nothing else can be true of it,
      // so its clock outranks the other states.
      if (isScheduled) {
        const visual = TOPIC_STATUS_VISUALS.scheduled;
        const runAt = metadata?.scheduledRun?.runAt;
        const icon = <Icon icon={visual.icon} size={'small'} style={{ color: visual.color }} />;
        return runAt ? (
          <Tooltip title={t('scheduledStatusTip', { time: dayjs(runAt).format('MM-DD HH:mm') })}>
            {icon}
          </Tooltip>
        ) : (
          icon
        );
      }
      if (isWaitingForHuman) {
        const visual = TOPIC_STATUS_VISUALS.waitingForHuman;
        return <Icon icon={visual.icon} size={'small'} style={{ color: visual.color }} />;
      }
      if (shouldShowRunningIcon) {
        return (
          <RingLoadingIcon
            ringColor={loadingRingColor}
            size={14}
            style={{ color: cssVar.colorWarning }}
          />
        );
      }
      if (isFailed) {
        const visual = TOPIC_STATUS_VISUALS.failed;
        return (
          <Tooltip title={t('failedStatusTip')}>
            <Icon icon={visual.icon} size={'small'} style={{ color: visual.color }} />
          </Tooltip>
        );
      }
      // Unread is the third `pending` attention state (see `resolveStatusBucket`
      // in `@lobechat/utils/client/topic`), so it ranks with its two siblings
      // above β€” and above the PR marker, which shares this single icon slot.
      if (hasUnread) return <UnreadDot />;
      // Persisted execution state is the topic's primary status. Keep every
      // non-idle state above git metadata so scheduled / completed
      // topics cannot be mistaken for merely open / merged / closed PRs.
      // `running` is handled exclusively by shouldShowRunningIcon above so
      // the masked post-output tail cannot fall back to a static running icon.
      if (status && status !== 'active' && status !== 'running') {
        const visual = TOPIC_STATUS_VISUALS[status];
        return <Icon icon={visual.icon} size={'small'} style={{ color: visual.color }} />;
      }
      return null;
    })();

    // Identity-flavored icons the row owns (goal, PR marker, bot platform) β€” these
    // keep the leading slot even in workspace mode, with the creator shrunk to
    // a corner badge.
    const identityIconNode = (() => {
      // The conversation a goal was planned in says more about the row than
      // the PR it produced, so it outranks the PR marker (which stays in the
      // meta hover card).
      if (hasGoal) {
        return (
          <Tooltip title={t('metaCard.goal')}>
            <span aria-label={t('metaCard.goal')} className={styles.markerIcon}>
              <Icon
                icon={TargetIcon}
                size={'small'}
                style={{ color: cssVar.colorTextDescription }}
              />
            </span>
          </Tooltip>
        );
      }
      if (metadata?.bot?.platform) {
        const ProviderIcon = getPlatformIcon(metadata.bot!.platform);
        if (ProviderIcon) {
          return <ProviderIcon color={cssVar.colorTextDescription} size={16} />;
        }
      }
      return null;
    })();

    const idleIconPlaceholder = <span aria-hidden style={{ flex: 'none', width: 16 }} />;

    // Workspace mode (creator resolvable): the creator's round avatar is the
    // primary visual and always leads the row; the row's own icon β€” execution
    // status first, then identity icons (Discord / WeChat) β€”
    // shrinks into a bottom-right corner badge. Personal mode keeps the
    // original layout untouched.
    const ownIconNode = statusIconNode ?? identityIconNode;
    const leadingIconNode =
      scopedTopic && !suppressAgentAvatar ? (
        <AgentAvatar
          agentId={scopedTopic.agentId}
          name={scopedTopic.agentName || scopedTopic.agentTitle || undefined}
          shape={'circle'}
          size={20}
          title={scopedTopic.agentName || scopedTopic.agentTitle || undefined}
          avatar={
            scopedTopic.agentAvatar ||
            (activeAgentId === inboxId ? DEFAULT_INBOX_AVATAR : undefined)
          }
        />
      ) : author ? (
        <TopicCreatorAvatar
          botCreator={metadata?.botCreator}
          corner={ownIconNode}
          userId={creatorUserId}
        />
      ) : (
        (ownIconNode ?? idleIconPlaceholder)
      );

    const navItem = (
      <TopicItemContextMenu fav={fav} id={id} status={status} title={title}>
        <NavItem
          draggable
          titleMarquee
          active={isTopicActive}
          description={workingDirectoryNode}
          href={href}
          icon={leadingIconNode}
          title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}
          titleColor={cssVar.colorText}
          actions={() => (
            <Actions
              fav={fav}
              id={id}
              // Archiving a topic mid-run would hide work that is still going.
              showInlineArchive={!shouldShowRunningIcon}
              status={status}
              title={title}
            />
          )}
          extra={
            <>
              {scopedTopic && !suppressAgentAvatar && ownIconNode}
              <TopicMigrationIndicator agentId={activeAgentId} topicId={id} />
              {/* Gated on the SAME boolean that draws the running ring: both say
                  "this row is visibly running", and a row that stopped spinning
                  must not keep counting. The server `runStartedAt` fallback only
                  knows the persisted `running` status, which outlives the answer
                  β€” it stays set through the post-visible-output tail where the
                  ring is deliberately masked (#16518) and the terminal
                  bookkeeping can run for tens of seconds. */}
              {shouldShowRunningIcon && (
                <RunningElapsedTime
                  agentId={activeAgentId}
                  runStartedAt={runStartedAt}
                  topicId={id}
                />
              )}
            </>
          }
          slots={
            workingDirectoryNode ? { iconBelow: draftBelowIcon } : { titlePrefix: draftPrefix }
          }
          onClick={handleClick}
          onDragStart={handleDragStart}
        />
      </TopicItemContextMenu>
    );

    return (
      <Flexbox
        data-testid="topic-item"
        data-topic-id={id}
        style={{ position: 'relative' }}
        {...hoverPrefetchHandlers}
      >
        {metaCard ? (
          <Popover
            arrow={false}
            content={<MetaHoverCard metadata={metadata} title={title} />}
            mouseEnterDelay={0.8}
            placement={'right'}
            styles={META_HOVER_CARD_STYLES}
            trigger={'hover'}
          >
            <div>{navItem}</div>
          </Popover>
        ) : (
          navItem
        )}
        {isMobileSurface() && showThreadList && id && (
          <Suspense
            fallback={
              <Flexbox gap={8} paddingBlock={8} paddingInline={24} width={'100%'}>
                <Skeleton height={18} width={'100%'} />
                <Skeleton height={18} width={'100%'} />
              </Flexbox>
            }
          >
            <Flexbox style={{ paddingInlineStart: NESTED_THREAD_LIST_INDENT }} width={'100%'}>
              <ThreadList topicId={id} />
            </Flexbox>
          </Suspense>
        )}
      </Flexbox>
    );
  },
);

TopicItemRow.displayName = 'TopicItemRow';

/**
 * Route awareness is resolved here rather than inside the row so that a
 * navigation re-renders only this thin shell. `useTopicNavigation` subscribes to
 * the pathname *and* to the chat store, so keeping it in the row made every
 * visible topic re-render its whole subtree twice per topic switch β€” with no
 * prop change to show for it. The row now takes plain booleans and bails out.
 *
 * The callbacks go through a ref because their identity changes on every
 * navigation; passing them as props would defeat the row's memo.
 */
const TopicItem = memo<TopicItemProps>((props) => {
  const { id } = props;
  const scope = useTopicListScope();
  const {
    focusTopicPopup,
    navigateToTopic,
    isInAgentSubRoute,
    isInTopicContextRoute,
    routeTopicId,
    urlTopicId,
  } = useTopicNavigation();

  // Active/thread state is subscribed here instead of arriving as props:
  // threading it through the group accordion re-rendered every group (and its
  // motion chain) on each topic switch, when only the two affected rows change.
  const active = useChatStore((s) => (id ? s.activeTopicId === id : !s.activeTopicId));
  const hasActiveThread = useChatStore((s) => !!s.activeThreadId);

  const navRef = useRef<TopicNavigationActions>({ focusTopicPopup, navigateToTopic });
  useEffect(() => {
    navRef.current = { focusTopicPopup, navigateToTopic };
  }, [focusTopicPopup, navigateToTopic]);

  const isRouteTopicActive = Boolean(id && routeTopicId === id && isInTopicContextRoute);

  return (
    <TopicItemRow
      {...props}
      defaultTopicActive={Boolean(active && !isInAgentSubRoute && !isInTopicContextRoute)}
      navRef={navRef}
      showThreadList={Boolean(!scope && id && id === urlTopicId)}
      isTopicActive={Boolean(
        (scope ? isRouteTopicActive : active || isRouteTopicActive) &&
        !hasActiveThread &&
        (!isInAgentSubRoute || isRouteTopicActive),
      )}
    />
  );
  // A list refresh rebuilds every topic/metadata object even when only one
  // topic changed β€” deep-compare props so unchanged rows still bail out.
}, isEqual);

TopicItem.displayName = 'TopicItem';

export default TopicItem;