Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

416 KB
Raw Blame
import { VideoSitePreview } from './VideoSitePreview';
import { InlineVideoPlayer } from './InlineVideoPlayer';
import { youtubeVideo } from '@cindy/maker-shared/rich-answer';
import { richVisualStyle, splitRichAnswer, richAnswerText, richMediaSource, richMarkdown, richString, type RichNode } from '@cindy/maker-shared/rich-answer';
import { RichAnswer } from './RichAnswer';
import { readFailedImageDelivery, readToolProcessMedia, readToolProcessText } from '@cindy/maker-shared/tool-process-media';
import { PluginCardActions } from '@/plugins/PluginCardActions';
import { McpAppCard } from './McpAppCard';
import { RichContentContext } from './richContentContext';
import { RichContentRuntime } from './richContentRuntime';
import { MessageListVisibility, MessageListVisibilityContext, useMessageListItemVisible } from './messageListVisibility';
import { CompanionLearningFooter } from './CompanionLearningFooter';
import { CompanionTaskResultCard } from './CompanionTaskResultCard';
import { botTaskResultKey, readBotTaskResults } from '@cindy/maker-shared/botCollaboration';
import type { ErrorDiagnosisSource } from './errorDiagnosisPrompt';
import { AgentErrorDetails } from './AgentErrorDetails';
import { ErrorNotice } from '@/components/ErrorNotice';
import { FileTypeIcon } from '@/components/FileTypeIcon';
import { CompanionMessageActions } from './CompanionMessageActions';
import { MarkdownCodeCopyButton } from './MarkdownCodeCopyButton';
import { BotGroupQuote } from './BotGroupQuote';
import { companionReplyQuoteDisplay, companionReplyQuoteFor } from './companionReplyQuote';
import type { ChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';
import { useMessageHistoryActive, useMessageHistoryPositioning } from './messageHistoryActivity';
import { usePaneViewport } from '@/platform/AdaptiveWindowContext';
import { messageReadingPosition } from './messageReadingPosition';
import { PluginInvocationHeader } from './PluginInvocationHeader';
import { companionPluginWorkEntries, type PluginInvocation } from './pluginInvocations';
import { useAuth } from '@/auth/AuthContext';
import { downloadRemoteMediaShareTemp } from './remoteMediaDiskCacheExpo';
import { usePluginResultCard } from './usePluginResultCard';
import { extractPayloadToolResultMedia, managedToolMediaKind } from '@cindy/maker-shared/payload-summary';
import { AuthorizationMessageCard } from './AuthorizationMessageCard';
import { collectBotMessageTimeGroups, formatBotMessageGroupTime, type BotTimelineMessage } from '@cindy/maker-shared/botTimeline';
import { CompanionMessageCard } from '@/session/CompanionMessageCard';
import { CompanionEntering } from '@/session/CompanionEntering';
import { LOCAL_SEND_FRESH_MS, localSendStartedAt } from '@/session/localSendMotion';
import { mobileDebugEnabled, mobileDebugLog } from '@/debug/mobileDebugLog';
import { createScrollDebugSampler } from '@/debug/scrollDebugSampler';
import { errorText, resolvedUrlKind } from '@/debug/fileDiagnostics';
import { createContext, Fragment, memo, useId, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type Dispatch, type ReactElement, type ReactNode, type SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
import { MessageLoadingImage, MessageImagePlaceholder } from './MessageLoadingImage';
import { InputHandoffRecordRow } from '@/inputHandoff/InputHandoffRecordRow';
import {
  ArrowLeftRight,
  Bot,
  Check,
  ChevronDown,
  ChevronRight,
  Circle,
  CircleAlert,
  CircleCheck,
  CircleDashed,
  CircleStop,
  Copy,
  Ellipsis,
  ExternalLink,
  Ghost,
  Layers,
  ListTodo,
  LoaderCircle,
  MessageSquare,
  Monitor,
  RefreshCw,
  PencilLine,
  Share as ShareIcon,
  Send,
  Smartphone,
  Split,
  Sparkles,
  Timer,
  Trash2,
  TriangleAlert,
  Undo2,
  X,
} from 'lucide-react-native';
import {
  AccessibilityInfo,
  ActivityIndicator,
  Alert,
  Animated,
  Easing,
  Linking,
  Modal,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  StatusBar,
  useWindowDimensions,
  View,
  type GestureResponderEvent,
  type NativeScrollEvent,
  type NativeSyntheticEvent,
  type ScrollViewProps,
  type LayoutChangeEvent,
  type StyleProp,
  type TextStyle,
  type ViewStyle,
} from 'react-native';
import { UITextView } from 'react-native-uitextview';
import {
  LegendList,
  useRecyclingState,
  type LegendListMetrics,
  type OnViewableItemsChangedInfo,
  type LegendListRef,
} from '@legendapp/list/react-native';
import { tokenizeCode, type CodeTokenKind } from '@/session/codeHighlight';
import { buildComposerTouchLayout } from '@/session/composerTouchLayout';
import { useFoldableExpandedState } from '@/session/expandedBlockMemory';
import {
  joinChatQuoteTextSegments,
  parseChatQuoteSegments,
  type ChatQuote,
} from '@cindy/maker-shared/chat-quotes';
import { formatCompactTokens } from '@cindy/maker-shared/usage-format';
import { QuoteCapsule } from '@/session/QuoteCapsule';
import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
import { motionDuration, motionEasing } from '@/theme/tokens';
import { mobileAgentLabelFromUnknown } from '@/session/sessionAgentSwitch';
import {
  NativePullDownMenu,
  showActionMenu,
  usesNativePullDownMenu,
  usesSystemActionMenu,
} from '@/platform/chrome';
import { MessageActionSheet } from '@/session/MessageActionSheet';
import { buildMobileMessageMenu, type MobileMessageMenuActionId } from '@/session/messageActionMenu';
import { isShareableMessage } from '@/session/shareSelectionStore';
import {
  ShareMessageCheckbox,
  useCancelShareSelectionRowTap,
  MessageBodyText,
} from '@/session/ShareMessageCheckbox';
import { SentInlineAtomBody } from '@/session/SentInlineAtomBody';
import { selectableTextVerticalOffset } from '@/session/selectableTextAlignment';
import {
  composerDocumentFromSerializedMessage,
  type ComposerDocument,
} from '@/session/composerDocument';
import {
  buildVisibleSentInlineTokens,
  sentInlineTokensDisplayText,
  type SentInlineToken,
} from '@/session/sentMessageAtoms';
import {
  selectionQuoteMenuLabel,
  SelectionQuoteContext,
  handleSelectionQuoteMenuAction,
} from '@/session/selectionQuote';
import { SelectionMenuText } from '@/session/SelectionMenuText';
import {
  MOBILE_COMPOSER_CONTROL_SIZE,
  MOBILE_COMPOSER_VOICE_ANCHOR_RIGHT,
} from '@/session/MobileComposerInputRow';
import { MAX_FONT_SIZE_MULTIPLIER, Text } from '@/components/AppText';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import type {
  NormalizedAttachment,
  NormalizedRemoteMessage,
  NormalizedToolDiff,
  NormalizedToolMedia,
} from '@/session/messageNormalize';
import type {
  MobileToolInputDetail,
  MobileToolInputProjection,
} from '@/session/messageToolPayloadProjection';
import {
  buildAttachmentPayload,
  buildDiffPayload,
  buildFilePayload,
  buildMediaPayload,
  buildMermaidPayload,
  buildTextPayload,
  buildToolResultPayload,
  formatDiffPayloadView,
  payloadMediaKindLabel,
  summarizeMessagePayloadBody,
  summarizeMessagePayloadPreview,
  summarizeMessagePayload,
  type FormattedDiffPayloadLine,
  type MessagePayload,
  type MessagePayloadPreview,
} from '@/session/messagePayload';
import { partitionMessageAttachments, svgAttachmentForDisplay } from '@/session/messageAttachments';
import {
  AUTOMATION_USER_MESSAGE_COLLAPSED_LINES,
  AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
  LONG_USER_MESSAGE_COLLAPSED_LINES,
  LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
  mayExceedVisualLineThreshold,
  resolveUserMessageCollapse,
} from '@/session/userMessageCollapse';
import {
  collectMobileMessageGalleryImages,
  galleryImageIndexForPayload,
  isLightboxMediaKind,
  lightboxImagesForPayload,
  type MobileMessageGalleryImage,
} from '@/session/messageGallery';
import {
  applySentAttachmentThumbOverlay,
  getSentAttachmentThumbUri,
  useSentAttachmentThumbsVersion,
} from '@/session/sentAttachmentThumbStore';
import type { GetSentMessageImagePreview, SentMessageImagePreview } from '@/session/sentMessageImagePreviews';
import {
  buildMobileMessageCopyText,
  copyMessageText,
  formatMessageAbsoluteTime,
  formatMessageRelativeTime,
  formatMessageTurnCost,
  formatMessageTurnTokens,
  formatModelShortLabel,
  mobileMessageShowsActionBar,
  writeClipboardText,
  type MobileMessageControlActionId,
  type CopyMessageStatus,
} from '@/session/messageActions';
import {
  describeTextPreviewFailure,
  remoteFilePreviewKind,
  textPreviewStatusText,
  type TextFilePreviewState,
} from '@/session/filePreview';
import {
  groupMobileMarkdownSelectableBlocks,
  mobileMarkdownManagedImagePreviewUrl,
  isMobileMarkdownImageDirectUrl,
  mobileMarkdownImageAltChipText,
  mobileMarkdownImageTitle,
  mobileMarkdownImageUrlForWorkdir,
  mobileMarkdownInlineImageSize,
  parseMobileMarkdownIncremental,
  parseMobileMarkdownInlines,
  type MobileMarkdownParseResult,
  type MobileMarkdownBlock,
  type MobileMarkdownBlockGroup,
  type MobileMarkdownInline,
  type MobileMarkdownInlineMark,
  type MobileMarkdownTextRunGroupingOptions,
} from '@/session/messageMarkdown';
import { MarkdownBlockContent } from '@/session/MarkdownBlockContent';
import { useMarkdownSessionLinkTitles } from '@/session/useMarkdownSessionLinkTitles';
import {
  isCindyDeepLinkUrl,
  parseProjectDeepLinkUrl,
  parseSessionDeepLinkUrl,
  projectDisplayName,
  type SessionDeepLinkTarget,
} from '@/session/sessionLinks';
import {
  chatPathLabelReadsAsFileReference,
  classifyChatPathLinkTarget,
  classifyInlineCodePathCandidate,
} from '@/session/chatPathCandidate';
import { ChatFilePathContext } from '@/session/chatFilePathContext';
import { MailLinkSpan } from '@/session/MailLinkSpan';
import { ChatPathChipSpan } from '@/session/ChatPathChipSpan';
import {
  useRemoteDeviceIdentity,
  useRemoteSessionMessages,
} from '@/session/remoteSessionStore';
import {
  isCrossDeviceSourceSessionId,
  shouldShowSourceDevice,
  type MessageSourceDevice,
  type MessageSourcePlugin,
} from '@cindy/maker-shared/message-source';
import {
  automationOriginLabel,
  imSourceHeaderTitle,
  sessionOriginLabel,
  sourceDeviceLabel,
  sourceIdText,
  sourcePluginLabel,
} from '@/session/messageSourceLabels';
import {
  mobileSessionMessageDisplayText,
  sentSessionMessageChipLabel,
} from '@/session/sessionMessageText';
import { buildMobileMarkdownTableColumnWidths } from '@/session/messageTableLayout';
import { buildPayloadHeaderLayout, buildPayloadModalSafeArea } from '@/session/payloadHeaderLayout';
import { buildPayloadBodyLayout, type PayloadBodyLayout } from '@/session/payloadBodyLayout';
import {
  buildMessageHierarchyLayout,
  type MessageHierarchyLayout,
} from '@/session/messageHierarchyLayout';
import {
  buildMessageContentLayout,
  nextSettledContentWidth,
  type MessageContentLayout,
} from '@/session/messageContentLayout';
import { buildMobileReadableViewportLayout } from '@/session/responsiveViewportLayout';
import {
  type MobileAgentTaskItem,
  type MobileMessageItem,
  type MobileMessageRenderItem,
  type MobileThinkingItem,
  type MobileTodoCardItem,
  type MobileTodoItem,
  type MobileSubagentGroupItem,
  type MobileToolGroupItem,
  type MobileToolMediaItem,
  type MobileWorkChildItem,
  type MobileWorkGroupItem,
} from '@/session/messageRenderModel';
import {
  PendingSendBubble,
  type PendingSendBubbleActions,
} from '@/session/PendingSendBubble';
import { buildMobileMessageListExtraData } from '@/session/pendingSendItems';
import { dedupeToolMediaByUrl } from '@cindy/maker-shared/message-render';
import { tokenizeThinkingText } from '@cindy/maker-shared/thinking-text';
import {
  buildAgentTaskCardModel,
  type AgentTaskCardModel,
  type AgentTaskStatus,
} from '@cindy/maker-shared/agent-task';
import {
  buildMessageActionBarPresentation,
  formatToolRowText,
  summarizeMessageBubblePresentation,
  summarizeTodoCardPresentation,
  summarizeToolGroupPresentation,
  summarizeToolRowPresentation,
  summarizeWorkGroupPresentation,
  todoStatusPresentation,
  type MessageActionBarItemId,
  type ToolRowPresentation,
  type ToolRowStatus,
} from '@/session/messagePresentation';
import {
  formatRemoteMediaSize,
  mediaLoadFailureKey,
  isDesktopLocalMediaUrl,
  isDirectPreviewableMediaUrl,
  type MobileResolvedRemoteMedia,
  type ResolveRemoteMediaFn,
} from '@/session/remoteMedia';
import {
  attachmentImageDisplaySize,
  mediaThumbnailPhase,
  shouldAutoResolveMediaThumbnail,
  type AttachmentImageIntrinsicSize,
  type MediaThumbnailResolveState,
} from '@/session/mediaThumbnail';
import { RemoteMediaPlayerWebView } from '@/session/mediaPlayerWebView';
import type {
  MobileMediaPlayerKind,
  MobileMediaPlayerStatus,
} from '@/session/mediaPlayerWebViewHtml';
import { formatAgentSwitchLocationLabel, formatMobileSystemCard } from '@/session/systemCard';
import { MobileBoundaryNotice } from '@/session/MobileBoundaryNotice';
import {
  getMobileAutoResumePresentation,
  isMobileAutoResumeRowInFlight,
  toggleMobileAutoResumeExpanded,
} from '@/session/autoResumePresentation';
import type { ContinuationInFlightProjectionCapability } from '@/session/types';
import {
  projectMobileWorkActivities,
  projectRecentMobileWorkActivities,
  type MobileProjectedToolActivity,
  sameMobileWorkToolActivity,
} from '@/session/workActivityProjection';
import { logUnhandledRenderItem } from '@/session/assertNever';
import type { OrcaCollabCard as OrcaCollabCardModel } from '@/session/orcaCollab';
import {
  buildMessageLoadEarlierAction,
  evaluateMessageWindowUpdate,
  MOBILE_ANCHOR_VERIFY_TOLERANCE,
  mobileLoadEarlierPrefetchThreshold,
  mobileMessageListKeysSignature,
  mobileMvcpSettleDeadline,
  mobileMessageListTopPadding,
  MOBILE_FOLLOW_UNPIN_DRAG_DEAD_ZONE,
  MOBILE_MESSAGE_LIST_BOTTOM_PADDING,
  type MessageScrollMetrics,
  mobileMessageListBottomPadding,
  resolveMobileNearBottomOnScroll,
  shouldAutoLoadEarlier,
  shouldPreserveMobileHistoryBrowseIntent,
  shouldUnpinMobileFollowOnDrag,
  mobileMessageListNearBottomThreshold,
} from '@/session/messageScroll';
import { createMobileTailFollower, type MobileTailFollower } from '@/session/messageTailFollower';
import {
  captureMobileHistoryAnchor,
  isMobileHistoryAnchorSettled,
  mobileHistoryAnchorCorrectionStatus,
  mobileHistoryPrependUsesAppOwnedAnchor,
  mobileHistoryTopOffsetAdjustment,
  resolveMobileHistoryAnchorOffset,
  type MobileHistoryAnchor,
  type MobileHistoryAnchorPendingCorrection,
  type MobileHistoryAnchorResolveState,
} from '@/session/messageHistoryAnchor';
import {
  mobileMessageHistoryAnchorIdentity,
  mobileMessageHistoryOnlyExpandedFirstWorkGroup,
  mobileMessageHistoryRowKeyByIdentity,
} from '@/session/messageHistoryAnchorIdentity';
import { ImageLightbox, type ImageLightboxAnnotationConfig } from '@/session/ImageLightbox';
import {
  MermaidDiagramWebView,
  writeMermaidExportPngTemp,
  type MermaidDiagramWebViewHandle,
} from '@/session/mermaidWebView';
import { MathFormulaWebView } from '@/session/mathWebView';
import { getMobileMessageWebViewMetrics } from '@/session/mobileMessageWebViewMetrics';
import {
  getMobileMarkdownRenderMetrics,
  recordMobileMarkdownParse,
  recordMobileMessageRenderItem,
} from '@/session/mobileMarkdownRenderMetrics';
import { latexToUnicodeApproximation } from '@cindy/maker-shared/math-markdown';
import type { RemoteTextFilePreviewResult } from '@/device-link/mobileMakerTransport';
import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
import { iconSize, iconStroke, monoFont, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { useUserBubbleAppearance } from '@/theme/userBubblePreference';
import { isOwnUserBubble } from './userBubbleOwnership';
import { i18n } from '@/i18n';
import { formatLocalizedDuration } from '@/session/sessionDurationFormat';
import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';
import { mobileToolRowWording } from '@/i18n/toolWording';
import type { HistoryWorkLine } from '@cindy/maker-shared/message-window';

const MESSAGE_CONTROL_HIT_SLOP = { bottom: 10, left: 10, right: 10, top: 10 };
const MESSAGE_CONTROL_TOUCH_SIZE = 44;
const MESSAGE_LIST_VISIBLE_PERCENT_THRESHOLD = 5;
const MESSAGE_LIST_VIEWABILITY_CONFIG_ID = 'message-heavy-content';

// Heavy Markdown blocks inherit the visibility of their outer list cell. Nested
// work/sub-agent cards should not create a second visibility window of their own.
const MessageHeavyContentVisibilityContext = createContext(true);
const MarkdownRemoteMediaContext = createContext<ResolveRemoteMediaFn | undefined>(undefined);

/** 分享模式吸顶 check 与行内 check 共用 44px 触达高度。 */
const SHARE_STICKY_CHECK_HEIGHT = 44;
const STICKY_SHARE_CHECK_THROTTLE_MS = 150;
// LegendList 变高 item 的初始估高(仅影响首帧布局定位,LegendList 挂载后按实测尺寸修正)。
/** Bound the hidden initial correction so live measurement churn cannot blank the list for seconds. */
const MOBILE_INITIAL_REVEAL_MAX_MS = 300;
/** Maximum time a native imperative scroll may be reported as in-flight. */
const MOBILE_PROGRAMMATIC_SCROLL_SETTLE_MS = 1000;
/** Animated jump-to-latest commands get a little more time to settle. */
const MOBILE_PROGRAMMATIC_ANIMATED_SCROLL_SETTLE_MS = 1400;
/** Cold-open history fill is useful, but bounded so a short/duplicate host page cannot drain history forever. */
const MAX_INITIAL_HISTORY_AUTOFILL_PAGES = 3;
// Keep the initial pool large enough for short message/work-group rows. An
// overestimate forces on-demand container growth during a fast fling, which is
// both a mount spike and a DEV LogBox update in the middle of Fabric commits.
const MOBILE_MESSAGE_ESTIMATED_ITEM_SIZE = 100;
/** Manual prepend anchoring retries layout positions for at most ~3 seconds, even under resize churn. */
const MOBILE_HISTORY_ANCHOR_VERIFY_MAX_FRAMES = 180;
const MOBILE_HISTORY_ANCHOR_VERIFY_MAX_MS = 3000;
const MOBILE_HISTORY_ANCHOR_STABLE_FRAMES = 2;
const MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR = mobileHistoryPrependUsesAppOwnedAnchor(
  Platform.OS,
);
const MOBILE_SCROLL_HISTORY_EVALUATION_INTERVAL_MS = 64;
const ANDROID_SELECTABLE_TEXT_RUN_MAX_BLOCKS = 12;
const ANDROID_SELECTABLE_TEXT_RUN_MAX_UTF16_LENGTH = 1800;
const ANDROID_SELECTABLE_TEXT_RUN_MAX_INLINE_FRAGMENTS = 20;
const ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS: MobileMarkdownTextRunGroupingOptions = {
  maxTextRunBlocks: ANDROID_SELECTABLE_TEXT_RUN_MAX_BLOCKS,
  maxTextRunUtf16Length: ANDROID_SELECTABLE_TEXT_RUN_MAX_UTF16_LENGTH,
  maxTextRunInlineFragments: ANDROID_SELECTABLE_TEXT_RUN_MAX_INLINE_FRAGMENTS,
};
// LegendList 预渲距离(px,视口外每侧):约 1 屏,挂载集小 → 滚动 mount 帧压进一帧内(见 listperf 实测)。
const MOBILE_MESSAGE_DRAW_DISTANCE = 800;
const FOLDABLE_HEADER_HIT_SLOP = { bottom: 10, left: 4, right: 4, top: 10 };

function mobileMessageListItemType(item: MobileMessageRenderItem): MobileMessageRenderItem['type'] {
  // A confirmed local send keeps the same logical row as its optimistic bubble.
  // Reusing the message pool preserves the measured height while the item data
  // changes from pending_send to the persisted message.
  return item.type === 'pending_send' ? 'message' : item.type;
}

function resolveMobileMessageHistoryAnchorOffset(
  anchor: MobileHistoryAnchor,
  state: MobileHistoryAnchorResolveState,
  topOffsetAdjustment: number,
): number | null {
  return resolveMobileHistoryAnchorOffset(anchor, {
    ...state,
    topOffsetAdjustment,
    keyByIdentity: state.data
      ? (identityKey) => mobileMessageHistoryRowKeyByIdentity(
        state.data as readonly MobileMessageRenderItem[],
        identityKey,
      )
      : undefined,
  });
}

interface MobileHistoryPrependTransaction {
  anchor: MobileHistoryAnchor | null;
  anchorStable: boolean;
  continueAfterRegroup: boolean;
  generation: number;
  pageCommitted: boolean;
  pendingCorrection: MobileHistoryAnchorPendingCorrection | null;
  promiseSettled: boolean;
  startItems: readonly MobileMessageRenderItem[];
  startProgressKey: string | null;
  userInitiated: boolean;
  userControlledAfterCommit: boolean;
  userControlledDuringRequest: boolean;
  userHandoffPending: boolean;
  verifyDeadlineAt: number;
}
// 「跳到底部」浮标直径:比 composer 里的语音按钮(28)大一档但不压过它,Telegram 同款层级感。
const SCROLL_TO_BOTTOM_FAB_SIZE = 36;
const stylesStatic = StyleSheet.create({
  compactActivityIndicator: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  workActivityIconSlot: {
    alignItems: 'center',
    height: lineHeight.bodySmall,
    justifyContent: 'center',
    width: iconSize.md,
  },
});

/**
 * 消息正文可选中文本块的双端实现:
 * - iOS:RN 官方 Text 底层是 UILabel,selectable 只有「长按拷贝整块」、没有系统选择手柄
 *   (部分选择做不到,facebook/react-native#13938)。换用 react-native-uitextview
 *   (Bluesky 开源,真 UITextView):长按出系统手柄、支持块内部分选择,嵌套 span 样式与 onPress 保留。
 * - Android:RN Text selectable 本身就有系统选择手柄,维持 AppText(带全局字体缩放限幅)。
 * 选中高亮双端都刻意**不**覆写 selectionColor,交给系统:iOS UITextView 本就用系统高亮;
 * Android 不传则回落 Activity 主题的 textColorHighlight(accent 色 ~26% 透明度的半透明
 * tint),选区可见性与选中文字可读性天然兼得。历史教训(#1427):曾逐 view 覆写不透明
 * token —— surfaceChip 近白,浅色主题选区与底色仅 1.04:1,选了看不见;换 inputCaret 纯蓝,
 * 选中文字对比度跌到 2.6:1,看得见但读不了 —— 不透明覆写两头都讨不到好。props 类型
 * Omit 掉 selectionColor 挡编译期,messageSelectionHighlight.test.ts 锁文件级不再覆写。
 */
type MarkdownSelectableTextProps = Omit<ComponentProps<typeof Text>, 'selectionColor'> & {
  /**
   * iOS 是否使用可部分选中的 UITextView。普通任务的超长展开正文回退 RN Text:
   * UITextView 在折叠→展开时骤增为超高复用视图会偶发只留下巨高空白容器。
   */
  allowIosUITextView?: boolean;
  /** Decorated table cells must stay on the row grid, including their borders. */
  adjustVerticalAlignment?: boolean;
  /** Include larger inline headings when aligning a combined text run. */
  alignmentTextStyles?: readonly StyleProp<TextStyle>[];
};

function MarkdownSelectableText({
  allowIosUITextView = true,
  adjustVerticalAlignment = true,
  alignmentTextStyles,
  selectable,
  ...rest
}: MarkdownSelectableTextProps) {
  // chat-text-quote:宿主(MessageRenderer)启用采集时,给 iOS UITextView 传
  // menuActionLabel(系统选择菜单里插入「添加到对话」项,iOS 16+)并挂
  // onTextLayout(缓存逐行渲染文本)+ onMenuAction(菜单点按时按选区偏移切
  // 文本提交)。context 为 null(宿主未启用 / 非会话场景)时零开销走原路径。
  const quoteCtx = useContext(SelectionQuoteContext);
  const renderedLinesRef = useRef<readonly string[]>([]);
  const { fontScale } = useWindowDimensions();
  if (selectable && allowIosUITextView && Platform.OS === 'ios') {
    const typography = [rest.style, ...(alignmentTextStyles ?? [])]
      .map((style) => StyleSheet.flatten(style) ?? {});
    const top = selectableTextVerticalOffset(typography, rest.allowFontScaling === false ? 1 : fontScale);
    // Position only the selectable root. RN Text already centers its leading;
    // shifting the bubble itself would also shift pending/Android text and chips.
    const alignedStyle: StyleProp<TextStyle> = adjustVerticalAlignment ? [rest.style, { top }] : rest.style;
    if (!quoteCtx) {
      return (
        <UITextView
          maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER}
          selectable
          uiTextView
          {...rest}
          style={alignedStyle}
        />
      );
    }
    return (
      <UITextView
        maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER}
        selectable
        uiTextView
        {...rest}
        style={alignedStyle}
        onTextLayout={(e) => {
          // uitextview 自定义 spec 的 lines 是 string[](RN 核心 Text 是对象数组),
          // 双形态防御:确保缓存的是纯字符串行。
          const rawLines = e.nativeEvent.lines as unknown as readonly (string | { text: string })[];
          renderedLinesRef.current = rawLines.map((line) => (typeof line === 'string' ? line : line.text));
          rest.onTextLayout?.(e);
        }}
        // menuActionLabel / onMenuAction 是 uitextview patch 的扩展 prop,不在
        // RN Text props 里,组件内部私有附加(经 {...rest} 透传到原生组件)。
        {...{
          menuActionLabel: selectionQuoteMenuLabel(),
          sideChatMenuActionLabel: quoteCtx.askInSideChat ? i18n.t('session.sideChat.title') : '',
          onMenuAction: (event: { nativeEvent: { target: number; start: number; end: number } }) => {
            handleSelectionQuoteMenuAction(event, renderedLinesRef.current, quoteCtx);
          },
          onSideChatMenuAction: (event: { nativeEvent: { target: number; start: number; end: number } }) => {
            handleSelectionQuoteMenuAction(event, renderedLinesRef.current, quoteCtx, 'side-chat');
          },
        }}
      />
    );
  }
  return <SelectionMenuText selectable={selectable} {...rest} />;
}

/**
 * iOS 可选中块里的嵌套 span:必须也是 UITextView(经库内祖先上下文渲染为原生 child),
 * 混入 RN Text 会破坏原生文本树。仅由 renderInline 在「块可选中且 iOS」时使用。
 */
function MarkdownSelectableSpan(props: ComponentProps<typeof Text>) {
  const cancelShareSelectionRowTap = useCancelShareSelectionRowTap();
  const handlePress = props.onPress
    ? (event: GestureResponderEvent) => {
      cancelShareSelectionRowTap?.();
      props.onPress?.(event);
    }
    : undefined;
  return (
    <UITextView
      maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER}
      {...props}
      onPress={handlePress}
    />
  );
}

function isTextRunContinuationGroup(group: MobileMarkdownBlockGroup): boolean {
  return group.type === 'text_run' && group.textRunContinuation === true;
}

/** Composer-ready user message body with product quotes kept out of raw text. */
export interface MobileMessageDraft {
  document: ComposerDocument;
  text: string;
  quotes: readonly ChatQuote[];
  /** marker 不进入可见输入框;未编辑时用这份原文保证 quote / prose 顺序不变。 */
  orderedBody?: string;
}

export type MobileMessageActionBusyKind = 'fork' | 'rewind' | 'delete';

/** Desktop BotAvatar `sm` beside teammate replies; exported so the host renders a matching portrait. */
export const COMPANION_AVATAR_SIZE = 28;
const COMPANION_AVATAR_GAP = 10;

/** 伙伴私聊引用回复与「回复对应的消息」(docs/product-rules/cindy-bots-runtime.md)。 */
export interface CompanionQuoteOptions {
  names: { owner: string; companion: string };
  /** 「显示回复对应的消息」本机偏好。 */
  showReplyTargets: boolean;
  /** Put a quote of this message above the composer. */
  onQuote: (quote: ChatReplyQuote) => void;
  /** Scroll to and highlight a message of this chat, loading it first when needed. */
  onLocate: (clientId: string) => void;
}

interface CompanionQuoteActions extends CompanionQuoteOptions {
  /** The message as this chat has it loaded; reads the latest list without re-rendering every row. */
  getMessage: (clientId: string) => NormalizedRemoteMessage | undefined;
  /** Whether `assistantClientId` is the last loaded reply of the turn it answers. */
  isLastReplyFor: (assistantClientId: string) => boolean;
}

interface MessageActions {
  onRetryImageDelivery?: (imageId: string) => Promise<void>;
  companion?: boolean;
  companionQuoteActions?: CompanionQuoteActions;
  onCompanionReadThrough?: (at: number) => void;
  onOpenCompanionSettings?: (page: 'memory' | 'capabilities') => void;
  companionWorkingLabel?: string | null;
  /** Teammate portrait beside its replies (Desktop withAssistantAvatar). */
  companionAvatar?: ReactNode;
  /** First visible message of each five-minute teammate time group → its timestamp. */
  companionTimeGroups?: ReadonlyMap<string, number>;
  companionPluginWork?: ReturnType<typeof companionPluginWorkEntries>;
  /** Partner chats keep the user's bubble plain; result and authorization cards remain independent. */
  showPluginInvocations?: boolean;
  /** Device hosting plugin results; independent of a filesystem workdir. */
  remoteDeviceId?: string;
  /** 长按/操作条「复制消息链接」:复制该消息的会话深链(带 ?message= 锚点)。 */
  onCopyMessageLink?: (clientId: string) => void;
  /** Insert this message's anchored link as an atom in the active composer. */
  onAddMessageToComposer?: (clientId: string) => void;
  onSideChatMessage?: (text: string) => void;
  onDiagnoseError?: (error: ErrorDiagnosisSource) => void;
  /**
   * chat-text-quote:选中消息文字 → 系统选择菜单「添加到对话」项的采集回调
   * (会话页写入 chatQuoteStore)。未传时选区采集整体关闭(context 为 null,
   * 只读宿主零开销)。当前仅 iOS 16+ 生效(Android RN Text 无系统菜单扩展点)。
   */
  onQuoteSelection?: (quote: { text: string }) => void;
  onForkMessage?: (clientId: string, draft?: MobileMessageDraft) => void;
  onDeleteMessage?: (clientId: string) => void;
  onLoadEarlier?: () => void | Promise<void>;
  onOpenForkOrigin?: () => void;
  /** 「由任务「X」发送」来源标签点击:跳到同一设备上的来源任务。 */
  onOpenOriginSession?: (sessionId: string) => void;
  /**
   * 本机(这台手机)的 device-link 设备 id:设备来源标签只标「别的设备」发来的消息,
   * 本机发出的不标(shouldShowSourceDevice)。
   */
  viewerDeviceId?: string | null;
  /** 「从手机「X」发送」设备标签点击:打开设备详情;设备已删除时由宿主提示。 */
  onOpenSourceDevice?: (deviceId: string) => void;
  onOpenPayload?: (payload: MessagePayload) => void;
  /**
   * 带点击来源打开:sourceGroupKey 为点开时所在的顶层 render item key,看图器据此
   * 确定「同一条消息」的翻页范围。顶层列表项把 onOpenPayload 包成它(见
   * RenderListItemView),组件内照常调 onOpenPayload。
   */
  onOpenPayloadFromItem?: (payload: MessagePayload, sourceGroupKey: string) => void;
  onLoadToolInput?: (ref: MobileToolInputProjection) => Promise<MobileToolInputDetail>;
  /** 正文里会话深链 chip(xdt-maker://session/…)点击回调,app 内跳转。 */
  onOpenSessionLink?: (url: string) => void;
  onPreviewRewind?: (clientId: string, draft: MobileMessageDraft) => void;
  onEnterShareSelection?: (clientId: string) => void;
  onShareableMessageViewChange?: (clientId: string, view: View | null) => void;
  shareSelectionActive?: boolean;
  shareSelectionBusy?: boolean;
  /** 待发送气泡(pending_send 项)的展开态与队列操作回调。 */
  pendingSend?: PendingSendBubbleActions;
  getSentImagePreview?: GetSentMessageImagePreview;
  onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
  onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;
  onResolveRemoteMedia?: ResolveRemoteMediaFn;
  busyClientId?: string | null;
  busyAction?: MobileMessageActionBusyKind | null;
  canLoadEarlier?: boolean;
  loadingEarlier?: boolean;
  screenWidth?: number;
  /** 会话是否流式中:驱动工具行 running/done 状态(未 settled 且流式中才显示进行中)。 */
  isSessionStreaming?: boolean;
  /** 当前 maker vendor turn 是否仍在运行;旧端续跑归属兜底只允许使用这条窄信号。 */
  makerTurnRunning?: boolean;
  /** 当前 vendor turn 的自动续跑 owner。 */
  continuationTurnClientId?: string | null;
  /** 只有明确识别为 legacy 的投影才允许使用最后一条输入的兼容判据。 */
  continuationInFlightProjectionCapability?: ContinuationInFlightProjectionCapability;
  /** 含自动续跑合成行、排除 steer 的最后一条用户输入。 */
  lastUserInputClientId?: string | null;
}

export function MessageRenderer({
  companion = false,
  companionQuote,
  companionWorkingLabel,
  onOpenCompanionSettings,
  companionAvatar,
  companionPluginInvocations,
  showPluginInvocations = true,
  remoteDeviceId,
  topOverlayHeight,
  focusedItemKey,
  followLatestRequestKey,
  items,
  itemsStructureKey,
  onCopyMessageLink,
  onAddMessageToComposer,
  onSideChatMessage,
  onDiagnoseError,
  onForkMessage,
  onDeleteMessage,
  onLoadEarlier,
  onLoadToolInput,
  onRetryImageDelivery,
  onOpenForkOrigin,
  onOpenOriginSession,
  viewerDeviceId,
  onOpenSourceDevice,
  onOpenSessionLink,
  onPreviewRewind,
  onEnterShareSelection,
  shareSelectionActive,
  shareSelectionBusy,
  onQuoteSelection,
  pendingSend,
  pendingSendGroupKeys,
  getSentImagePreview,
  onReadTextFilePreview,
  onReleaseRemoteMedia,
  onResolveRemoteMedia,
  onShareImage,
  imageAnnotation,
  busyClientId,
  busyAction,
  canLoadEarlier,
  emptyTestID,
  emptyMessage,
  bottomOverlayHeight,
  contentBottomInset,
  renderScrollComponent,
  isSessionStreaming,
  makerTurnRunning,
  continuationTurnClientId,
  continuationInFlightProjectionCapability,
  loadingEarlier,
  loadEarlierProgressKey,
  focusedRequestKey,
  queueFooter,
  scrollResetKey,
  isReadingPositionActive,
  onCompanionReadThrough,
  syncingWhileEmpty,
  testID,
  devExposeList,
  devRecycleItems = false,
}: {
  companion?: boolean;
  /** Companion private chats only; ordinary tasks keep their existing message actions. */
  companionQuote?: CompanionQuoteOptions;
  onOpenCompanionSettings?: (page: 'memory' | 'capabilities') => void;
  companionWorkingLabel?: string | null;
  companionAvatar?: ReactNode;
  companionPluginInvocations?: ReadonlyMap<string, PluginInvocation[]>;
  /** Offscreen preload and disappearing native screens must not replace the user's bookmark. */
  isReadingPositionActive?: () => boolean;
  bottomOverlayHeight?: number;
  /** 列表滚动容器;任务页用它让聊天记录往下拖到输入框顶边时交给输入框(composerPullThrough)。 */
  renderScrollComponent?: (props: ScrollViewProps) => ReactElement<ScrollViewProps>;
  /** Floating composers reserve a stable tail gap while their expanded surface overlays history. */
  contentBottomInset?: number;
  /** 顶部 chrome(绝对定位半透明工具栏)实测高度:内容顶部按此让位,详见 mobileMessageListTopPadding。 */
  topOverlayHeight?: number;
  focusedItemKey?: string | null;
  focusedRequestKey?: number | string | null;
  followLatestRequestKey?: number | string | null;
  items: readonly MobileMessageRenderItem[];
  /** Live outbox, queued and settling rows; an absent source cannot retain its viewer forever. */
  pendingSendGroupKeys?: ReadonlySet<string>;
  /** Stable while streaming only changes row content; structural list derivations key off this. */
  itemsStructureKey?: unknown;
  /** Oldest loaded host cursor; synthetic cards must not mask successful history prepends. */
  loadEarlierProgressKey?: string | null;
  emptyTestID?: string;
  emptyMessage?: string;
  /** 排队消息 inline 区(InlineQueueSection),渲染在最后一条消息之后、随内容滚动。 */
  queueFooter?: ReactNode;
  scrollResetKey?: string;
  /** 空列表且本次打开的首同步未完成:渲染「正在同步」占位(延迟显形防闪)而非「暂无消息」。 */
  syncingWhileEmpty?: boolean;
  testID?: string;
  /** DEV-only A/B override for listperf; regular screens match production and recycle rows. */
  devRecycleItems?: boolean;
  /** 全屏图片查看器的分享回调(由会话屏落地本地文件后唤起系统分享单)。 */
  onShareImage?: (
    media: Extract<MessagePayload, { kind: 'media' }>['media'],
    displayUri: string,
    mimeType?: string,
    /** 取件已知的对象字节数:分享落盘可据此跳过超预算的 LRU 写入。 */
    sizeBytes?: number,
  ) => void | Promise<void>;
  /** 全屏图片查看器的圈点标注配置(画笔 → 发送到对话;由会话屏接线附件管线)。 */
  imageAnnotation?: ImageLightboxAnnotationConfig;
  onEnterShareSelection?: (clientId: string) => void;
  shareSelectionActive?: boolean;
  shareSelectionBusy?: boolean;
  /** DEV-only:把内部列表控制器暴露给性能 harness 驱动自动滚动(临时,profiling/回归测量用)。 */
  devExposeList?: (api: {
    scrollTo: (y: number) => void;
    getMetrics: () => { contentHeight: number; offsetY: number; viewportHeight: number };
    getWebViewMetrics: typeof getMobileMessageWebViewMetrics;
    getMarkdownMetrics: typeof getMobileMarkdownRenderMetrics;
  }) => void;
} & MessageActions) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const historyActive = useMessageHistoryActive();
  const { accountGeneration } = useAuth();
  const richContent = useMemo(() => Platform.OS === 'android' ? new RichContentRuntime() : null,
    [scrollResetKey, remoteDeviceId, accountGeneration]);
  useEffect(() => () => richContent?.clear(), [richContent]);
  // Match LegendList's key: a new list must never inherit old visibility.
  const messageListVisibility = useMemo(() => new MessageListVisibility(), [scrollResetKey]);
  const historyPositioning = useMessageHistoryPositioning();
  const historyPositioningRef = useRef(historyPositioning);
  historyPositioningRef.current = historyPositioning;
  const historyActiveRef = useRef(historyActive);
  historyActiveRef.current = historyActive;
  const readingPosition = useMemo(() => scrollResetKey && remoteDeviceId
    ? messageReadingPosition(remoteDeviceId, scrollResetKey) : null, [remoteDeviceId, scrollResetKey]);
  const reopeningPosition = useMemo(() => readingPosition?.read(), [readingPosition]);
  const readingPositionActiveRef = useRef(isReadingPositionActive);
  readingPositionActiveRef.current = isReadingPositionActive;
  const itemStructureIdentity = itemsStructureKey ?? items;
  const itemsForStructureRef = useRef(items);
  itemsForStructureRef.current = items;
  const firstUserMessageClientId = useMemo(
    () => findFirstUserMessageClientId(itemsForStructureRef.current),
    [itemStructureIdentity],
  );
  const lastUserInputClientId = useMemo(
    () => findLastUserInputClientId(itemsForStructureRef.current),
    [itemStructureIdentity],
  );
  const focusedItemKeyRef = useRef(focusedItemKey);
  focusedItemKeyRef.current = focusedItemKey;
  const listRef = useRef<LegendListRef>(null);
  const listMetricsRef = useRef<LegendListMetrics>({ footerSize: 0, headerSize: 0 });
  const listTopPaddingRef = useRef(0);
  const listBottomPaddingRef = useRef(0);
  const shareableMessageViewsRef = useRef(new Map<string, View>());
  const windowDimensions = usePaneViewport();
  const viewportLayout = useMemo(() => buildMobileReadableViewportLayout({
    screenHeight: windowDimensions.height,
    screenWidth: windowDimensions.width,
  }), [windowDimensions.height, windowDimensions.width]);
  const wideContentInset = viewportLayout.wideViewport
    ? Math.max(0, (windowDimensions.width - viewportLayout.contentMaxWidth) / 2)
    : 0;
  const nearBottomRef = useRef(reopeningPosition?.atEnd ?? true);
  // ── 拖动手势追踪(贴底跟随的意图解除用)──
  // 拖动期间(onScrollBeginDrag ~ onScrollEndDrag)相对起点累计上移超过死区
  // → 立即解除跟随(shouldUnpinMobileFollowOnDrag),不看近底距离阈值——
  // 距离阈值(≥228px)在流式期间与程序化贴底滚动竞态,慢速小幅上滑会被反复拽回
  // (桌面版同源 bug 的手机版变体,见 messageScroll.ts)。
  const isDraggingRef = useRef(false);
  const isMomentumScrollingRef = useRef(false);
  const dragStartOffsetYRef = useRef<number | null>(null);
  // 用户是否主动拖动过(区分「冷开初始布局」与「用户上翻」):自动加载更早只在用户真拖过之后才允许,
  // 否则短会话(只加载了少量最新消息但 hasOlderMessages)冷开时会落在 onStartReachedThreshold 内、
  // 未经用户操作就自动拉历史(review P2)。切会话重置。
  const userScrollForOlderRef = useRef(false);
  // Android does not always emit onScrollBeginDrag when a list is already hard-clamped at
  // offset 0. Track raw downward touch displacement as a fallback history-browse intent.
  const historyTouchStartYRef = useRef<number | null>(null);
  const historyTouchTriggeredRef = useRef(false);
  // 冷开时自动补齐短初窗,最多连续拉三页;用户主动浏览后改走既有不限页的近顶预取。
  const initialHistoryAutofillRemainingRef = useRef(MAX_INITIAL_HISTORY_AUTOFILL_PAGES);
  // 上一次自动 load-earlier 触发时的首项 key:相同 = 上次尝试无进展(失败 / 拉回重复页),
  // 不再自动重试,防止对着打不出进展的 host 无限拉取。用户重新拖动 / 切会话时清除。
  const lastAutoLoadEarlierKeyRef = useRef<string | null>(null);
  const lastScrollHistoryEvaluationAtRef = useRef(0);
  const pendingScrollHistoryMetricsRef = useRef<MessageScrollMetrics | null>(null);
  const scrollHistoryEvaluationTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const attemptAutoLoadEarlierRef = useRef<(nativeMetrics?: MessageScrollMetrics) => void>(() => {});
  // 正在读「加载更早」拉回来的历史:抑制 handleContentSize 的大块撑高贴底,否则短会话(内容仍近底)
  // load-earlier 的 prepend 撑高会被误当成底部增长 → scrollToEnd 把用户从刚加载的历史拽回最新(review P1)。
  // 用户重新拖动 / 主动跳底 / 切会话时解除。
  const readingOlderRef = useRef(false);
  // 每次补页分配 generation:旧会话 / 旧请求的异步 settle 不得清掉新请求的抑制态。
  const readingOlderRequestGenerationRef = useRef(0);
  // Android data-change anchoring is app-owned; iOS keeps LegendList/RN's atomic native MVCP.
  // The shared transaction also suppresses follow-to-end until the page commit has settled.
  const historyPrependTransactionRef = useRef<MobileHistoryPrependTransaction | null>(null);
  const historyAnchorVerifyFrameRef = useRef<number | null>(null);
  const queuedLoadEarlierRef = useRef(false);
  const queuedLoadEarlierFlushFrameRef = useRef<number | null>(null);
  // On Android, keep native MVCP for ordinary data/size changes but turn it fully off before a
  // history request. LegendList maps either flag to the same RN ScrollView prop, so leaving size on
  // would still race the app-owned correction. iOS never flips this state.
  const [historyPrependNativeMvcpDisabled, setHistoryPrependNativeMvcpDisabled] = useState(false);
  const historyPrependNativeMvcpDisabledRef = useRef(historyPrependNativeMvcpDisabled);
  historyPrependNativeMvcpDisabledRef.current = historyPrependNativeMvcpDisabled;
  const loadingEarlierRef = useRef(loadingEarlier === true);
  loadingEarlierRef.current = loadingEarlier === true;
  // Data/size changes extend a short quiet window. During a manual prepend, the app-owned anchor
  // keeps correcting against the same key until that layout window ends.
  const mvcpSettleAtRef = useRef(0);
  const programmaticScrollGenerationRef = useRef(0);
  const programmaticScrollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const programmaticScrollInFlightRef = useRef(false);
  const programmaticAnimatedScrollInFlightRef = useRef(false);
  const programmaticScrollSettleAtRef = useRef(0);
  const previousFollowLatestRequestKeyRef = useRef(followLatestRequestKey);
  const previousItemKeysRef = useRef<readonly string[]>([]);
  // LegendList updates getState().scroll optimistically before an imperative native scroll lands.
  // Only native ScrollView scroll/end-drag samples advance this ack source for Android prepend.
  const nativeScrollEventSequenceRef = useRef(0);
  const [sampleScrollDebug] = useState(createScrollDebugSampler);
  const scrollMetricsRef = useRef<MessageScrollMetrics>({
    contentHeight: 0,
    offsetY: 0,
    viewportHeight: 0,
  });
  const tailFollowerRef = useRef<MobileTailFollower | null>(null);
  // 实际定位完成就直接显示;UI 线程只负责 300ms 兜底,不让繁忙 JS 无限延长隐藏。
  // 揭示沿用唯一 tail follower 的位置校验,不再额外等待或对旧消息做淡入。
  const initialAnchorDoneRef = useRef(false);
  const reopeningAnchorRef = useRef<{ anchor: MobileHistoryAnchor; expires: number; corrections: number } | null>(null);
  const reopeningFrameRef = useRef<number | null>(null);
  const initialRevealGenerationRef = useRef(0);
  const initialRevealAnimationRef = useRef<Animated.CompositeAnimation | null>(null);
  const initialRevealProgress = useMemo(
    () => new Animated.Value(0),
    [scrollResetKey],
  );
  const [listRevealed, setListRevealed] = useState(false);
  // Once revealed, detach opacity from the native animation. Its delayed stop callback
  // may still update the Animated.Value; later keyboard/layout renders must stay visible.
  const initialRevealOpacity = listRevealed ? 1 : initialRevealProgress;
  // Re-evaluate the near-start predicate after a prepend request releases its ref-only lock.
  // Without a render tick, a user who remains at the top can stall after one page because the
  // page commit effect ran while readingOlderRef was still true.
  const [loadEarlierEvaluationVersion, setLoadEarlierEvaluationVersion] = useState(0);
  // Main immediately requests another page when a prepend only expands the first collapsed
  // `Worked for` row. The app-owned anchor transaction settles first, then consumes this one-shot.
  const regroupedHistoryContinuationRef = useRef(false);
  // 会话切换(scrollResetKey)的 ref 复位必须在渲染期同步完成,不能只靠下方的 reset effect:
  // effect 在 paint 后异步执行,而重挂的新列表(key={scrollResetKey})的首批 scroll /
  // onStartReached 回调、以及先于 reset effect 定义的 eligibility effect,都可能带着上个会话的
  // 「上翻意图」与去重记录先跑——冷开短窗口会在无用户操作时误触发自动拉历史(review P2)。
  // setState 类复位(浮标/红点等)不参与该竞态,仍留在下方 effect。
  const visibleCompanionReplyKeysRef = useRef(new Set<string>());
  const prevScrollResetKeyRef = useRef(scrollResetKey);
  if (prevScrollResetKeyRef.current !== scrollResetKey) {
    prevScrollResetKeyRef.current = scrollResetKey;
    visibleCompanionReplyKeysRef.current.clear();
    listMetricsRef.current = { footerSize: 0, headerSize: 0 };
    nearBottomRef.current = reopeningPosition?.atEnd ?? true;
    isDraggingRef.current = false;
    isMomentumScrollingRef.current = false;
    dragStartOffsetYRef.current = null;
    userScrollForOlderRef.current = false;
    historyTouchStartYRef.current = null;
    historyTouchTriggeredRef.current = false;
    initialHistoryAutofillRemainingRef.current = MAX_INITIAL_HISTORY_AUTOFILL_PAGES;
    lastAutoLoadEarlierKeyRef.current = null;
    lastScrollHistoryEvaluationAtRef.current = 0;
    pendingScrollHistoryMetricsRef.current = null;
    if (scrollHistoryEvaluationTimerRef.current !== null) {
      clearTimeout(scrollHistoryEvaluationTimerRef.current);
      scrollHistoryEvaluationTimerRef.current = null;
    }
    readingOlderRef.current = false;
    readingOlderRequestGenerationRef.current += 1;
    historyPrependTransactionRef.current = null;
    queuedLoadEarlierRef.current = false;
    regroupedHistoryContinuationRef.current = false;
    if (historyPrependNativeMvcpDisabled) setHistoryPrependNativeMvcpDisabled(false);
    if (queuedLoadEarlierFlushFrameRef.current !== null) {
      cancelAnimationFrame(queuedLoadEarlierFlushFrameRef.current);
      queuedLoadEarlierFlushFrameRef.current = null;
    }
    if (historyAnchorVerifyFrameRef.current !== null) {
      cancelAnimationFrame(historyAnchorVerifyFrameRef.current);
      historyAnchorVerifyFrameRef.current = null;
    }
    mvcpSettleAtRef.current = 0;
    programmaticScrollGenerationRef.current += 1;
    programmaticScrollInFlightRef.current = false;
    programmaticAnimatedScrollInFlightRef.current = false;
    programmaticScrollSettleAtRef.current = 0;
    if (programmaticScrollTimerRef.current !== null) {
      clearTimeout(programmaticScrollTimerRef.current);
      programmaticScrollTimerRef.current = null;
    }
    previousItemKeysRef.current = [];
    nativeScrollEventSequenceRef.current = 0;
    scrollMetricsRef.current = { contentHeight: 0, offsetY: 0, viewportHeight: 0 };
    tailFollowerRef.current?.reset();
    tailFollowerRef.current = null;
    initialAnchorDoneRef.current = false;
    reopeningAnchorRef.current = null;
    initialRevealGenerationRef.current += 1;
    initialRevealAnimationRef.current?.stop();
    initialRevealAnimationRef.current = null;
    setListRevealed(false);
  }
  const lastAppliedFocusKeyRef = useRef<string | null>(null);
  const [hasNewMessages, setHasNewMessagesState] = useState(false);
  const hasNewMessagesRef = useRef(false);
  const setHasNewMessages = useCallback((next: boolean) => {
    if (hasNewMessagesRef.current === next) return;
    hasNewMessagesRef.current = next;
    setHasNewMessagesState(next);
  }, []);
  const [isAwayFromBottom, setIsAwayFromBottomState] = useState(false);
  const isAwayFromBottomRef = useRef(false);
  const setIsAwayFromBottom = useCallback((next: boolean) => {
    if (isAwayFromBottomRef.current === next) return;
    isAwayFromBottomRef.current = next;
    setIsAwayFromBottomState(next);
  }, []);
  const companionReplyTimes = useMemo(() => {
    const times = new Map<string, number>();
    if (companion) for (const item of items) {
      if (item.type !== 'message' || item.message.kind !== 'assistant') continue;
      const stamp = new Date(item.message.createdAt).getTime();
      if (Number.isFinite(stamp)) times.set(item.key, stamp);
    }
    return times;
  }, [companion, items]);
  const acknowledgeCompanionRead = useCallback(() => {
    if (!companion || !onCompanionReadThrough || !listRevealed || !initialAnchorDoneRef.current
      || isSessionStreaming || !historyActiveRef.current || !nearBottomRef.current
      || isReadingPositionActive?.() === false) return;
    const { contentHeight, viewportHeight, offsetY } = scrollMetricsRef.current;
    // Follow intent starts true before native layout; it is not proof of having read the tail.
    if (viewportHeight <= 0 || contentHeight <= 0
      || contentHeight - viewportHeight - offsetY > mobileMessageListNearBottomThreshold(bottomOverlayHeight)) return;
    let at = 0;
    for (const key of visibleCompanionReplyKeysRef.current) at = Math.max(at, companionReplyTimes.get(key) ?? 0);
    if (at > 0) onCompanionReadThrough(at);
  }, [companion, onCompanionReadThrough, listRevealed, isSessionStreaming, isReadingPositionActive, companionReplyTimes, bottomOverlayHeight]);
  const acknowledgeCompanionReadRef = useRef(acknowledgeCompanionRead);
  acknowledgeCompanionReadRef.current = acknowledgeCompanionRead;
  const handleCompanionViewableItems = useCallback(({ viewableItems }: OnViewableItemsChangedInfo<MobileMessageRenderItem>) => {
    visibleCompanionReplyKeysRef.current = new Set(viewableItems.filter(item => item.isViewable).map(item => item.key));
    acknowledgeCompanionReadRef.current();
  }, []);
  const handleViewableItemsChanged = useCallback((info: OnViewableItemsChangedInfo<MobileMessageRenderItem>) => {
    messageListVisibility.update(info.viewableItems);
    if (companion) handleCompanionViewableItems(info);
  }, [messageListVisibility, companion, handleCompanionViewableItems]);
  useEffect(() => {
    if (!companion || !onCompanionReadThrough) return;
    const frame = requestAnimationFrame(acknowledgeCompanionRead);
    return () => cancelAnimationFrame(frame);
  }, [acknowledgeCompanionRead, companion, onCompanionReadThrough, isAwayFromBottom]);
  const [payload, setPayload] = useState<MessagePayload | null>(null);
  /** 当前 payload 的点击来源(顶层 render item key);看图器按它取同一条消息的图集。 */
  const [payloadSourceGroupKey, setPayloadSourceGroupKey] = useState<string | null>(null);
  const openPayload = useCallback((next: MessagePayload) => {
    setPayloadSourceGroupKey(null);
    setPayload(next);
  }, []);
  const openPayloadFromItem = useCallback((next: MessagePayload, sourceGroupKey: string) => {
    setPayloadSourceGroupKey(sourceGroupKey);
    setPayload(next);
  }, []);
  useEffect(() => {
    if (!historyActive) setPayload(null);
  }, [historyActive, payload]);
  // 关闭回调必须引用稳定:内联闭包每次渲染换新,会经 ImageLightbox 透传成
  // LightboxPage 手势 useMemo 的依赖,流式回复期间每 token 重建手势图,
  // 可能打断进行中的捏合/拖动手势(rule 7)。
  const closePayload = useCallback(() => setPayload(null), []);
  const markProgrammaticScroll = useCallback((animated: boolean) => {
    const generation = programmaticScrollGenerationRef.current + 1;
    const settleMs = animated
      ? MOBILE_PROGRAMMATIC_ANIMATED_SCROLL_SETTLE_MS
      : MOBILE_PROGRAMMATIC_SCROLL_SETTLE_MS;
    programmaticScrollGenerationRef.current = generation;
    programmaticScrollInFlightRef.current = true;
    programmaticAnimatedScrollInFlightRef.current = animated;
    programmaticScrollSettleAtRef.current = Date.now() + settleMs;
    if (programmaticScrollTimerRef.current !== null) {
      clearTimeout(programmaticScrollTimerRef.current);
    }
    programmaticScrollTimerRef.current = setTimeout(() => {
      if (programmaticScrollGenerationRef.current !== generation) return;
      programmaticScrollTimerRef.current = null;
      programmaticScrollInFlightRef.current = false;
      programmaticAnimatedScrollInFlightRef.current = false;
      programmaticScrollSettleAtRef.current = 0;
    }, settleMs);
  }, []);

  const clearProgrammaticScroll = useCallback(() => {
    programmaticScrollGenerationRef.current += 1;
    programmaticScrollInFlightRef.current = false;
    programmaticAnimatedScrollInFlightRef.current = false;
    programmaticScrollSettleAtRef.current = 0;
    if (programmaticScrollTimerRef.current !== null) {
      clearTimeout(programmaticScrollTimerRef.current);
      programmaticScrollTimerRef.current = null;
    }
  }, []);

  const markMobileMvcpSettle = useCallback(() => {
    mvcpSettleAtRef.current = mobileMvcpSettleDeadline(
      mvcpSettleAtRef.current,
      Date.now(),
    );
  }, []);

  const isUserControllingScroll = useCallback(() => (
    historyTouchStartYRef.current !== null
    || isDraggingRef.current
    || isMomentumScrollingRef.current
  ), []);

  const revealPositionedHistory = useCallback(() => {
    // The fallback handle also gates repeated settle notifications. Stop before
    // setting opacity so the native fallback cannot write a later hidden frame.
    const animation = initialRevealAnimationRef.current;
    if (!initialAnchorDoneRef.current || !animation) return;
    initialRevealAnimationRef.current = null;
    animation.stop();
    initialRevealProgress.setValue(1);
    setListRevealed(true);
  }, [initialRevealProgress]);

  const getTailFollower = useCallback(() => {
    if (!tailFollowerRef.current) {
      tailFollowerRef.current = createMobileTailFollower({
        read: () => ({
          metrics: scrollMetricsRef.current,
          stickToLatest: nearBottomRef.current,
          userControllingScroll: isUserControllingScroll(),
          preservingHistory: readingOlderRef.current || !historyPositioningRef.current,
          layoutSettleAt: mvcpSettleAtRef.current,
          animatedScrollUntil: programmaticAnimatedScrollInFlightRef.current
            ? programmaticScrollSettleAtRef.current : 0,
        }),
        seekEnd: (animated) => {
          markProgrammaticScroll(animated);
          return listRef.current?.scrollToEnd({ animated });
        },
        correctOffset: (offset) => {
          markProgrammaticScroll(false);
          void listRef.current?.scrollToOffset({ animated: false, offset });
        },
        onMeasurementOscillation: () => console.warn(
          '[message-list] contentSize follow-pin circuit tripped: oscillating item measurements suspected',
        ),
        onSettled: revealPositionedHistory,
      });
    }
    return tailFollowerRef.current;
  }, [isUserControllingScroll, markProgrammaticScroll, revealPositionedHistory]);

  const scrollToEndProgrammatically = useCallback((
    animated: boolean,
    intent: 'follow' | 'explicit' = 'follow',
  ) => {
    // Only an explicit destination supersedes a pending final drag sample.
    if (intent === 'explicit') {
      reopeningAnchorRef.current = null;
      dragStartOffsetYRef.current = null;
      readingPosition?.write({ anchor: null, atEnd: true });
    }
    getTailFollower().requestEnd(animated, intent === 'explicit');
  }, [getTailFollower, readingPosition]);

  const scrollToOffsetProgrammatically = useCallback((offset: number, animated: boolean) => {
    markProgrammaticScroll(animated);
    void listRef.current?.scrollToOffset({ animated, offset });
  }, [markProgrammaticScroll]);

  const scrollToIndexProgrammatically = useCallback((index: number, viewPosition: number, animated = true) => {
    dragStartOffsetYRef.current = null;
    markProgrammaticScroll(animated);
    return listRef.current?.scrollToIndex({ animated, index, viewPosition });
  }, [markProgrammaticScroll]);

  const getCurrentHistoryTopOffsetAdjustment = useCallback(() => {
    const listState = listRef.current?.getState();
    if (!listState) return listTopPaddingRef.current + listMetricsRef.current.headerSize;
    return mobileHistoryTopOffsetAdjustment(listState, {
      baseTopOffset: listTopPaddingRef.current + listMetricsRef.current.headerSize,
      bottomPadding: listBottomPaddingRef.current,
      footerSize: listMetricsRef.current.footerSize,
    });
  }, []);

  const captureCurrentHistoryAnchor = useCallback((useNativeViewport = false): MobileHistoryAnchor | null => {
    const listState = listRef.current?.getState();
    const nativeMetrics = scrollMetricsRef.current;
    const canUseNativeViewport = useNativeViewport && nativeMetrics.viewportHeight > 0;
    return listState
      ? captureMobileHistoryAnchor(
        {
          ...listState,
          // A pending LegendList command can move `scroll` and the cached visible range before
          // Android's ScrollView follows. Once a finger owns the viewport, derive the anchor from
          // the last native offset and force the position lookup to ignore that optimistic range.
          ...(canUseNativeViewport
            ? { scroll: nativeMetrics.offsetY, start: -1 }
            : {}),
          topOffsetAdjustment: getCurrentHistoryTopOffsetAdjustment(),
        },
        (item) => (item as MobileMessageRenderItem).key,
        (item) => mobileMessageHistoryAnchorIdentity(item as MobileMessageRenderItem),
      )
      : null;
  }, [getCurrentHistoryTopOffsetAdjustment]);

  // A seek first uses estimated heights. Correct it only when layout supplies
  // real positions; never retry from onScroll (which can create a scroll storm).
  const reconcileReopeningAnchor = useCallback(() => {
    if (!historyPositioningRef.current || !reopeningAnchorRef.current || reopeningFrameRef.current !== null) return;
    reopeningFrameRef.current = requestAnimationFrame(() => {
      reopeningFrameRef.current = null;
      const pending = reopeningAnchorRef.current;
      if (!pending || !historyPositioningRef.current) return;
      if (Date.now() > pending.expires || pending.corrections >= 20) {
        reopeningAnchorRef.current = null;
        return;
      }
      const state = listRef.current?.getState();
      if (!state || state.scrollLength <= 0) return;
      const key = pending.anchor.identityKey
        ? mobileMessageHistoryRowKeyByIdentity(state.data, pending.anchor.identityKey) ?? pending.anchor.key
        : pending.anchor.key;
      const index = state.data.findIndex(item => item.key === key);
      if (index < 0 || !Number.isFinite(state.sizeAtIndex(index))) return;
      const target = resolveMobileMessageHistoryAnchorOffset(pending.anchor, state,
        getCurrentHistoryTopOffsetAdjustment());
      if (target === null || Math.abs(state.scroll - target) <= MOBILE_ANCHOR_VERIFY_TOLERANCE) return;
      pending.corrections++;
      markProgrammaticScroll(false);
      listRef.current?.scrollToOffset({ offset: target, animated: false });
    });
  }, [getCurrentHistoryTopOffsetAdjustment, markProgrammaticScroll]);

  const finishHistoryPrependTransaction = useCallback((generation: number) => {
    const transaction = historyPrependTransactionRef.current;
    if (!transaction || transaction.generation !== generation) return;
    if (historyAnchorVerifyFrameRef.current !== null) {
      cancelAnimationFrame(historyAnchorVerifyFrameRef.current);
      historyAnchorVerifyFrameRef.current = null;
    }
    regroupedHistoryContinuationRef.current = transaction.continueAfterRegroup
      && transaction.userInitiated
      && !transaction.userControlledDuringRequest;
    historyPrependTransactionRef.current = null;
    readingOlderRef.current = false;
    setHistoryPrependNativeMvcpDisabled(false);
    setLoadEarlierEvaluationVersion((version) => version + 1);
    getTailFollower().reconcile();
  }, [getTailFollower]);

  const maybeFinishHistoryPrependTransaction = useCallback((generation: number) => {
    const transaction = historyPrependTransactionRef.current;
    if (!transaction || transaction.generation !== generation) return;
    if (loadingEarlierRef.current || !transaction.promiseSettled) return;
    // A committed page still needs its anchor correction acknowledged; that case is covered by
    // `anchorStable` below. Only hold the handoff open while the finger or momentum still owns the
    // viewport, otherwise a page that resolves with no coordinate change could never release the
    // transaction and native MVCP would stay off for the rest of the session.
    if (
      transaction.userHandoffPending
      && (
        isDraggingRef.current
        || isMomentumScrollingRef.current
        || historyTouchStartYRef.current !== null
      )
    ) return;
    if (transaction.pageCommitted && !transaction.anchorStable) return;
    finishHistoryPrependTransaction(generation);
  }, [finishHistoryPrependTransaction]);

  // `viewportTakenOver` separates «a finger is on the ScrollView» from «the reader actually moved
  // the viewport». Both must stop imperative corrections, but only the latter may cancel the
  // regroup-only continuation: a bare tap moves nothing, and treating it as a takeover strands the
  // reader at the top when a page merely expanded the collapsed first work group.
  const handoffHistoryPrependToUser = useCallback((viewportTakenOver = true) => {
    const transaction = historyPrependTransactionRef.current;
    if (!transaction) return;
    if (viewportTakenOver) transaction.userControlledDuringRequest = true;
    if (!MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR) return;
    transaction.userHandoffPending = true;
    const currentAnchor = captureCurrentHistoryAnchor(true);
    if (currentAnchor) transaction.anchor = currentAnchor;
    if (!transaction.pageCommitted) return;
    transaction.userControlledAfterCommit = true;
    transaction.anchorStable = false;
    // An imperative scroll already handed to native cannot be cancelled reliably. Stop the JS
    // verifier from adding more commands while the finger/momentum owns the viewport, keep MVCP
    // disabled, and reconcile from native metrics after that gesture ends.
    transaction.pendingCorrection = null;
    if (historyAnchorVerifyFrameRef.current !== null) {
      cancelAnimationFrame(historyAnchorVerifyFrameRef.current);
      historyAnchorVerifyFrameRef.current = null;
    }
  }, [captureCurrentHistoryAnchor]);

  const cancelHistoryPrependTransaction = useCallback(() => {
    readingOlderRequestGenerationRef.current += 1;
    readingOlderRef.current = false;
    historyPrependTransactionRef.current = null;
    queuedLoadEarlierRef.current = false;
    regroupedHistoryContinuationRef.current = false;
    setHistoryPrependNativeMvcpDisabled(false);
    if (queuedLoadEarlierFlushFrameRef.current !== null) {
      cancelAnimationFrame(queuedLoadEarlierFlushFrameRef.current);
      queuedLoadEarlierFlushFrameRef.current = null;
    }
    if (historyAnchorVerifyFrameRef.current !== null) {
      cancelAnimationFrame(historyAnchorVerifyFrameRef.current);
      historyAnchorVerifyFrameRef.current = null;
    }
  }, []);

  const scheduleHistoryAnchorRestore = useCallback((generation: number) => {
    if (!MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR) return;
    const transaction = historyPrependTransactionRef.current;
    if (
      !transaction
      || transaction.generation !== generation
      || !transaction.pageCommitted
      || transaction.userControlledAfterCommit
    ) return;
    // The running verifier already re-resolves the anchor on every frame. Restarting it for every
    // tail content-size event prevents a live session from ever accumulating two stable frames.
    if (historyAnchorVerifyFrameRef.current !== null) return;
    transaction.anchorStable = false;
    if (transaction.verifyDeadlineAt === 0) {
      transaction.verifyDeadlineAt = Date.now() + MOBILE_HISTORY_ANCHOR_VERIFY_MAX_MS;
    }
    markMobileMvcpSettle();

    const step = (
      attempts: number,
      stableFrames: number,
      previousTargetOffset: number | null,
    ) => {
      const currentTransaction = historyPrependTransactionRef.current;
      if (
        !currentTransaction
        || currentTransaction.generation !== generation
        || currentTransaction.userControlledAfterCommit
      ) return;
      const withinDeadline = Date.now() < currentTransaction.verifyDeadlineAt;
      const anchor = currentTransaction.anchor;
      const listState = listRef.current?.getState();
      const targetOffset = anchor && listState
        ? resolveMobileMessageHistoryAnchorOffset(
          anchor,
          listState,
          getCurrentHistoryTopOffsetAdjustment(),
        )
        : null;

      if (targetOffset !== null && listState) {
        // LegendList moves getState().scroll to an imperative target before the native ScrollView
        // receives it. Using that optimistic value here used to self-confirm the correction in two
        // frames, release MVCP, and leave Android briefly rendering the target cell window at the
        // old physical offset. Only native scroll/end-drag metrics prove the viewport actually moved.
        const currentOffset = scrollMetricsRef.current.offsetY;
        const pendingCorrection = currentTransaction.pendingCorrection;
        const correctionStatus = pendingCorrection
          ? mobileHistoryAnchorCorrectionStatus(pendingCorrection, {
              nativeOffset: currentOffset,
              nativeScrollSequence: nativeScrollEventSequenceRef.current,
            }, MOBILE_ANCHOR_VERIFY_TOLERANCE)
          : null;
        const waitingForNativeCorrection = correctionStatus === 'waiting'
          && Math.abs(currentOffset - targetOffset) > MOBILE_ANCHOR_VERIFY_TOLERANCE;
        if (waitingForNativeCorrection) {
          // Keep one command in flight while no later native event has arrived. Once a later event
          // misses, the branch below clears this command and retries the latest resolved target at
          // most once per native event, rather than replacing the command on every animation frame.
          if (withinDeadline && attempts < MOBILE_HISTORY_ANCHOR_VERIFY_MAX_FRAMES) {
            historyAnchorVerifyFrameRef.current = requestAnimationFrame(() => {
              historyAnchorVerifyFrameRef.current = null;
              step(attempts + 1, 0, targetOffset);
            });
            return;
          }
        } else {
          if (pendingCorrection) currentTransaction.pendingCorrection = null;
          const settled = isMobileHistoryAnchorSettled(
            currentOffset,
            targetOffset,
            previousTargetOffset,
            MOBILE_ANCHOR_VERIFY_TOLERANCE,
          );
          // Only the anchor row's resolved position matters here. A running session can keep
          // growing below the reader while history is settling; treating every tail size change as
          // anchor instability keeps this verifier alive for the full retry bound and needlessly
          // churns cells/GC. If a layout change above the anchor matters, targetOffset changes and
          // the two-frame stability check resets on its own.
          const nextStableFrames = settled ? stableFrames + 1 : 0;
          if (
            Math.abs(currentOffset - targetOffset) > MOBILE_ANCHOR_VERIFY_TOLERANCE
            && withinDeadline
            && attempts < MOBILE_HISTORY_ANCHOR_VERIFY_MAX_FRAMES
          ) {
            currentTransaction.pendingCorrection = {
              requestedAfterNativeScrollSequence: nativeScrollEventSequenceRef.current,
              targetOffset,
            };
            scrollToOffsetProgrammatically(targetOffset, false);
          }
          if (nextStableFrames >= MOBILE_HISTORY_ANCHOR_STABLE_FRAMES) {
            historyAnchorVerifyFrameRef.current = null;
            currentTransaction.anchorStable = true;
            maybeFinishHistoryPrependTransaction(generation);
            return;
          }
          if (withinDeadline && attempts < MOBILE_HISTORY_ANCHOR_VERIFY_MAX_FRAMES) {
            historyAnchorVerifyFrameRef.current = requestAnimationFrame(() => {
              historyAnchorVerifyFrameRef.current = null;
              step(attempts + 1, nextStableFrames, targetOffset);
            });
            return;
          }
        }
      } else if (withinDeadline && attempts < MOBILE_HISTORY_ANCHOR_VERIFY_MAX_FRAMES) {
        historyAnchorVerifyFrameRef.current = requestAnimationFrame(() => {
          historyAnchorVerifyFrameRef.current = null;
          step(attempts + 1, 0, null);
        });
        return;
      }

      // Do not fire unacknowledged "final" scrolls and immediately re-enable native MVCP. That old
      // fallback raced its still-pending imperative command and amplified the visible bounce. Keep
      // the transaction bounded, warn once, and leave the reader detached from follow-to-latest.
      console.warn('[message-list] history prepend anchor did not settle before the retry bound');
      historyAnchorVerifyFrameRef.current = null;
      currentTransaction.pendingCorrection = null;
      currentTransaction.anchorStable = true;
      maybeFinishHistoryPrependTransaction(generation);
    };

    // useLayoutEffect calls this before paint. Run the first correction synchronously so Android
    // never displays the intermediate coordinate system where the old rows have moved but the
    // ScrollView offset still belongs to the pre-prepend data.
    step(0, 0, null);
  }, [
    getCurrentHistoryTopOffsetAdjustment,
    markMobileMvcpSettle,
    maybeFinishHistoryPrependTransaction,
    scrollToOffsetProgrammatically,
  ]);

  const restoreHistoryAnchorOnce = useCallback((generation: number) => {
    if (!MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR) return;
    const transaction = historyPrependTransactionRef.current;
    if (
      !transaction
      || transaction.generation !== generation
      || transaction.userControlledAfterCommit
    ) return;
    const listState = listRef.current?.getState();
    const targetOffset = transaction.anchor && listState
      ? resolveMobileMessageHistoryAnchorOffset(
        transaction.anchor,
        listState,
        getCurrentHistoryTopOffsetAdjustment(),
      )
      : null;
    if (
      targetOffset !== null
      && Math.abs(scrollMetricsRef.current.offsetY - targetOffset) > MOBILE_ANCHOR_VERIFY_TOLERANCE
    ) {
      scrollToOffsetProgrammatically(targetOffset, false);
    }
  }, [getCurrentHistoryTopOffsetAdjustment, scrollToOffsetProgrammatically]);

  const scheduleHistoryPrependUserHandoffSettle = useCallback(() => {
    if (!MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR) return;
    const transaction = historyPrependTransactionRef.current;
    if (!transaction || !transaction.userHandoffPending) return;
    if (historyAnchorVerifyFrameRef.current !== null) return;
    const generation = transaction.generation;
    // onScrollEndDrag can be followed by onMomentumScrollBegin. Defer one frame so momentum gets
    // ownership before deciding whether it is safe to resume imperative anchor verification.
    historyAnchorVerifyFrameRef.current = requestAnimationFrame(() => {
      historyAnchorVerifyFrameRef.current = null;
      const currentTransaction = historyPrependTransactionRef.current;
      if (
        !currentTransaction
        || currentTransaction.generation !== generation
        || isDraggingRef.current
        || isMomentumScrollingRef.current
        || historyTouchStartYRef.current !== null
      ) return;

      if (currentTransaction.pageCommitted) {
        currentTransaction.userHandoffPending = false;
        currentTransaction.userControlledAfterCommit = false;
        currentTransaction.pendingCorrection = null;
        currentTransaction.verifyDeadlineAt = 0;
        scheduleHistoryAnchorRestore(generation);
        return;
      }
      if (currentTransaction.promiseSettled && !loadingEarlierRef.current) {
        // A failed, empty, or duplicate page changed no coordinates. Waiting until the gesture
        // ended still guarantees that an older in-flight correction cannot race MVCP re-enable.
        currentTransaction.userHandoffPending = false;
        currentTransaction.userControlledAfterCommit = false;
        currentTransaction.pendingCorrection = null;
        currentTransaction.anchorStable = true;
        maybeFinishHistoryPrependTransaction(generation);
      }
    });
  }, [maybeFinishHistoryPrependTransaction, scheduleHistoryAnchorRestore]);

  // Initial entry, layout, content growth and release events share one tail controller.
  const runStickToLatestVerify = useCallback(() => {
    getTailFollower().reconcile();
  }, [getTailFollower]);

  // DEV-only:把列表控制器 + 滚动 metrics 暴露给性能 harness(临时,profiling/回归测量用)。
  useEffect(() => {
    if (!__DEV__) return;
    devExposeList?.({
      scrollTo: (y: number) => scrollToOffsetProgrammatically(y, false),
      getMetrics: () => scrollMetricsRef.current,
      getWebViewMetrics: getMobileMessageWebViewMetrics,
      getMarkdownMetrics: getMobileMarkdownRenderMetrics,
    });
  }, [devExposeList, scrollToOffsetProgrammatically]);

  // 与 main 保持一致:完整历史从首次挂载起就在同一个 LegendList 中,屏外 cell 交给
  // LegendList 虚拟化/回收。不能用业务尾窗代替完整数据,否则短尾窗未撑满首屏时
  // Android 无法产生有效滚动,运行中任务会重现“上半屏空白且历史不可拖动”。
  const listData = items;
  const listDataRef = useRef(listData);
  listDataRef.current = listData;
  const prevListLengthRef = useRef(listData.length);
  if (prevListLengthRef.current !== listData.length) {
    if (
      prevListLengthRef.current === 0
      && listData.length > 0
      && !initialAnchorDoneRef.current
      && listRevealed
    ) {
      // 冷进入常先挂空列表再收到首批缓存;必须在同一 render 重新遮住,不能先露顶部。
      setListRevealed(false);
    }
    prevListLengthRef.current = listData.length;
  }
  const itemKeys = useMemo(
    () => listDataRef.current.map((item) => item.key),
    [itemStructureIdentity],
  );
  const itemKeysSignature = useMemo(
    () => mobileMessageListKeysSignature(itemKeys),
    [itemKeys],
  );
  // Use host-cursor progress for both paging and transaction settlement. A history page may
  // expand a folded group or sit after a local synthetic row without changing the first item.
  const firstItemKey = itemKeys[0] ?? null;
  const historyProgressKey = loadEarlierProgressKey ?? firstItemKey;
  // A successful history page changes the oldest host cursor. Restore the captured visible row
  // in a layout effect: LegendList has accepted the new data, but React Native has not painted the
  // shifted absolute positions yet. This is the atomic point missing from Android native MVCP.
  useLayoutEffect(() => {
    const transaction = historyPrependTransactionRef.current;
    if (!transaction) return;
    if (transaction.startProgressKey !== historyProgressKey) {
      transaction.pageCommitted = true;
      transaction.continueAfterRegroup = transaction.userInitiated
        && mobileMessageHistoryOnlyExpandedFirstWorkGroup(
          transaction.startItems,
          listDataRef.current,
        );
      if (!MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR) {
        // iOS keeps LegendList/RN MVCP enabled for the data commit. Do not follow its atomic native
        // correction with an application scroll; only retain the transaction's follow-to-end guard.
        transaction.anchorStable = true;
        maybeFinishHistoryPrependTransaction(transaction.generation);
        return;
      }
      if (transaction.userControlledDuringRequest) {
        // A second gesture can begin while the remote page is in flight. Keep native MVCP disabled
        // and issue no app scroll while the finger/momentum owns the viewport. Gesture-end resumes
        // verification from the latest native-captured anchor and waits for its native ack.
        transaction.userControlledAfterCommit = true;
        transaction.anchorStable = false;
        transaction.pendingCorrection = null;
        // Re-arm the handoff explicitly: the gesture that took over may already have ended, in
        // which case the scheduled settle below is the only path back to anchor verification.
        transaction.userHandoffPending = true;
        scheduleHistoryPrependUserHandoffSettle();
        return;
      }
      scheduleHistoryAnchorRestore(transaction.generation);
      maybeFinishHistoryPrependTransaction(transaction.generation);
      return;
    }
    if (transaction.promiseSettled && !loadingEarlier) {
      // Failed, empty, or duplicate page: the current render has observed Promise settlement with
      // no oldest-cursor progress, so there is no prepend coordinate change to restore.
      transaction.anchorStable = true;
      maybeFinishHistoryPrependTransaction(transaction.generation);
    }
  }, [
    historyProgressKey,
    itemKeysSignature,
    loadEarlierEvaluationVersion,
    loadingEarlier,
    maybeFinishHistoryPrependTransaction,
    scheduleHistoryAnchorRestore,
    scheduleHistoryPrependUserHandoffSettle,
  ]);
  // 只认行身份(追加 / 换行 / 重排)。流式改内容会换 items 引用,但不能续安静窗。
  useEffect(() => {
    markMobileMvcpSettle();
  }, [itemKeysSignature, markMobileMvcpSettle]);
  // 本地缩略兜底映射版本:collect 内部对 cindy-oss-attach:// 附件读全局 store 做 overlay,
  // hydrate / 新注册后 gallery 需要重建,否则点开气泡本地图时 initialUrl 对不上图集条目。
  const sentThumbsVersion = useSentAttachmentThumbsVersion();
  const chatFilePathContext = useContext(ChatFilePathContext);
  // 图片与视频都进全屏查看器,两者在同一图集里横滑互翻;音频等仍走通用查看器。
  const imageLightboxOpen = historyActive && payload?.kind === 'media' && isLightboxMediaKind(payload.media.kind);
  const galleryImages = useMemo(
    () => (imageLightboxOpen
      ? collectMobileMessageGalleryImages(
          listData,
          chatFilePathContext?.workdir,
          chatFilePathContext?.remoteHostId,
          chatFilePathContext?.sessionId,
          getSentImagePreview,
        )
      : null),
    // eslint-disable-next-line react-hooks/exhaustive-deps -- sentThumbsVersion 是 collect 内部读的全局 store 的失效信号
    [
      chatFilePathContext?.remoteHostId,
      chatFilePathContext?.sessionId,
      chatFilePathContext?.workdir,
      getSentImagePreview,
      imageLightboxOpen,
      listData,
      sentThumbsVersion,
    ],
  );
  // 只在图片查看器打开时扫描完整历史;关闭态不能让每个流式 token 都递归遍历
  // message / work group / subagent 树。查看器打开期间若语义相同,则继续复用图集引用,
  // 避免取件 effect / FlatList / LightboxPage memo 每帧全部失效。
  const lightboxImagesRef = useRef<readonly MobileMessageGalleryImage[] | null>(null);
  const lightboxImages = useMemo(() => {
    if (!(payload?.kind === 'media' && isLightboxMediaKind(payload.media.kind)) || !galleryImages) {
      lightboxImagesRef.current = null;
      return null;
    }
    const prev = lightboxImagesRef.current;
    const sourceGroupPresent = listData.some((item) => item.key === payloadSourceGroupKey);
    const retainPendingSnapshot = !!payloadSourceGroupKey && pendingSendGroupKeys?.has(payloadSourceGroupKey) === true;
    const next = lightboxImagesForPayload(galleryImages, payload, payloadSourceGroupKey, prev, sourceGroupPresent, retainPendingSnapshot);
    if (prev && prev.length === next.length && prev.every((p, i) => {
      const n = next[i];
      return p.key === n.key
        && p.url === n.url
        && p.payload.media.url === n.payload.media.url
        && p.payload.media.previewable === n.payload.media.previewable
        && p.payload.galleryImageSlot === n.payload.galleryImageSlot
        && p.previewUri === n.previewUri;
    })) {
      return prev;
    }
    lightboxImagesRef.current = next;
    return next;
  }, [galleryImages, imageLightboxOpen, listData, payload, payloadSourceGroupKey, pendingSendGroupKeys]);
  const initialLightboxImage = lightboxImages
    ? lightboxImages[galleryImageIndexForPayload(lightboxImages, payload)]
    : undefined;
  const bottomPadding = mobileMessageListBottomPadding(bottomOverlayHeight, contentBottomInset);
  const topPadding = mobileMessageListTopPadding(topOverlayHeight);
  listBottomPaddingRef.current = bottomPadding;
  listTopPaddingRef.current = topPadding;
  // 上一次 topPadding,供顶部 chrome 高度变化时补偿 scroll offset(见下方 effect)。
  const prevTopPaddingRef = useRef(topPadding);
  const floatingBottomOffset = Math.max(
    spacing.lg,
    Math.ceil(bottomOverlayHeight ?? 0) + spacing.md,
  );
  // 浮标圆心与 composer 语音按钮圆心同列(设计要求:与右下角麦克风/输入框保持关系):
  // 从 composer 的真实布局常量推导,不写魔法数;宽屏(内容居中)时补上居中列的外侧留白。
  const scrollToBottomFabRight = useMemo(() => {
    const touchLayout = buildComposerTouchLayout({ screenWidth: windowDimensions.width });
    const micCenterFromRight = touchLayout.composerPaddingHorizontal
      + MOBILE_COMPOSER_VOICE_ANCHOR_RIGHT
      + MOBILE_COMPOSER_CONTROL_SIZE / 2;
    return Math.round(wideContentInset + micCenterFromRight - SCROLL_TO_BOTTOM_FAB_SIZE / 2);
  }, [wideContentInset, windowDimensions.width]);
  const loadEarlierAction = buildMessageLoadEarlierAction({
    hasOlderMessages: canLoadEarlier === true,
    loading: loadingEarlier === true,
    visibleMessageCount: listData.length,
  });
  const handleShareableMessageViewChange = useCallback((clientId: string, view: View | null) => {
    if (view) {
      shareableMessageViewsRef.current.set(clientId, view);
    } else {
      shareableMessageViewsRef.current.delete(clientId);
    }
    if (shareSelectionActiveRef.current) scheduleStickyShareCheckRef.current?.(true);
  }, []);
  const companionPluginWork = useMemo(() => companion ? companionPluginWorkEntries(items, companionPluginInvocations) : undefined, [companion, items, companionPluginInvocations]);
  // Desktop MessageStream groups the visible teammate conversation (not hidden work) into five-minute stamps.
  // Your own send is grouped by its send time from the moment its bubble appears, and its echo
  // (same key) keeps that time, so a phone/computer clock skew cannot add or move a stamp on
  // confirmation. Outbox rows carry the time across restarts.
  const pendingSentAtRef = useRef(new Map<string, number>());
  const companionTimeGroups = useMemo(() => companion ? collectBotMessageTimeGroups(items.flatMap((item): BotTimelineMessage[] => {
    if (item.type === 'pending_send') {
      const sentAt = item.sentAt ?? localSendStartedAt(item.key);
      if (sentAt === null) return [];
      pendingSentAtRef.current.set(item.key, sentAt);
      return [{ clientId: item.key, createdAt: sentAt }];
    }
    return item.type === 'message' && (item.message.kind === 'user' || item.message.kind === 'assistant' || item.message.companion)
      ? [{ clientId: item.key, createdAt: pendingSentAtRef.current.get(item.key) ?? localSendStartedAt(item.key) ?? item.message.createdAt }] : [];
  })) : undefined, [companion, items]);
  const quoteItemsRef = useRef(items);
  quoteItemsRef.current = items;
  const showCompanionReplyTargets = !!(companion && companionQuote?.showReplyTargets);
  // The last reply of each turn, as a stable key: rows re-render when a later reply of the same turn
  // arrives (so the earlier one drops its reply target), not on every streaming update.
  const lastCompanionReplyKey = useMemo(() => {
    if (!showCompanionReplyTargets) return '';
    const answered = new Set<string>();
    const lastReplies: string[] = [];
    for (let index = items.length - 1; index >= 0; index -= 1) {
      const entry = items[index];
      if (entry.type !== 'message' || entry.message.kind !== 'assistant') continue;
      const target = readReplyToClientId(entry.message);
      if (!target || answered.has(target)) continue;
      answered.add(target);
      lastReplies.push(messageClientId(entry));
    }
    return lastReplies.join('\n');
  }, [items, showCompanionReplyTargets]);
  const companionQuoteActions = useMemo<CompanionQuoteActions | undefined>(() => {
    if (!companion || !companionQuote) return undefined;
    const lastReplies = new Set(lastCompanionReplyKey ? lastCompanionReplyKey.split('\n') : []);
    return {
    ...companionQuote,
    getMessage: (clientId) => {
      for (const entry of quoteItemsRef.current) {
        if (entry.type === 'message' && messageClientId(entry) === clientId) return entry.message;
      }
      return undefined;
    },
    isLastReplyFor: (assistantClientId) => lastReplies.has(assistantClientId),
    };
  }, [companion, companionQuote, lastCompanionReplyKey]);
  const actions: MessageActions & { firstUserMessageClientId?: string } = useMemo(() => ({
    companion,
    companionQuoteActions,
    companionWorkingLabel,
  onOpenCompanionSettings,
    companionAvatar,
    companionTimeGroups,
    companionPluginWork,
    showPluginInvocations,
    remoteDeviceId,
    onAddMessageToComposer,
    onSideChatMessage,
    onDiagnoseError,
    onCopyMessageLink,
    onForkMessage,
    onDeleteMessage,
    onOpenForkOrigin,
    onOpenOriginSession,
    viewerDeviceId,
    onOpenSourceDevice,
    onOpenSessionLink,
    onPreviewRewind,
    onEnterShareSelection,
    onShareableMessageViewChange: handleShareableMessageViewChange,
    onOpenPayload: openPayload,
    onOpenPayloadFromItem: openPayloadFromItem,
    onLoadToolInput,
    onRetryImageDelivery,
    onResolveRemoteMedia,
    // 待发送气泡(pending_send 项)的展开态与队列操作:漏了这一项 actions.pendingSend 就是
    // undefined,渲染分支直接 null —— 气泡整个不画,乐观显示消失。
    pendingSend,
    getSentImagePreview,
    shareSelectionActive,
    shareSelectionBusy,
    busyClientId,
    busyAction,
    firstUserMessageClientId,
    lastUserInputClientId,
    makerTurnRunning,
    continuationTurnClientId,
    continuationInFlightProjectionCapability,
    isSessionStreaming,
    screenWidth: viewportLayout.contentWidth,
  }), [
    companion,
    companionQuoteActions,
    companionWorkingLabel,
  onOpenCompanionSettings,
    companionAvatar,
    companionTimeGroups,
    companionPluginWork,
    showPluginInvocations,
    remoteDeviceId,
    busyClientId,
    busyAction,
    continuationInFlightProjectionCapability,
    continuationTurnClientId,
    firstUserMessageClientId,
    isSessionStreaming,
    lastUserInputClientId,
    makerTurnRunning,
    onCopyMessageLink,
    onAddMessageToComposer,
    onSideChatMessage,
    onDiagnoseError,
    onDeleteMessage,
    onForkMessage,
    onOpenForkOrigin,
    onOpenOriginSession,
    viewerDeviceId,
    onOpenSourceDevice,
    onLoadToolInput,
    onRetryImageDelivery,
    onOpenSessionLink,
    onPreviewRewind,
    onEnterShareSelection,
    handleShareableMessageViewChange,
    onResolveRemoteMedia,
    openPayload,
    openPayloadFromItem,
    pendingSend,
    getSentImagePreview,
    shareSelectionActive,
    shareSelectionBusy,
    viewportLayout.contentWidth,
  ]);
  // Native selection menus share the host's action availability. Read-only hosts
  // keep the system menu; side-chat tasks do not recursively offer side chats.
  const selectionQuoteEnabled = !!onQuoteSelection;
  const commitSelectionQuote = useCallback((text: string) => onQuoteSelection?.({ text }), [onQuoteSelection]);
  const selectionQuoteContextValue = useMemo(
    () => (selectionQuoteEnabled
      ? { commitQuote: commitSelectionQuote, askInSideChat: onSideChatMessage }
      : null),
    [onSideChatMessage, selectionQuoteEnabled, commitSelectionQuote],
  );
  const showJumpToLatest = isAwayFromBottom && !hasNewMessages;
  const focusRunKey = focusedItemKey
    ? `${focusedRequestKey ?? 'default'}:${focusedItemKey}`
    : null;
  const viewabilityConfigRef = useRef({
    id: MESSAGE_LIST_VIEWABILITY_CONFIG_ID,
    itemVisiblePercentThreshold: MESSAGE_LIST_VISIBLE_PERCENT_THRESHOLD,
  });
  const shareSelectionActiveRef = useRef(shareSelectionActive);
  shareSelectionActiveRef.current = shareSelectionActive;
  const topOverlayHeightRef = useRef(topOverlayHeight);
  topOverlayHeightRef.current = topOverlayHeight;
  const [stickyShareClientId, setStickyShareClientId] = useState<string | null>(null);
  const stickyCheckSeqRef = useRef(0);
  const stickyCheckLastRunAtRef = useRef(0);
  const stickyCheckTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const runStickyShareCheck = useCallback(async () => {
    const seq = ++stickyCheckSeqRef.current;
    if (!shareSelectionActiveRef.current) {
      setStickyShareClientId(null);
      return;
    }
    const shareableViews = Array.from(shareableMessageViewsRef.current.entries());
    const list = listRef.current;
    if (!list || shareableViews.length === 0) {
      setStickyShareClientId(null);
      return;
    }
    const [listFrame, candidates] = await Promise.all([
      measureInWindow(list.getNativeScrollRef()),
      Promise.all(shareableViews.map(async ([clientId, view]) => ({
        clientId,
        frame: await measureInWindow(view),
      }))),
    ]);
    if (seq !== stickyCheckSeqRef.current) return;
    if (!listFrame) {
      setStickyShareClientId(null);
      return;
    }
    const dockY = listFrame.y + (topOverlayHeightRef.current ?? 0) + spacing.sm;
    candidates.sort((a, b) => (a.frame?.y ?? Number.POSITIVE_INFINITY)
      - (b.frame?.y ?? Number.POSITIVE_INFINITY));
    const pinned = candidates.find(({ frame }) => frame
      && frame.height > 0
      && frame.y + spacing.sm < dockY
      && frame.y + frame.height > dockY + SHARE_STICKY_CHECK_HEIGHT);
    setStickyShareClientId((prev) => {
      const next = pinned?.clientId ?? null;
      return prev === next ? prev : next;
    });
  }, []);
  const scheduleStickyShareCheck = useCallback((immediate = false) => {
    const now = Date.now();
    const elapsed = now - stickyCheckLastRunAtRef.current;
    if (immediate || elapsed >= STICKY_SHARE_CHECK_THROTTLE_MS) {
      stickyCheckLastRunAtRef.current = now;
      void runStickyShareCheck();
      return;
    }
    if (stickyCheckTimerRef.current) return;
    stickyCheckTimerRef.current = setTimeout(() => {
      stickyCheckTimerRef.current = null;
      stickyCheckLastRunAtRef.current = Date.now();
      void runStickyShareCheck();
    }, STICKY_SHARE_CHECK_THROTTLE_MS - elapsed);
  }, [runStickyShareCheck]);
  const scheduleStickyShareCheckRef = useRef(scheduleStickyShareCheck);
  scheduleStickyShareCheckRef.current = scheduleStickyShareCheck;
  useEffect(() => {
    if (!shareSelectionActive) setStickyShareClientId(null);
    else scheduleStickyShareCheck(true);
  }, [shareSelectionActive, scheduleStickyShareCheck, topOverlayHeight]);
  useEffect(() => () => {
    if (stickyCheckTimerRef.current) clearTimeout(stickyCheckTimerRef.current);
  }, []);
  // 贴底跟随由 handleContentSize 的手动补滚承担(nearBottomRef 是跟随意图的唯一真相);
  // 跳底先命令式 scrollToEnd,随后复用同一轮有界落底校验。
  const scrollToBottom = useCallback(() => {
    nearBottomRef.current = true;
    cancelHistoryPrependTransaction();
    userScrollForOlderRef.current = false;
    setIsAwayFromBottom(false);
    setHasNewMessages(false);
    scrollToEndProgrammatically(true, 'explicit');
  }, [cancelHistoryPrependTransaction, scrollToEndProgrammatically]);

  // The send-time follow runs before the local bubble exists, so the bubble would then land through
  // the instant tail correction. Follow once more, animated, the moment it is in the list: the list
  // carries the bubble up while it eases in.
  const followedLocalSendKeysRef = useRef(new Set<string>());
  useLayoutEffect(() => {
    if (!historyActive) return;
    const now = Date.now();
    for (let index = listData.length - 1; index >= Math.max(0, listData.length - 3); index--) {
      const item = listData[index];
      if (item.type !== 'pending_send' && item.type !== 'message') continue;
      const sentAt = localSendStartedAt(item.key);
      if (sentAt === null || now - sentAt >= LOCAL_SEND_FRESH_MS) continue;
      if (followedLocalSendKeysRef.current.has(item.key)) return;
      followedLocalSendKeysRef.current.add(item.key);
      scrollToBottom();
      return;
    }
  }, [historyActive, listData, scrollToBottom]);

  // A retained list must not replay requests issued while another task was active.
  const followRequestWasActiveRef = useRef(historyActive);
  // Sending and the jump button share the same explicit follow action.
  useEffect(() => {
    const wasActive = followRequestWasActiveRef.current;
    followRequestWasActiveRef.current = historyActive;
    if (!historyActive || !wasActive) {
      previousFollowLatestRequestKeyRef.current = followLatestRequestKey;
      return;
    }
    if (previousFollowLatestRequestKeyRef.current === followLatestRequestKey) return;
    previousFollowLatestRequestKeyRef.current = followLatestRequestKey;
    if (followLatestRequestKey === null || followLatestRequestKey === undefined) return;
    scrollToBottom();
  }, [historyActive, followLatestRequestKey, scrollToBottom]);

  // 自动加载更早:电平触发判定(shouldAutoLoadEarlier),在所有可能改变判定结果的时机重评估
  // (scroll 事件 / LegendList onStartReached 边沿 / eligibility 变化 effect)。
  // 为什么不能只靠 onStartReached:它是边沿信号——触发过一次后要滚离顶部超过阈值 × 1.3 再回来
  // (或阈值内 data 变化)才会再发;这里的业务 guard(没拖动过 / 正在加载 / 入口未点亮)吞掉一次
  // 边沿后,条件就绪时不会有下一个边沿,用户就停在顶部干等(短加载窗口的会话冷开即中招:
  // 列表底部已落在近顶阈值内,边沿在拖动前就被消费,之后永远滚不出复位区 → 永久哑火)。
  // nearStart / atEnd 读 LegendList getState() 的实时账;app 侧 onScroll 的原生 offsetY
  // 在 prepend 提交期间不代表「距内容顶端的距离」,不可用于判顶。prepend 防跳由上面的
  // key + viewportOffset 事务处理;请求开始前会暂时关闭 Android native MVCP,恢复完成后重开。
  // 冷开只在列表同时位于 start/end(内容未撑满首屏)时有界补页;真实上翻意图继续沿用
  // 不限页的近顶预取。两条路径都受首项进展去重保护,失败/重复页不会循环打 host。
  const beginLoadEarlier = useCallback(() => {
    if (!historyActiveRef.current || !onLoadEarlier) return;
    const generation = readingOlderRequestGenerationRef.current + 1;
    readingOlderRequestGenerationRef.current = generation;
    const listState = listRef.current?.getState();
    const anchor = MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR && listState
      ? captureMobileHistoryAnchor(
        {
          ...listState,
          topOffsetAdjustment: getCurrentHistoryTopOffsetAdjustment(),
        },
        (item) => (item as MobileMessageRenderItem).key,
        (item) => mobileMessageHistoryAnchorIdentity(item as MobileMessageRenderItem),
      )
      : null;
    historyPrependTransactionRef.current = {
      anchor,
      anchorStable: !MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR,
      continueAfterRegroup: false,
      generation,
      pageCommitted: false,
      pendingCorrection: null,
      promiseSettled: false,
      startItems: listDataRef.current,
      startProgressKey: historyProgressKey,
      userInitiated: userScrollForOlderRef.current,
      userControlledAfterCommit: false,
      userControlledDuringRequest: false,
      userHandoffPending: false,
      verifyDeadlineAt: 0,
    };
    readingOlderRef.current = true;
    // A short list can be simultaneously atStart and atEnd. Once the user explicitly browses
    // older history, it must no longer be treated as following the latest edge; otherwise the
    // prepend height is mistaken for a tail append and handleContentSize scrolls to the end.
    if (userScrollForOlderRef.current) {
      nearBottomRef.current = false;
      setIsAwayFromBottom(true);
    }
    const markRequestSettled = () => {
      const transaction = historyPrependTransactionRef.current;
      if (!transaction || transaction.generation !== generation) return;
      transaction.promiseSettled = true;
      // Force one render after Promise settlement. The parent may batch loading=true, the merged
      // page, and loading=false; the layout effect above is the authoritative point where we decide
      // whether a page actually committed before releasing the transaction.
      setLoadEarlierEvaluationVersion((version) => version + 1);
    };
    try {
      const result = onLoadEarlier();
      void Promise.resolve(result).then(
        markRequestSettled,
        markRequestSettled,
      );
    } catch {
      markRequestSettled();
    }
  }, [getCurrentHistoryTopOffsetAdjustment, historyProgressKey, onLoadEarlier]);

  const flushQueuedLoadEarlier = useCallback(() => {
    if (!queuedLoadEarlierRef.current) return;
    // Native MVCP can prepend while iOS is scrolling. Only the app-owned Android anchor
    // needs a quiet gesture boundary; delaying both platforms defeats near-start prefetch.
    if (MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR && (
      isDraggingRef.current
      || isMomentumScrollingRef.current
      || historyTouchStartYRef.current !== null
    )) return;
    // Android must not start until a committed render removes RN's native MVCP prop. Otherwise a
    // fast local/relay response can prepend before that prop update lands. iOS keeps native MVCP
    // throughout and can start while the user's gesture is still active.
    if (
      MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR
      && !historyPrependNativeMvcpDisabledRef.current
    ) {
      setHistoryPrependNativeMvcpDisabled(true);
      return;
    }
    queuedLoadEarlierRef.current = false;
    beginLoadEarlier();
  }, [beginLoadEarlier]);

  const scheduleQueuedLoadEarlierFlush = useCallback(() => {
    if (queuedLoadEarlierFlushFrameRef.current !== null) return;
    queuedLoadEarlierFlushFrameRef.current = requestAnimationFrame(() => {
      queuedLoadEarlierFlushFrameRef.current = null;
      flushQueuedLoadEarlier();
    });
  }, [flushQueuedLoadEarlier]);

  const requestLoadEarlier = useCallback(() => {
    if (!onLoadEarlier || readingOlderRef.current || queuedLoadEarlierRef.current) return;
    // Queueing itself owns the history-browse lock: a running task may append/resize messages while
    // the current drag or momentum is still settling, and those contentSize events must not follow
    // the latest edge before the history request actually starts.
    queuedLoadEarlierRef.current = true;
    readingOlderRef.current = true;
    if (userScrollForOlderRef.current) {
      nearBottomRef.current = false;
      setIsAwayFromBottom(true);
    }
    // The first safe frame disables native MVCP. Its committed layout effect below then starts the
    // request, keeping the unanchored interval to a single React commit with no network in flight.
    scheduleQueuedLoadEarlierFlush();
  }, [onLoadEarlier, scheduleQueuedLoadEarlierFlush]);

  useLayoutEffect(() => {
    if (!historyPrependNativeMvcpDisabled) return;
    flushQueuedLoadEarlier();
  }, [flushQueuedLoadEarlier, historyPrependNativeMvcpDisabled]);

  const attemptAutoLoadEarlier = useCallback((nativeMetrics?: MessageScrollMetrics) => {
    if (!historyActiveRef.current || !onLoadEarlier) return;
    if (readingOlderRef.current || queuedLoadEarlierRef.current) return;
    // 热路径前置短路(滚动事件每 16ms 评估一次,getState() 每次新建状态对象):没有用户浏览意图
    // 且冷开预算已耗尽、或当前首项已尝试过时不碰 getState。完整判定仍以
    // shouldAutoLoadEarlier 为唯一真相,这里只做它的子集提前返回。
    const userScrolledForOlder = userScrollForOlderRef.current;
    // Reveal the latest cached page before cold-open autofill starts. Otherwise the initial
    // scroll-to-end verifier waits behind one or more history requests while the whole list is
    // still opacity-hidden, which turns a background prefetch into a multi-second blank screen.
    const initialAutoFillAllowed = listRevealed
      && !userScrolledForOlder
      && initialHistoryAutofillRemainingRef.current > 0;
    const continueAfterRegroup = userScrolledForOlder
      && regroupedHistoryContinuationRef.current;
    if (!userScrolledForOlder && !initialAutoFillAllowed && !continueAfterRegroup) return;
    if (historyProgressKey !== null && lastAutoLoadEarlierKeyRef.current === historyProgressKey) return;
    if (continueAfterRegroup) {
      if (!loadEarlierAction.visible) {
        regroupedHistoryContinuationRef.current = false;
        return;
      }
      // A merged page did make host-cursor progress but added no visible top-level history. Do not
      // reapply the near-start gate after app-owned anchor restoration moved the viewport; main
      // immediately continues from the changed first rendered row in the same situation.
      if (loadEarlierAction.disabled || historyProgressKey === null) return;
      regroupedHistoryContinuationRef.current = false;
      lastAutoLoadEarlierKeyRef.current = historyProgressKey;
      requestLoadEarlier();
      return;
    }
    if (
      nativeMetrics
      && nativeMetrics.offsetY <= MOBILE_ANCHOR_VERIFY_TOLERANCE
      && scrollHistoryEvaluationTimerRef.current !== null
    ) {
      pendingScrollHistoryMetricsRef.current = null;
      clearTimeout(scrollHistoryEvaluationTimerRef.current);
      scrollHistoryEvaluationTimerRef.current = null;
    }
    if (
      nativeMetrics
      && nativeMetrics.offsetY > MOBILE_ANCHOR_VERIFY_TOLERANCE
    ) {
      const now = Date.now();
      if (
        now - lastScrollHistoryEvaluationAtRef.current
        < MOBILE_SCROLL_HISTORY_EVALUATION_INTERVAL_MS
      ) {
        // 保留最后一帧再补一次尾调用:否则快滑恰好停在近顶区时,最后一次判定可能
        // 被节流吞掉,用户必须再拖一下才能继续分页。
        pendingScrollHistoryMetricsRef.current = nativeMetrics;
        if (scrollHistoryEvaluationTimerRef.current === null) {
          const remainingMs = MOBILE_SCROLL_HISTORY_EVALUATION_INTERVAL_MS
            - (now - lastScrollHistoryEvaluationAtRef.current);
          scrollHistoryEvaluationTimerRef.current = setTimeout(() => {
            scrollHistoryEvaluationTimerRef.current = null;
            const pendingMetrics = pendingScrollHistoryMetricsRef.current;
            pendingScrollHistoryMetricsRef.current = null;
            lastScrollHistoryEvaluationAtRef.current = 0;
            attemptAutoLoadEarlierRef.current(pendingMetrics ?? undefined);
          }, remainingMs);
        }
        return;
      }
      pendingScrollHistoryMetricsRef.current = null;
      if (scrollHistoryEvaluationTimerRef.current !== null) {
        clearTimeout(scrollHistoryEvaluationTimerRef.current);
        scrollHistoryEvaluationTimerRef.current = null;
      }
      lastScrollHistoryEvaluationAtRef.current = now;
    }
    const listState = listRef.current?.getState();
    if (!listState) return;
    // LegendList's edge bookkeeping can lag behind the native ScrollView during recycling,
    // initial anchoring, and a no-bounce drag at offset 0. Native metrics are only a positive
    // fallback: they may prove this gesture is at/near the history edge, never disqualify it.
    const nativeAtStart = nativeMetrics !== undefined
      && nativeMetrics.offsetY <= MOBILE_ANCHOR_VERIFY_TOLERANCE;
    const nativeNearStart = nativeMetrics !== undefined
      && nativeMetrics.offsetY <= mobileLoadEarlierPrefetchThreshold(nativeMetrics.viewportHeight);
    const eligible = shouldAutoLoadEarlier({
      actionDisabled: loadEarlierAction.disabled,
      actionVisible: loadEarlierAction.visible,
      atEnd: listState.isAtEnd,
      atStart: listState.isAtStart || nativeAtStart,
      progressKey: historyProgressKey,
      initialAutoFillAllowed,
      lastAttemptedProgressKey: lastAutoLoadEarlierKeyRef.current,
      nearStart: listState.isNearStart || nativeNearStart,
      userScrolledForOlder,
    });
    if (!eligible) return;
    lastAutoLoadEarlierKeyRef.current = historyProgressKey;
    if (initialAutoFillAllowed) initialHistoryAutofillRemainingRef.current -= 1;
    requestLoadEarlier();
  }, [
    historyProgressKey,
    loadEarlierAction.disabled,
    loadEarlierAction.visible,
    listRevealed,
    onLoadEarlier,
    requestLoadEarlier,
  ]);
  attemptAutoLoadEarlierRef.current = attemptAutoLoadEarlier;

  // 近底/跟随态迁移 + 「跳到底部」浮标与新消息红点;metrics 也供 DEV harness 读取。
  // 「解除跟随」的主路径是拖动意图(shouldUnpinMobileFollowOnDrag):拖动中相对起点
  // 上移超过死区立即解除(nearBottomRef 翻 false 即关掉 handleContentSize 的贴底补滚)。
  // 「恢复跟随」走 resolveMobileNearBottomOnScroll:距离 + 明确向下方向。读历史
  // (readingOlderRef)期间禁止方向性恢复——load-earlier prepend 的 mVCP 补偿会产生
  // 程序化向下增量,短会话里会被误判成「用户滑回底部」。
  const handleScroll = useCallback((
    event: NativeSyntheticEvent<NativeScrollEvent>,
    isFinalDragSample = false,
  ) => {
    richContent?.onScroll();
    if (!historyPositioningRef.current) return;
    // Cancellation releases ownership immediately. Only endDrag may still consume its final
    // sample; an ordinary layout/MVCP scroll cannot use the retained origin as user intent.
    const isDragSample = isDraggingRef.current
      || (isFinalDragSample && dragStartOffsetYRef.current !== null);
    nativeScrollEventSequenceRef.current += 1;
    const metrics = {
      contentHeight: event.nativeEvent.contentSize.height,
      offsetY: event.nativeEvent.contentOffset.y,
      viewportHeight: event.nativeEvent.layoutMeasurement.height,
    };
    const previousOffsetY = scrollMetricsRef.current.offsetY;
    scrollMetricsRef.current = metrics;
    // A native acknowledgment ends reopening, not merely its reveal animation.
    // Otherwise later measurements keep replaying the old bookmark after the
    // viewport is already correct (including after the 300ms reveal fallback).
    const reopening = reopeningAnchorRef.current;
    if (reopening) {
      const state = listRef.current?.getState();
      const target = state ? resolveMobileMessageHistoryAnchorOffset(reopening.anchor,
        state, getCurrentHistoryTopOffsetAdjustment()) : null;
      if (target !== null && Math.abs(metrics.offsetY - target) <= MOBILE_ANCHOR_VERIFY_TOLERANCE) {
        reopeningAnchorRef.current = null;
        revealPositionedHistory();
      }
    }
    // Preloads need real geometry, but must not publish bookmarks or trigger user work.
    if (!historyActiveRef.current) return;
    const debugFlags = Number(isDragSample) | (Number(isMomentumScrollingRef.current) << 1)
      | (Number(readingOlderRef.current) << 2) | (Number(nearBottomRef.current) << 3);
    if (mobileDebugEnabled() && sampleScrollDebug(debugFlags, isFinalDragSample)) mobileDebugLog('debug', 'scroll', 'list scroll', {
      hostRef: remoteDeviceId?.slice(0, 8), sessionRef: scrollResetKey?.slice(0, 8),
      itemCount: itemsForStructureRef.current.length, initialAnchorDone: initialAnchorDoneRef.current,
      reopening: reopeningAnchorRef.current !== null,
      ...metrics, dragging: isDragSample, momentum: isMomentumScrollingRef.current,
      readingOlder: readingOlderRef.current, nearBottom: nearBottomRef.current,
    });
    if (readingOlderRef.current) {
      if (
        isDragSample
        || isMomentumScrollingRef.current
        || historyTouchTriggeredRef.current
      ) {
        handoffHistoryPrependToUser();
        // Loading older messages must not discard the reader's latest position.
        // Only native user movement may replace the bookmark during a prepend;
        // layout-only/MVCP events are still ignored here.
        if (metrics.viewportHeight > 0 && metrics.contentHeight >= metrics.viewportHeight
          && !programmaticScrollInFlightRef.current
          && (readingPositionActiveRef.current?.() ?? true)) {
          const anchor = captureCurrentHistoryAnchor(true);
          if (anchor) readingPosition?.write({ anchor, atEnd: false });
        }
      }
      // Prepend layout can transiently report an empty/short content range. Never feed those
      // metrics into near-bottom resolution: it would flip false→true and the next size event
      // would force the reader to the latest message.
      attemptAutoLoadEarlier(metrics);
      if (shareSelectionActiveRef.current) scheduleStickyShareCheck();
      return;
    }
    const wasNearBottom = nearBottomRef.current;
    const scrollDelta = metrics.offsetY - previousOffsetY;
    if (
      nearBottomRef.current
      && shouldUnpinMobileFollowOnDrag({
        dragging: isDragSample,
        dragStartOffsetY: dragStartOffsetYRef.current,
        metrics,
      })
    ) {
      nearBottomRef.current = false;
      setIsAwayFromBottom(true);
    } else {
      const preserveHistoryBrowseIntent = shouldPreserveMobileHistoryBrowseIntent({
        // Only preserve an actual unpin. A dead-zone drag also enables pagination, but its
        // final native event must not turn a temporary follow suspension into an unpin.
        historyBrowseIntent: userScrollForOlderRef.current && !nearBottomRef.current,
        userControllingScroll: isDragSample
          || isMomentumScrollingRef.current
          || historyTouchStartYRef.current !== null,
      });
      // Dragging (including end-drag's final native metrics) owns the cumulative dead zone.
      // Outside a drag, layout/MVCP corrections cannot prove user intent. Preserve follow;
      // actual momentum retains the existing direction/distance fallback.
      const preserveFollowIntent = nearBottomRef.current && !isMomentumScrollingRef.current;
      const nearBottom = preserveHistoryBrowseIntent
        ? false
        : preserveFollowIntent || resolveMobileNearBottomOnScroll({
          wasNearBottom: nearBottomRef.current,
          metrics,
          programmaticScrollInFlight: programmaticScrollInFlightRef.current,
          scrollDelta,
          bottomOverlayHeight,
        });
      nearBottomRef.current = nearBottom;
      // A genuine downward false→true transition means the user manually returned to the
      // latest edge. The old history-browsing intent no longer owns follow verification;
      // a later drag will set it again before any new upward browse.
      if (!wasNearBottom && nearBottom && scrollDelta > 0) {
        userScrollForOlderRef.current = false;
      }
      setIsAwayFromBottom(!nearBottom);
      if (nearBottom) setHasNewMessages(false);
    }
    acknowledgeCompanionReadRef.current();
    // 拖动进近顶区时 onStartReached 边沿可能早已被消费(见 attemptAutoLoadEarlier 注释),
    // 滚动事件兜底重评估;前置短路让稳态滚动只付 1~2 次 ref 比较的成本。
    attemptAutoLoadEarlier(metrics);
    // 分享模式:滚动驱动吸顶 check 的几何重判(内部节流,非分享模式直接返回)。
    if (shareSelectionActiveRef.current) scheduleStickyShareCheck();
    if (initialAnchorDoneRef.current && !programmaticScrollInFlightRef.current && !readingOlderRef.current
      && (readingPositionActiveRef.current?.() ?? true)) {
      const anchor = captureCurrentHistoryAnchor(true);
      if (anchor && !reopeningAnchorRef.current) readingPosition?.write({ anchor, atEnd: nearBottomRef.current });
    }
  }, [
    captureCurrentHistoryAnchor,
    reopeningPosition,
    getCurrentHistoryTopOffsetAdjustment,
    revealPositionedHistory,
    readingPosition,
    remoteDeviceId,
    scrollResetKey,
    attemptAutoLoadEarlier,
    bottomOverlayHeight,
    handoffHistoryPrependToUser,
    scheduleStickyShareCheck,
    richContent,
  ]);

  const handleHistoryTouchStart = useCallback((event: GestureResponderEvent) => {
    reopeningAnchorRef.current = null;
    // Android may omit momentum-end when a new finger stops a fling. The new touch owns the
    // ScrollView now, so the old momentum flag must not keep a queued history request suspended.
    isMomentumScrollingRef.current = false;
    historyTouchStartYRef.current = event.nativeEvent.pageY;
    historyTouchTriggeredRef.current = false;
    clearProgrammaticScroll();
    // Touch-start only means the finger holds the ScrollView; it is not a viewport takeover yet.
    // maybeTriggerHistoryTouch / onScrollBeginDrag report the real move once it clears the dead zone.
    handoffHistoryPrependToUser(false);
  }, [clearProgrammaticScroll, handoffHistoryPrependToUser]);

  const maybeTriggerHistoryTouch = useCallback((pageY: number) => {
    const startY = historyTouchStartYRef.current;
    if (
      startY === null
      || historyTouchTriggeredRef.current
      || pageY - startY < MOBILE_FOLLOW_UNPIN_DRAG_DEAD_ZONE
    ) return;
    historyTouchTriggeredRef.current = true;
    userScrollForOlderRef.current = true;
    lastAutoLoadEarlierKeyRef.current = null;
    handoffHistoryPrependToUser();
    attemptAutoLoadEarlier(scrollMetricsRef.current);
  }, [attemptAutoLoadEarlier, handoffHistoryPrependToUser]);

  const handleHistoryTouchMove = useCallback((event: GestureResponderEvent) => {
    maybeTriggerHistoryTouch(event.nativeEvent.pageY);
  }, [maybeTriggerHistoryTouch]);

  const handleHistoryTouchEnd = useCallback((event: GestureResponderEvent) => {
    // Android may suppress move callbacks when ScrollView is already clamped at offset 0.
    // The completed touch still carries the final coordinate, so apply the same threshold here.
    maybeTriggerHistoryTouch(event.nativeEvent.pageY);
    historyTouchStartYRef.current = null;
    historyTouchTriggeredRef.current = false;
    scheduleHistoryPrependUserHandoffSettle();
    scheduleQueuedLoadEarlierFlush();
    runStickToLatestVerify();
  }, [
    maybeTriggerHistoryTouch,
    runStickToLatestVerify,
    scheduleHistoryPrependUserHandoffSettle,
    scheduleQueuedLoadEarlierFlush,
  ]);

  const handleHistoryTouchCancel = useCallback(() => {
    // An interrupted drag may never emit endDrag. Android's normal native takeover emits
    // touchCancel before beginDrag, so that subsequent beginDrag establishes its own ownership.
    isDraggingRef.current = false;
    historyTouchStartYRef.current = null;
    historyTouchTriggeredRef.current = false;
    scheduleHistoryPrependUserHandoffSettle();
    scheduleQueuedLoadEarlierFlush();
    runStickToLatestVerify();
  }, [runStickToLatestVerify, scheduleHistoryPrependUserHandoffSettle, scheduleQueuedLoadEarlierFlush]);

  // 用户开始拖动 → 标记「上翻意图」,放行自动加载更早(onScrollBeginDrag 仅用户手势触发,
  // 程序化 scrollToEnd 不会触发,故不会误置);同时记录拖动起点 offset,供
  // shouldUnpinMobileFollowOnDrag 判「相对起点累计上移」。
  const handleScrollBeginDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
    richContent?.onScroll();
    reopeningAnchorRef.current = null;
    const nativeMetrics = {
      contentHeight: event.nativeEvent.contentSize.height,
      offsetY: event.nativeEvent.contentOffset.y,
      viewportHeight: event.nativeEvent.layoutMeasurement.height,
    };
    clearProgrammaticScroll();
    isMomentumScrollingRef.current = false;
    isDraggingRef.current = true;
    dragStartOffsetYRef.current = event.nativeEvent.contentOffset.y;
    userScrollForOlderRef.current = true;
    // 新手势 = 允许重新尝试一次自动加载(上次失败 / 无进展的去重记录随手势作废)。
    lastAutoLoadEarlierKeyRef.current = null;
    attemptAutoLoadEarlier(nativeMetrics);
    handoffHistoryPrependToUser();
    // 请求仍在飞或新页仍在做 mVCP 布局时,新的触摸不能提前解除历史锚点保护。
    // 下滑回底的显式按钮/跟随请求会主动清理;普通手势在分页落地后由方向判定恢复。
    // 翻完 refs 立即补一次电平评估:列表已顶死时(Android 无 bounce 尤甚)这次拖动不产生
    // offset 变化,不会有 onScroll / onStartReached,ref 写入也不驱动 effect——没有这一刀,
    // 「失败后停在顶部再拖一下重试」的信号会整体丢失(review P2)。
  }, [attemptAutoLoadEarlier, clearProgrammaticScroll, handoffHistoryPrependToUser, richContent]);

  // 原生 endDrag 自带最终位置,不依赖最后一帧 onScroll 的投递顺序。
  // 先结算本次拖动再清理起点,避免把后续 MVCP 布局校正误判成用户上翻。
  const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
    handleScroll(event, true);
    isDraggingRef.current = false;
    dragStartOffsetYRef.current = null;
    // Wait one frame so Android can report whether this drag transitioned into momentum.
    scheduleHistoryPrependUserHandoffSettle();
    scheduleQueuedLoadEarlierFlush();
    runStickToLatestVerify();
  }, [
    handleScroll,
    runStickToLatestVerify,
    scheduleHistoryPrependUserHandoffSettle,
    scheduleQueuedLoadEarlierFlush,
  ]);

  const handleMomentumScrollBegin = useCallback(() => {
    isMomentumScrollingRef.current = true;
  }, []);

  const handleMomentumScrollEnd = useCallback((event?: NativeSyntheticEvent<NativeScrollEvent>) => {
    // The final native sample can arrive without a matching onScroll event.
    if (event) handleScroll(event);
    isMomentumScrollingRef.current = false;
    scheduleHistoryPrependUserHandoffSettle();
    scheduleQueuedLoadEarlierFlush();
    runStickToLatestVerify();
  }, [
    handleScroll,
    runStickToLatestVerify,
    scheduleHistoryPrependUserHandoffSettle,
    scheduleQueuedLoadEarlierFlush,
  ]);

  useEffect(() => {
    if (!historyPositioning) {
      tailFollowerRef.current?.reset();
      return;
    }
    getTailFollower().reconcile();
  }, [historyPositioning, getTailFollower]);

  const handleStartReached = useCallback(() => {
    attemptAutoLoadEarlier();
  }, [attemptAutoLoadEarlier]);

  // eligibility 变化时重评估:上一页加载结束(disabled 翻 false)、入口点亮(visible 翻 true)、
  // prepend 落地(firstItemKey 变)。覆盖「用户停在顶部等待、无滚动事件」的全部哑火场景;
  // 小页(payload 重试降到 1~5 条)prepend 后仍在近顶区也由此级联补拉,直到填满预取区。
  useEffect(() => {
    attemptAutoLoadEarlier();
  }, [attemptAutoLoadEarlier, loadEarlierEvaluationVersion]);

  const handleListLayout = useCallback((event: LayoutChangeEvent) => {
    const viewportHeight = event.nativeEvent.layout.height;
    if (!Number.isFinite(viewportHeight) || viewportHeight <= 0) return;
    scrollMetricsRef.current = { ...scrollMetricsRef.current, viewportHeight };
    markMobileMvcpSettle();
    if (nearBottomRef.current) runStickToLatestVerify();
    acknowledgeCompanionReadRef.current();
  }, [markMobileMvcpSettle, runStickToLatestVerify]);

  const handleListMetricsChange = useCallback((metrics: LegendListMetrics) => {
    listMetricsRef.current = metrics;
    reconcileReopeningAnchor();
    if (!readingOlderRef.current) return;
    const transaction = historyPrependTransactionRef.current;
    if (!transaction) return;
    if (transaction.pageCommitted) {
      scheduleHistoryAnchorRestore(transaction.generation);
    } else if (
      !isDraggingRef.current
      && !isMomentumScrollingRef.current
      && historyTouchStartYRef.current === null
    ) {
      restoreHistoryAnchorOnce(transaction.generation);
    }
  }, [reconcileReopeningAnchor, restoreHistoryAnchorOnce, scheduleHistoryAnchorRestore]);

  // 记录 contentHeight 供近底判定 fallback + DEV harness 就绪判定;并承担**唯一的贴底跟随**:
  // 内容长高(流式增长、大块一帧撑高、冷开测量结算)时,用户本就贴底(nearBottomRef,与
  // 「跳到底部」浮标同源)则无论这次长多少都跟到底(仿 filo onContentSizeChange → scrollToEnd);
  // 上翻历史时 nearBottomRef=false,不打断。animated:false → 即时跟随、不排队动画。
  // LegendList 内置 maintainScrollAtEnd 已弃用(见 LegendList props 注释),不存在双机制叠加。
  const handleContentSize = useCallback((_width: number, height: number) => {
    reconcileReopeningAnchor();
    markMobileMvcpSettle();
    scrollMetricsRef.current = { ...scrollMetricsRef.current, contentHeight: height };
    // readingOlderRef:load-earlier 的 prepend 也会撑高 contentHeight,但那是顶部增长、不该贴底(review P1)。
    if (readingOlderRef.current) {
      const transaction = historyPrependTransactionRef.current;
      if (transaction) {
        if (transaction.pageCommitted) {
          scheduleHistoryAnchorRestore(transaction.generation);
        } else if (
          !isDraggingRef.current
          && !isMomentumScrollingRef.current
          && historyTouchStartYRef.current === null
        ) {
          // Native MVCP is intentionally disabled before the request starts. Keep the current row
          // pinned while an image/Markdown/live row changes height during that network window.
          restoreHistoryAnchorOnce(transaction.generation);
        }
      }
      return;
    }
    getTailFollower().contentChanged();
    acknowledgeCompanionReadRef.current();
  }, [
    getTailFollower,
    reconcileReopeningAnchor,
    markMobileMvcpSettle,
    restoreHistoryAnchorOnce,
    scheduleHistoryAnchorRestore,
  ]);

  // 首次落底:完整历史已经在列表里。校验到位即显示,native Animated 只作上限兜底。
  // 没有淡入阶段;持续 resize 或复杂 cell 占满 JS 也不能无限延长隐藏。
  useLayoutEffect(() => {
    if (initialAnchorDoneRef.current) return;
    if (listData.length === 0) {
      initialRevealProgress.setValue(1);
      setListRevealed(true);
      return;
    }

    initialAnchorDoneRef.current = true;
    const generation = initialRevealGenerationRef.current + 1;
    initialRevealGenerationRef.current = generation;
    initialRevealAnimationRef.current?.stop();
    initialRevealProgress.setValue(0);
    setListRevealed(false);
    const finish = () => {
      if (initialRevealGenerationRef.current === generation) setListRevealed(true);
    };

    const revealAnimation = Animated.timing(initialRevealProgress, {
      duration: MOBILE_INITIAL_REVEAL_MAX_MS,
      easing: Easing.step1,
      toValue: 1,
      useNativeDriver: true,
    });
    initialRevealAnimationRef.current = revealAnimation;
    revealAnimation.start(() => {
      if (initialRevealAnimationRef.current === revealAnimation) {
        initialRevealAnimationRef.current = null;
      }
      // Native cancellation must also release the initial visibility gate. Once
      // this handle is cleared, positioning cannot reveal the list through it,
      // and a retained list will not rerun initial positioning on reentry.
      // finish() fences callbacks from a previous history or an unmounted list.
      finish();
    });

    // Seek once, then reconcile the bookmark as estimated row heights become measured.
    const saved = !focusedItemKeyRef.current ? reopeningPosition : undefined;
    const savedKey = saved?.anchor?.identityKey
      ? mobileMessageHistoryRowKeyByIdentity(listData, saved.anchor.identityKey) ?? saved.anchor.key
      : saved?.anchor?.key;
    const savedIndex = savedKey ? listData.findIndex(item => item.key === savedKey) : -1;
    if (focusedItemKeyRef.current) {
      // Explicit message navigation owns the first position, even if its row is
      // still being fetched. Do not seek the tail and then jump back to history.
      nearBottomRef.current = false;
      setIsAwayFromBottom(true);
    } else if (saved && !saved.atEnd && savedIndex >= 0) {
      reopeningAnchorRef.current = { anchor: saved.anchor!, expires: Date.now() + 1500, corrections: 0 };
      nearBottomRef.current = false;
      setIsAwayFromBottom(true);
      markProgrammaticScroll(false);
      // One positioning command, using the same list-owned measurement path as message links.
      // Do not enable initialScrollIndex: it conflicts with this list's dynamic measurement.
      void listRef.current?.scrollToIndex({ animated: false, index: savedIndex,
        viewPosition: 0, viewOffset: saved.anchor!.viewportOffset });
      reconcileReopeningAnchor();
    } else {
      nearBottomRef.current = true;
      setIsAwayFromBottom(false);
      scrollToEndProgrammatically(false);
    }
  }, [
    reopeningPosition,
    reconcileReopeningAnchor,
    markProgrammaticScroll,
    initialRevealProgress,
    listData.length,
    scrollResetKey,
    scrollToEndProgrammatically,
  ]);

  // 会话切换(scrollResetKey):重置浮标/近底等 UI 状态;LegendList 本体完整重挂并重新落底。
  // 滚动/自动加载相关的 ref 复位已在渲染期同步块完成(见 prevScrollResetKeyRef,防切会话
  // 竞态误触发自动拉历史),此处不重复。
  useEffect(() => {
    lastAppliedFocusKeyRef.current = null;
    setIsAwayFromBottom(!(reopeningPosition?.atEnd ?? true));
    setHasNewMessages(false);
  }, [scrollResetKey, reopeningPosition]);
  // 卸载时清掉在飞的定时器/rAF(闭包引用 listRef,卸载后触发是无害 no-op,
  // 但不留悬挂句柄)。
  useEffect(() => () => {
    reopeningAnchorRef.current = null;
    if (reopeningFrameRef.current !== null) cancelAnimationFrame(reopeningFrameRef.current);
    initialRevealGenerationRef.current += 1;
    readingOlderRequestGenerationRef.current += 1;
    historyPrependTransactionRef.current = null;
    tailFollowerRef.current?.reset();
    clearProgrammaticScroll();
    if (queuedLoadEarlierFlushFrameRef.current !== null) cancelAnimationFrame(queuedLoadEarlierFlushFrameRef.current);
    if (historyAnchorVerifyFrameRef.current !== null) cancelAnimationFrame(historyAnchorVerifyFrameRef.current);
    if (scrollHistoryEvaluationTimerRef.current !== null) clearTimeout(scrollHistoryEvaluationTimerRef.current);
    initialRevealAnimationRef.current?.stop();
  }, [clearProgrammaticScroll]);

  // 顶部 chrome(如连接横幅)出现/消失 → topPadding 变 → contentContainerStyle.paddingTop 变 →
  // 所有 item 随之上下移。LegendList 的 maintainVisibleContentPosition 只跟 data / item 尺寸变化、
  // 不管容器 padding → 可见消息会跳 padding 差值(迁移前由手搓 scrollToOffset 补偿,一并删了;
  // 此处按差值补回,review P1)。跳过补偿的条件是「近底且非读历史」——此时贴底补滚
  // (handleContentSize)会随后续 contentSize 事件把列表重新拉到底,不重复补;读历史期间
  // 补滚被 readingOlderRef 挡住,即便被判近底(短会话)也必须在这里补,否则 topPadding
  // 变化两边都不处理、可见消息仍跳(review P1 L683)。
  useEffect(() => {
    const prev = prevTopPaddingRef.current;
    prevTopPaddingRef.current = topPadding;
    const delta = topPadding - prev;
    if (delta === 0 || (nearBottomRef.current && !readingOlderRef.current)) return;
    // The bookmark resolver already includes current top padding. A relative
    // compensation here would cancel its scrollToIndex using stale native metrics.
    if (reopeningAnchorRef.current) {
      reconcileReopeningAnchor();
      return;
    }
    if (!initialAnchorDoneRef.current || nativeScrollEventSequenceRef.current === 0) return;
    const { offsetY } = scrollMetricsRef.current;
    scrollToOffsetProgrammatically(Math.max(0, offsetY + delta), false);
  }, [reconcileReopeningAnchor, scrollToOffsetProgrammatically, topPadding]);

  // 深链/搜索:滚到指定消息(LegendList scrollToIndex 自带 offscreen 处理,无需 rAF/失败兜底)。
  useEffect(() => {
    if (!focusedItemKey || !focusRunKey) {
      lastAppliedFocusKeyRef.current = null;
      return;
    }
    if (lastAppliedFocusKeyRef.current === focusRunKey) return;
    const index = listData.findIndex((item) => item.key === focusedItemKey);
    if (index < 0) return;
    lastAppliedFocusKeyRef.current = focusRunKey;
    reopeningAnchorRef.current = null;
    // 深链 / 搜索定位是明确的历史浏览意图。定位后落在近顶区时继续自动补页,
    // 不要求用户再拖动一次才能看到目标上方上下文。
    userScrollForOlderRef.current = true;
    lastAutoLoadEarlierKeyRef.current = null;
    nearBottomRef.current = false;
    setIsAwayFromBottom(true);
    const generation = initialRevealGenerationRef.current;
    // Initial navigation lands without an animated trip across unrelated rows.
    // Reveal on the list's positioning completion, not a fixed waiting period.
    void Promise.resolve(scrollToIndexProgrammatically(index, 0.45, listRevealed && !initialRevealAnimationRef.current)).then(() => {
      if (initialRevealGenerationRef.current === generation && lastAppliedFocusKeyRef.current === focusRunKey) {
        revealPositionedHistory();
      }
    }, () => { /* The existing bounded reveal fallback handles a failed native seek. */ });
  }, [
    focusRunKey,
    focusedItemKey,
    listData,
    listRevealed,
    revealPositionedHistory,
    scrollToIndexProgrammatically,
  ]);

  // 新消息红点:滚离底时来新消息(尾部 append)→ 提示。贴底时由 handleContentSize 补滚
  // 自动跟随、不提示。wasNearBottom 只看 nearBottomRef(跟随态唯一真相):以前 || 距离兜底
  // 会在「意图解除后仍停在近底阈值带内」时把状态判回跟随——标志说在跟、补滚却已解除,
  // 红点被吞。ref 由 handleScroll / 意图解除 / 跳转路径维护,冷开与切会话初始为 true,
  // 无需距离兜底。
  useEffect(() => {
    const decision = evaluateMessageWindowUpdate({
      previousKeys: previousItemKeysRef.current,
      nextKeys: itemKeys,
      wasNearBottom: nearBottomRef.current,
    });
    if (decision.preserveVisibleAnchor && userScrollForOlderRef.current) {
      // Belt-and-suspenders for externally initiated prepends: preserve the reader's anchor even
      // when data arrived without passing through requestLoadEarlier in this renderer.
      nearBottomRef.current = false;
      setIsAwayFromBottom(true);
    }
    if (!focusedItemKey && decision.shouldAutoFollow && decision.autoFollowTarget === 'content-end') {
      setHasNewMessages(false);
      setIsAwayFromBottom(false);
    } else if (decision.showNewMessageIndicator) {
      setHasNewMessages(true);
    }
    previousItemKeysRef.current = itemKeys;
  }, [focusedItemKey, itemKeys]);

  const handleLoadEarlierPress = useCallback(() => {
    userScrollForOlderRef.current = true;
    lastAutoLoadEarlierKeyRef.current = null;
    requestLoadEarlier();
  }, [requestLoadEarlier]);

  const renderMessageItem = useCallback(({ item }: { item: MobileMessageRenderItem }) => {
    if (__DEV__ || mobileDebugEnabled()) recordMobileMessageRenderItem();
    return (
      <RenderListItemView
        actions={actions}
        focused={item.key === focusedItemKey}
        item={item}
      />
    );
  }, [actions, focusedItemKey]);
  // pending_send 的展开态不改变 listData;LegendList 会复用现有行,单靠 renderItem
  // 闭包更新不足以保证可见行重绘。把选中项显式纳入 extraData,确保轻点气泡后
  // 「取消 / 编辑 / 插话」操作行立即出现,不依赖滚动触发回收重渲染。
  const messageListExtraData = useMemo(
    () => ({
      ...buildMobileMessageListExtraData(
        pendingSend?.selectedClientId ?? null,
        shareSelectionActive === true,
      ),
      // Resource discovery can complete after history has already populated the list.
      // Update visible cells when a task is identified as a companion chat.
      companion,
      companionWorkingLabel,
      showPluginInvocations,
      companionPluginWork,
    }),
    [pendingSend?.selectedClientId, shareSelectionActive, companion, companionWorkingLabel, showPluginInvocations, companionPluginWork],
  );
  // Keep production and regular DEV screens on keyed remounts. With Fabric,
  // recycling an Android container across heterogeneous message trees can race
  // native detach/attach batches and try to mount a child that still belongs to
  // the previous row. listperf keeps the DEV-only override for explicit A/Bs.
  const recycleItems = __DEV__ ? devRecycleItems === true : false;
  // 贴底跟随时数据变化不做可见位置锚定:重连补同步会整批替换 / 丢弃尾部行,锚定会把旧的可见行
  // 钉在原屏幕位置,先露出新内容的开头(甚至列表顶部)再被贴底跟随拉回,表现为「跳一下又跳回来」。
  // 不锚定时内容变短由原生滚动范围直接截到新底部,变长由贴底跟随补滚。读历史(离开底部,或
  // 「加载更早」事务进行中——它可能由自动补齐在贴底时发起)仍靠锚定保住正在看的行。
  // readingOlderRef 在事务开始与结束时都会伴随一次重渲染(loadingEarlier / 事务收尾的 state),
  // 这里在渲染期读取它足以让 prepend 那次数据提交带上锚定。
  const anchorVisibleRowsOnDataChange = isAwayFromBottom || readingOlderRef.current;

  return (
    // chat-text-quote:Provider 恒挂载(值可为 null),避免启用态翻转时整棵消息树
    // 因 Provider 增删而重挂;value 稳定(useMemo),不触发订阅方重渲。
    <SelectionQuoteContext.Provider value={selectionQuoteContextValue}>
    <RichContentContext.Provider value={richContent}>
    <MessageListVisibilityContext.Provider value={messageListVisibility}>
    <MarkdownRemoteMediaContext.Provider value={onResolveRemoteMedia}>
    <View
      style={styles.messageFrame}
      onTouchStart={handleHistoryTouchStart}
      onTouchMove={handleHistoryTouchMove}
      onTouchEnd={handleHistoryTouchEnd}
      onTouchCancel={handleHistoryTouchCancel}
    >
      <Animated.View style={[styles.messageList, { opacity: initialRevealOpacity }]}>
      <LegendList
        keyboardShouldPersistTaps="handled"
        // 与 main 一致:每个任务用完整历史重挂;首次命令式落底在 opacity 遮罩下完成。
        key={scrollResetKey}
        data={listData}
        extraData={messageListExtraData}
        getItemType={mobileMessageListItemType}
        onItemSizeChanged={reconcileReopeningAnchor}
        keyExtractor={(item) => item.key}
        renderItem={renderMessageItem}
        recycleItems={recycleItems}
        estimatedItemSize={MOBILE_MESSAGE_ESTIMATED_ITEM_SIZE}
        drawDistance={MOBILE_MESSAGE_DRAW_DISTANCE}
        // initialScrollAtEnd / initialScrollIndex 的程序化滚动在特定
        // 内容形态下会与布局结算互相触发,形成无限 onScroll 风暴把 JS 线程打满——表现为
        // 冷开会话消息区空白、无 loading、返回键无响应,只能杀 App(2026-07 模拟器逐项
        // 二分实锤,3.3.2 / 3.3.3 均复现)。
        alignItemsAtEnd
        maintainScrollAtEnd={false}
        // iOS uses LegendList/RN's atomic data/size anchoring while reading history. Android history
        // prepends temporarily disable the whole prop because RN exposes one native switch: leaving
        // either flag on would race the app-owned key/offset correction there.
        maintainVisibleContentPosition={historyPrependNativeMvcpDisabled
          ? false
          : { data: anchorVisibleRowsOnDataChange, size: true }}
        contentContainerStyle={[
          styles.messages,
          { paddingBottom: bottomPadding, paddingTop: topPadding },
          viewportLayout.wideViewport && styles.messagesWide,
          viewportLayout.wideViewport && { maxWidth: viewportLayout.contentMaxWidth },
        ]}
        ListEmptyComponent={syncingWhileEmpty
          ? <SyncingMessages />
          : <EmptyMessages testID={emptyTestID} copy={emptyMessage} />}
        ListHeaderComponent={
          loadEarlierAction.visible ? (
            <MessageListActionButton
              accessibilityLabel={loadEarlierAction.accessibilityLabel}
              disabled={loadEarlierAction.disabled}
              onPress={handleLoadEarlierPress}
              style={styles.loadEarlierButton}
              testID="message.loadEarlierButton"
            >
              <Text style={styles.loadEarlierText}>{loadEarlierAction.label}</Text>
            </MessageListActionButton>
          ) : null
        }
        ListFooterComponent={queueFooter ? <>{queueFooter}</> : null}
        onLayout={handleListLayout}
        onMetricsChange={handleListMetricsChange}
        onContentSizeChange={handleContentSize}
        onScroll={handleScroll}
        onScrollBeginDrag={handleScrollBeginDrag}
        onScrollEndDrag={handleScrollEndDrag}
        onMomentumScrollBegin={handleMomentumScrollBegin}
        onMomentumScrollEnd={handleMomentumScrollEnd}
        onStartReached={handleStartReached}
        onStartReachedThreshold={2}
        scrollEventThrottle={16}
        ref={listRef}
        style={styles.messageList}
        testID={testID ?? 'message.list'}
        viewabilityConfig={viewabilityConfigRef.current}
        onViewableItemsChanged={handleViewableItemsChanged}
        renderScrollComponent={renderScrollComponent}
      />
      </Animated.View>
      {shareSelectionActive && stickyShareClientId ? (
        // 与分享消息行同构,保持吸顶 check 和行内 check 水平对齐。
        <View
          pointerEvents="box-none"
          style={[styles.stickyShareOverlay, { top: (topOverlayHeight ?? 0) + spacing.sm }]}
          testID="message.shareStickyCheck"
        >
          <View
            pointerEvents="box-none"
            style={[styles.stickyShareControl, { marginLeft: wideContentInset + spacing.lg }]}
          >
            <ShareMessageCheckbox
              clientId={stickyShareClientId}
              disabled={shareSelectionBusy === true}
            />
          </View>
        </View>
      ) : null}
      {hasNewMessages || showJumpToLatest ? (
        // 跳到底部浮标(Telegram 风):右下角半透明圆形 chevron,弱存在感;
        // 有未读新消息时不换样式,只在圆标右上角加一颗 CTA 色小圆点提示。
        <MessageListActionButton
          accessibilityLabel={hasNewMessages ? t('message.renderer.newMessagesToBottom') : t('message.renderer.jumpToBottom')}
          onPress={scrollToBottom}
          style={[styles.scrollToBottomFab, { bottom: floatingBottomOffset, right: scrollToBottomFabRight }]}
          testID={hasNewMessages ? 'message.newMessageButton' : 'message.jumpToLatestButton'}
        >
          <ChevronDown color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.regular} />
          {hasNewMessages ? <View style={styles.scrollToBottomDot} testID="message.newMessageDot" /> : null}
        </MessageListActionButton>
      ) : null}
      {imageLightboxOpen && payload?.kind === 'media' && lightboxImages ? (
        // 图片 / 视频走 IM 级全屏查看器(手势缩放/下滑关闭/横滑翻页);其余 payload 走通用查看器。
        <ImageLightbox
          annotation={imageAnnotation}
          images={lightboxImages}
          initialImageKey={initialLightboxImage?.key ?? payload.galleryImageKey}
          initialUrl={initialLightboxImage?.url ?? payload.media.url}
          onClose={closePayload}
          onReleaseRemoteMedia={onReleaseRemoteMedia}
          onResolveRemoteMedia={onResolveRemoteMedia}
          onShareImage={onShareImage}
        />
      ) : (
        <MessagePayloadModal
          imageAnnotation={imageAnnotation}
          onClose={closePayload}
          onReadTextFilePreview={onReadTextFilePreview}
          onReleaseRemoteMedia={onReleaseRemoteMedia}
          onResolveRemoteMedia={onResolveRemoteMedia}
          onShareImage={onShareImage}
          payload={historyActive ? payload : null}
        />
      )}
    </View>
    </MarkdownRemoteMediaContext.Provider>
    </MessageListVisibilityContext.Provider>
    </RichContentContext.Provider>
    </SelectionQuoteContext.Provider>
  );
}

const RenderItemView = memo(function RenderItemView({
  item,
  actions,
  focused = false,
}: {
  item: MobileMessageRenderItem | MobileWorkChildItem;
  actions: MessageActions & { firstUserMessageClientId?: string };
  focused?: boolean;
}) {
  const styles = useThemedStyles(makeStyles);
  // 「user 行渲染系统卡」形态(silent-stop 自动续跑 agentMeta.autoResume):渲染层
  // 降级为 kind='system' 再进 MessageBubble——presentation 的 isUserAligned 判定是
  // `align==='user' || kind==='user'`,保持 user kind 会右对齐成用户气泡并挂上
  // fork / rewind 等 user 操作行(对齐桌面 MessageStream 提前 return SystemCard 的
  // 语义,review P2)。只是渲染拷贝,normalize 层 kind='user' 的 turn 边界不受影响;
  // useMemo 保引用稳定,不破坏 MessageBubble 的 memo。
  const systemCardUserItem = useMemo(
    () => (
      item.type === 'message'
        && !item.message.orcaCard
        && item.message.kind === 'user'
        && item.message.systemCardType
        ? { ...item, message: { ...item.message, kind: 'system' as const } }
        : null
    ),
    [item],
  );
  // 旧 Hook(落库正文是拼好的 Agent prompt)降级为左对齐系统卡,不挂 fork / rewind /
  // delete 等用户操作;本机 IM 落库的是用户原文(userTextContent),保持 user kind 与普通
  // 用户消息的全部操作,只在 MessageBubble 里换成左对齐的「Cindy · 来自 X」卡片。
  const hookSourceUserItem = useMemo(
    () => (
      item.type === 'message'
        && item.message.kind === 'user'
        && item.message.hookSource
        && !item.message.hookSource.userTextContent
        ? { ...item, message: { ...item.message, kind: 'system' as const, align: 'agent' as const } }
        : null
    ),
    [item],
  );
  let node: ReactNode;
  switch (item.type) {
    case 'message':
      node = item.message.authorization
        ? <AuthorizationMessageCard message={item.message} />
        : item.message.companion
        ? <CompanionMessageCard message={item.message} deviceId={actions.remoteDeviceId ?? ''}
            renderMarkdown={(text) => <CompanionCardMarkdown messageKey={item.key} text={text} actions={actions} />} />
        : item.message.orcaCard
        ? (
          <>
            {item.message.sessionOrigin ? (
              <SessionOriginLabel align="agent" origin={item.message.sessionOrigin} onOpen={actions.onOpenOriginSession} />
            ) : null}
            <OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth}
              blockKey={JSON.stringify([actions.remoteDeviceId, item.key])} />
          </>
        )
        : <MessageBubble item={hookSourceUserItem ?? systemCardUserItem ?? item} actions={actions} />;
      break;
    case 'thinking':
      node = (
        <ThinkingCard
          item={item}
          screenWidth={actions.screenWidth}
          isSessionStreaming={actions.isSessionStreaming === true}
        />
      );
      break;
    case 'tool_group':
      node = <ToolGroupCard item={item} actions={actions} />;
      break;
    case 'tool_media':
      node = <ToolMediaBlock item={item} actions={actions} />;
      break;
    case 'todo':
      node = (
        <TodoCard
          animated={item.isStreaming === true}
          item={item}
          screenWidth={actions.screenWidth}
        />
      );
      break;
    case 'agent_task':
      node = <AgentTaskCard item={item} screenWidth={actions.screenWidth} />;
      break;
    case 'work_group':
      node = <WorkGroupCard item={item} actions={actions} />;
      break;
    case 'subagent_group':
      node = <SubagentCard item={item} actions={actions} />;
      break;
    case 'fork_origin':
      node = <ForkOriginMarker onOpenForkOrigin={actions.onOpenForkOrigin} />;
      break;
    case 'pending_send':
      // 待发送气泡。actions.pendingSend 由会话页恒传;真缺失时**跳过这一项**(不渲染),
      // 而不是渲染一个点不动的气泡 —— 没有回调的气泡无法取消 / 编辑 / 重试,画出来只会
      // 让用户对着死气泡操作。渲染路径无 ErrorBoundary,这里也不抛,免得整列崩掉。
      node = actions.pendingSend
        ? (
          <PendingSendBubble
            actions={actions.pendingSend}
            item={item}
            renderReplyQuote={actions.companionQuoteActions ? (quote) => (
              <View style={styles.companionQuote}>
                <BotGroupQuote display={companionReplyQuoteDisplay(quote,
                  actions.companionQuoteActions!.getMessage(quote.clientId), actions.companionQuoteActions!.names)}
                  onPress={() => actions.companionQuoteActions!.onLocate(quote.clientId)} />
              </View>
            ) : undefined}
            onOpenImage={actions.onOpenPayload}
            screenWidth={actions.screenWidth}
            viewerDeviceId={actions.viewerDeviceId}
            renderImage={(uri, sourceUri, onError) => uri ? (
              <PendingAttachmentImage key={sourceUri ?? uri}
                layout={buildMessageContentLayout({ screenWidth: actions.screenWidth })}
                uri={uri}
                sourceUri={sourceUri ?? uri}
                onError={onError}
              />
            ) : (
              <View style={[styles.attachmentImagePending, {
                width: buildMessageContentLayout({ screenWidth: actions.screenWidth }).attachmentImageMaxWidth,
                height: buildMessageContentLayout({ screenWidth: actions.screenWidth }).attachmentImageMaxHeight,
              }]} />
            )}
            renderFile={(name, index) => (
              <FileChip key={`${name}:${index}`} name={name} presentationOnly
                layout={buildMessageContentLayout({ screenWidth: actions.screenWidth })} />
            )}
            renderText={(text, index) => (
              <MarkdownBody key={`text:${index}`} text={text} streaming={false}
                selectable={false} pinContentWidth={false}
                layout={buildMessageContentLayout({ screenWidth: actions.screenWidth })} />
            )}
            resolveRemoteMedia={actions.onResolveRemoteMedia}
          />
        )
        : null;
      break;
    default:
      // 穷尽性保证:给 render-item union 加新变体却漏处理 → typecheck 报错(入参 never)。运行时降级为
      // log+skip(node 保持空)而非 throw —— render 路径无 ErrorBoundary,不能让单个未知 item 崩整列。
      logUnhandledRenderItem(item);
      break;
  }
  const groupTimestamp = actions.companion && (item.type === 'message' || item.type === 'pending_send')
    ? actions.companionTimeGroups?.get(item.key) : undefined;
  // Cards and work groups share the reply text column, leaving the avatar slot empty.
  const alignWithReplies = !!actions.companionAvatar && actions.companion
    && (item.type === 'work_group' || (item.type === 'message' && !!item.message.companion));
  const aligned = alignWithReplies ? <View style={styles.companionAvatarInset}>{node}</View> : node;
  // Your own send eases in once, as its local bubble (both chats). Its echo keeps the same key and
  // wrapper, so it neither remounts nor replays. Companion chats also ease in a new message or
  // finished reply (M4 / M5).
  const localSendAt = item.type === 'pending_send' || item.type === 'message'
    ? localSendStartedAt(item.key) : null;
  const entering = localSendAt !== null
    ? <CompanionEntering key={item.key} id={item.key} createdAt={localSendAt} kind="send">{aligned}</CompanionEntering>
    : actions.companion && item.type === 'message' && !item.message.systemCardType
    && (item.message.kind === 'user' || item.message.kind === 'assistant')
    ? <CompanionEntering key={item.key} id={item.key} createdAt={item.message.createdAt} kind={item.message.kind === 'user' ? 'send' : 'reply'}>{aligned}</CompanionEntering>
    : aligned;
  return (
    <View style={focused ? styles.focusedItem : undefined} testID={focused ? 'message.focusedItem' : undefined}>
      {groupTimestamp !== undefined ? <CompanionTimeGroupStamp timestamp={groupTimestamp} /> : null}
      {entering}
    </View>
  );
});

const RenderListItemView = memo(function RenderListItemView({
  item,
  actions,
  focused,
}: {
  item: MobileMessageRenderItem;
  actions: MessageActions & { firstUserMessageClientId?: string };
  focused: boolean;
}) {
  const isViewable = useMessageListItemVisible(item.key);
  const heavyContentVisible = focused || isViewable;
  // 本项(含 work_group / subagent 内层)点开的 payload 都带上顶层 key 作来源:
  // 看图器按它取「同一条消息」的图集,不靠 url 反查(同一 url 会再出现在后面的消息里)。
  const openPayloadFromItem = actions.onOpenPayloadFromItem;
  const itemActions = useMemo(() => (openPayloadFromItem
    ? { ...actions, onOpenPayload: (next: MessagePayload) => openPayloadFromItem(next, item.key) }
    : actions), [actions, item.key, openPayloadFromItem]);
  return (
    <MessageHeavyContentVisibilityContext.Provider value={heavyContentVisible}>
      <RenderItemView actions={itemActions} focused={focused} item={item} />
    </MessageHeavyContentVisibilityContext.Provider>
  );
});

/**
 * 气泡外的来源标签(任务 / 自动化 / 插件 / 设备共用):有 ID 时长按就地显示 ID(可选中复制),
 * 读屏在提示里直接读出 ID;脱敏后没有 ID 的来源保持静态展示。对齐桌面悬停给出 ID。
 * 标签挂在气泡外——气泡本身不能挂 Pressable(会干扰正文横向滚动手势)。
 */
function SourceLabelWithId({
  accessibilityLabel,
  align,
  icon,
  label,
  idText,
  onPress,
  openHint,
  testID,
}: {
  /** 读屏标签;缺省读 label。 */
  accessibilityLabel?: string;
  align: 'user' | 'agent';
  icon?: ReactNode;
  label: string;
  idText?: string;
  onPress?: () => void;
  openHint?: string;
  testID: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const [idVisible, setIdVisible] = useRecyclingState(false);
  const hint = [onPress ? openHint : undefined, idText].filter(Boolean).join(' ');
  return (
    <View style={[styles.sourceLabelStack, align === 'user' ? styles.sourceLabelStackUser : null]}>
      <Pressable
        accessibilityHint={hint || undefined}
        accessibilityLabel={accessibilityLabel ?? label}
        accessibilityRole={onPress ? 'button' : 'text'}
        disabled={!onPress && !idText}
        hitSlop={8}
        onLongPress={idText ? () => setIdVisible((visible) => !visible) : undefined}
        onPress={onPress}
        style={styles.automationOriginRow}
        testID={testID}
      >
        {icon}
        <Text numberOfLines={1} style={styles.automationOriginText}>{label}</Text>
      </Pressable>
      {idVisible && idText ? (
        <Text selectable style={styles.automationOriginText} testID={`${testID}Id`}>{idText}</Text>
      ) : null}
    </View>
  );
}

/** 另一个任务经工具发来的消息:气泡上方的来源标签,点按跳来源任务(对齐桌面 AutomationOriginBadge)。 */
function SessionOriginLabel({
  align,
  origin,
  onOpen,
  sourceMeta,
}: {
  align: 'user' | 'agent';
  origin: NonNullable<NormalizedRemoteMessage['sessionOrigin']>;
  onOpen?: (sessionId: string) => void;
  /** 原始 agentMeta:长按 ID 与桌面悬停、排队行同源(伙伴给伙伴 ID + 任务 ID)。 */
  sourceMeta?: unknown;
}) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const senderSessionId = origin.senderSessionId;
  return (
    <SourceLabelWithId
      align={align}
      icon={<Send color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.thin} />}
      idText={sourceIdText(sourceMeta)
        ?? (senderSessionId ? t('message.renderer.sourceSessionId', { id: senderSessionId }) : undefined)}
      label={sessionOriginLabel(origin)}
      onPress={onOpen && senderSessionId && !isCrossDeviceSourceSessionId(senderSessionId)
        ? () => onOpen(senderSessionId)
        : undefined}
      openHint={t('message.renderer.openSessionOrigin')}
      testID="message.sessionOrigin"
    />
  );
}

/** 自动化注入的消息:气泡上方的来源标签(手机版不跳自动化页);脱敏来源没有 ID,静态展示。 */
function AutomationOriginLabel({
  align,
  origin,
}: {
  align: 'user' | 'agent';
  origin: NonNullable<NormalizedRemoteMessage['automationOrigin']>;
}) {
  const { colors } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  const label = useMemo(() => automationOriginLabel(origin), [origin, i18nInstance.language]);
  return (
    <SourceLabelWithId
      align={align}
      icon={<Timer color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.thin} />}
      idText={origin.scheduleId ? t('message.renderer.sourceAutomationId', { id: origin.scheduleId }) : undefined}
      label={label}
      testID="message.automationOrigin"
    />
  );
}

/**
 * 手机或另一台电脑远程操作主机时发来的消息:气泡外的设备标签(样式同其它来源标签)。
 * 点按打开设备详情;长按就地显示设备 ID。
 */
function SourceDeviceLabel({
  align,
  device,
  onOpen,
}: {
  align: 'user' | 'agent';
  device: MessageSourceDevice;
  onOpen?: (deviceId: string) => void;
}) {
  const { colors } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  const directory = useRemoteDeviceIdentity();
  const label = useMemo(
    () => sourceDeviceLabel(device, directory),
    // 文案走 i18n.t,语言进依赖。
    [device, directory, i18nInstance.language],
  );
  const Icon = device.platform === 'mobile' ? Smartphone : Monitor;
  return (
    <SourceLabelWithId
      align={align}
      icon={<Icon color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.thin} />}
      idText={t('message.renderer.sourceDeviceId', { id: device.deviceId })}
      label={label}
      onPress={onOpen ? () => onOpen(device.deviceId) : undefined}
      openHint={t('message.renderer.openSourceDeviceHint', { id: device.deviceId })}
      testID="message.sourceDevice"
    />
  );
}

/** 插件任务派发的消息:气泡外的来源标签;与气泡内的本轮插件调用头(PluginInvocationHeader)是两回事。 */
function SourcePluginLabel({ align, plugin }: { align: 'user' | 'agent'; plugin: MessageSourcePlugin }) {
  const { colors } = useTheme();
  const { i18n: i18nInstance } = useTranslation();
  const label = useMemo(() => sourcePluginLabel(plugin), [plugin, i18nInstance.language]);
  return (
    <SourceLabelWithId
      align={align}
      icon={<Ghost color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.thin} />}
      idText={sourceIdText({ sourcePlugin: plugin })}
      label={label}
      testID="message.sourcePlugin"
    />
  );
}

function ForkOriginMarker({ onOpenForkOrigin }: { onOpenForkOrigin?: () => void }) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  return (
    <View style={styles.forkOriginRow} testID="message.forkOrigin">
      <View style={styles.forkOriginLine} />
      <MessageListActionButton
        accessibilityLabel={t('message.renderer.openForkOrigin')}
        onPress={onOpenForkOrigin}
        style={styles.forkOriginButton}
        testID="message.forkOriginButton"
      >
        <Split color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
        <Text style={styles.forkOriginText}>{t('message.renderer.viewForkOrigin')}</Text>
      </MessageListActionButton>
      <View style={styles.forkOriginLine} />
    </View>
  );
}

function EmptyMessages({ testID, copy }: { testID?: string; copy?: string }) {
  const styles = useThemedStyles(makeStyles);
  const { t } = useTranslation();
  return (
    <View style={styles.emptyCard} testID={testID ?? 'message.empty'}>
      <Text style={styles.emptyTitle}>{copy ?? t('message.renderer.emptyMessages')}</Text>
    </View>
  );
}

function SyncingMessages() {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  return (
    <View style={styles.emptyCard} testID="message.syncing">
      <ActivityIndicator color={colors.textTertiary} size="small" />
      <Text style={styles.syncingTitle}>{t('message.renderer.syncing')}</Text>
    </View>
  );
}

const AnimatedPressable = Animated.createAnimatedComponent(Pressable);

function MessageListActionButton({
  accessibilityLabel,
  children,
  disabled = false,
  onPress,
  style,
  testID,
}: {
  accessibilityLabel: string;
  children: ReactNode;
  disabled?: boolean;
  onPress?: () => void;
  style?: StyleProp<ViewStyle>;
  testID?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const interactionDisabled = disabled || !onPress;
  // mount 入场:150ms 淡入 + 0.92→1 轻缩放(浮标条件挂载,此前瞬间硬现)。
  // 单 Value 同驱 opacity/scale,native driver 一次性动画;reduce-motion
  // (含 null 未知态)从 1 起步不播。消失走 unmount 直接卸,不做 exit。
  const reduceMotionEnabled = useReduceMotionEnabled();
  const appear = useRef(new Animated.Value(reduceMotionEnabled === false ? 0 : 1)).current;
  useEffect(() => {
    if (reduceMotionEnabled !== false) {
      appear.setValue(1);
      return;
    }
    Animated.timing(appear, {
      duration: motionDuration.fast,
      easing: Easing.bezier(...motionEasing.out),
      isInteraction: false,
      toValue: 1,
      useNativeDriver: true,
    }).start();
    // 仅 mount 播一次:reduceMotionEnabled 运行中翻转不重放入场。
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const appearStyle = {
    opacity: appear,
    transform: [{ scale: appear.interpolate({ inputRange: [0, 1], outputRange: [0.92, 1] }) }],
  };
  // pressed 用受控 state 而非函数型 style:createAnimatedComponent 只解析
  // 静态 props 里的 AnimatedNode,函数型 style 的返回值不会被解析,
  // Animated.Value 会以原始对象漏进底层 View 的 style(非法 prop)。
  const [pressed, setPressed] = useState(false);
  return (
    <AnimatedPressable
      accessibilityLabel={accessibilityLabel}
      accessibilityRole="button"
      accessibilityState={{ disabled: interactionDisabled }}
      disabled={interactionDisabled}
      onPress={interactionDisabled ? undefined : onPress}
      onPressIn={() => setPressed(true)}
      onPressOut={() => setPressed(false)}
      style={[
        style,
        appearStyle,
        pressed && !interactionDisabled && styles.pressed,
        interactionDisabled && styles.disabled,
      ]}
      testID={testID}
    >
      {children}
    </AnimatedPressable>
  );
}

function MessageBubble({
  item,
  actions,
}: {
  item: MobileMessageItem;
  actions: MessageActions & { firstUserMessageClientId?: string };
}) {
  const { colors: userBubbleColors } = useUserBubbleAppearance();
  const { user: viewer } = useAuth();
  const styles = useThemedStyles(makeStyles);
  const { colors, mode } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  const [copyState, setCopyState] = useRecyclingState<CopyMessageStatus | 'idle' | 'copying'>('idle');
  const [actionSheetOpen, setActionSheetOpen] = useRecyclingState(false);
  const historyActive = useMessageHistoryActive();
  useEffect(() => {
    if (!historyActive) setActionSheetOpen(false);
  }, [historyActive, setActionSheetOpen]);
  // chat-text-quote:只解析持久化 quotesEncoded 明确标记的产品引用消息,避免
  // 把用户手写的 Markdown blockquote 误当产品引用。兼容 desktop 的交错
  // marker 块和 mobile 的前置引用。旧 markerless 消息保持 leading-only,
  // 避免把正文里的用户 Markdown blockquote 误当产品引用。手机版逐条渲染紧凑
  // quote chip,正文不泄露内部 marker/source 行;fork / rewind 直接携带完整
  // ComposerDocument,无损恢复 quote、pasted-text 与 Slash。orca 协同消息已走
  // orcaCard 分支,不进本路径。
  const quoteSegments = useMemo(
    () => (item.message.kind === 'user'
      && item.message.quotesEncoded === true
      && !item.message.systemCardType
      && item.message.body
      ? parseChatQuoteSegments(item.message.body)
      : []),
    [
      item.message.body,
      item.message.kind,
      item.message.quotesEncoded,
      item.message.systemCardType,
    ],
  );
  const messageQuotes = quoteSegments.flatMap((segment) => (
    segment.kind === 'quote' ? [segment.quote] : []
  ));
  const bubbleBody = messageQuotes.length > 0
    ? joinChatQuoteTextSegments(quoteSegments)
    : item.message.errorSummaryKey ? t(item.message.errorSummaryKey) : item.message.body;
  const sentInlineTokens = useMemo(
    () => (item.message.kind === 'user'
      ? buildVisibleSentInlineTokens(
          item.message.body,
          quoteSegments.length > 0
            ? quoteSegments
            : item.message.body ? [{ kind: 'text' as const, text: item.message.body }] : [],
          item.message.pastedTextRanges,
          item.message.slashCommandRanges,
        )
      : []),
    [
      item.message.body,
      item.message.kind,
      item.message.pastedTextRanges,
      item.message.slashCommandRanges,
      quoteSegments,
    ],
  );
  const hasSentInlineAtoms = sentInlineTokens.some((token) => token.kind !== 'text');
  const rendersSentInlineBody = hasSentInlineAtoms;
  const displayBubbleBody = hasSentInlineAtoms
    ? sentInlineTokensDisplayText(sentInlineTokens)
    : bubbleBody;
  const draftBody = item.message.draftBody ?? item.message.body;
  const draftText = item.message.draftBody ?? bubbleBody;
  const composerDraftDocument = useMemo(
    () => (item.message.kind === 'user'
      ? composerDocumentFromSerializedMessage(draftBody, {
          quotesEncoded: item.message.quotesEncoded,
          agentReferences: item.message.agentReferences,
          pastedTextRanges: item.message.pastedTextRanges,
          slashCommandRanges: item.message.slashCommandRanges,
        })
      : null),
    [
      draftBody,
      item.message.agentReferences,
      item.message.kind,
      item.message.pastedTextRanges,
      item.message.quotesEncoded,
      item.message.slashCommandRanges,
    ],
  );
  const presentation = summarizeMessageBubblePresentation({
    align: item.message.align,
    attachmentCount: item.message.attachments?.length ?? 0,
    body: displayBubbleBody,
    hasSystemCard: !!item.message.systemCardType,
    isStreaming: item.message.isStreaming,
    kind: item.message.kind,
    mediaCount: item.message.media?.length ?? 0,
    secondaryBody: item.message.secondaryBody,
  });
  // IM 来源卡片(本机 IM 保留 user kind 以挂普通用户操作)与桌面一样左对齐。
  const isUser = presentation.isUserAligned && !item.message.hookSource;
  const isStreamingAssistant = item.message.kind === 'assistant' && item.message.isStreaming === true;
  const clientId = messageClientId(item);
  const shareableMessage = isShareableMessage(item.message);
  const handleShareableMessageViewChange = useCallback((view: View | null) => {
    actions.onShareableMessageViewChange?.(clientId, view);
  }, [actions.onShareableMessageViewChange, clientId]);
  const shareSelectionActive = actions.shareSelectionActive === true
    && shareableMessage;
  const isFirstUserMessage = item.message.kind === 'user' && clientId === actions.firstUserMessageClientId;
  const rawCopyText = buildMobileMessageCopyText(item.message);
  const copyText = item.message.kind === 'assistant' ? richAnswerText(rawCopyText) : rawCopyText;
  const canUseCompletedActions = !isStreamingAssistant;
  // 操作行只挂在每轮收尾正文、且该行确实是一条发言(判据见
  // mobileMessageShowsActionBar):中间句不再逐条带复制/分叉/时间,系统边界卡整行
  // 不挂。分享态只保留与导出图片一致的消息内容,不显示操作图标、时间或费用。
  // 流式回复不显示操作,但保留最终操作行的占位,收尾时不把正在看的正文推走。
  const showCompletedActionBar = !shareSelectionActive && mobileMessageShowsActionBar({
    hasSystemCard: !!item.message.systemCardType,
    isStreamingAssistant,
    isTurnFinalAssistant: item.message.isTurnFinalAssistant === true,
    kind: item.message.kind,
  });
  const canCopy = showCompletedActionBar && copyText.trim().length > 0;
  const canSelectVisibleText = canUseCompletedActions && copyText.trim().length > 0;
  const relativeTime = showCompletedActionBar ? formatMessageRelativeTime(item.message.createdAt) : '';
  const absoluteTime = formatMessageAbsoluteTime(item.message.createdAt);
  const turnCost = showCompletedActionBar && item.message.kind === 'assistant'
    ? formatMessageTurnCost(item.message.turnMoney)
    : '';
  // 金额缺席时退回显示本轮 token(桌面算不出模型报价的轮次):这一格不留空。
  const turnTokens = !turnCost && showCompletedActionBar && item.message.kind === 'assistant'
    ? formatMessageTurnTokens(item.message.turnTotalTokens)
    : '';
  const canFork = !!(
    showCompletedActionBar
    && clientId
    && actions.onForkMessage
    && (item.message.kind === 'assistant' || (item.message.kind === 'user' && !isFirstUserMessage))
  );
  const canRewind = !!(
    showCompletedActionBar
    && clientId
    && actions.onPreviewRewind
    && item.message.kind === 'user'
    && !isFirstUserMessage
  );
  // 对齐桌面:任务运行中也保留删除入口,点了由页面提示等回复结束,不让菜单项时有时无。
  const canDelete = !!(
    showCompletedActionBar
    && clientId
    && actions.onDeleteMessage
    && (item.message.kind === 'user' || item.message.kind === 'assistant')
  );
  const canCopyLink = !!(showCompletedActionBar && clientId && actions.onCopyMessageLink);
  const canAddToChat = !!(showCompletedActionBar && clientId && actions.onAddMessageToComposer);
  const canSideChat = !!(showCompletedActionBar && copyText.trim() && actions.onSideChatMessage);
  const canShare = !!(
    showCompletedActionBar
    && clientId
    && shareableMessage
    && actions.onEnterShareSelection
    && !actions.shareSelectionActive
    && !actions.busyClientId
  );
  const contentLayout = useMemo(() => buildMessageContentLayout({
    screenWidth: actions.screenWidth,
  }), [actions.screenWidth]);
  // 长消息自动收起(对齐桌面 UserMessage 的两档阈值):自动化任务注入的消息
  // (agentMeta.origin → automationOrigin)是模板化调度 prompt,用更紧的阈值
  // 并只留 3 行;手打消息 14 行阈值 / 收起留 10 行。判定以真实排版为准:粗筛
  // 命中的消息在气泡里挂隐藏测量 Text,onTextLayout 实测行数,回调到达前用
  // 纯文本估算兜底(避免先整段渲染再跳变收起)。
  const automationOrigin = item.message.kind === 'user' ? item.message.automationOrigin : undefined;
  const hookSource = item.message.hookSource;
  const collapseThreshold = automationOrigin
    ? AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD
    : LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD;
  const collapsedLineCount = automationOrigin
    ? AUTOMATION_USER_MESSAGE_COLLAPSED_LINES
    : LONG_USER_MESSAGE_COLLAPSED_LINES;
  // hook 来源消息在 RenderItemView 中会降级为左对齐 system kind,避免暴露
  // 本地 user 消息的 fork / rewind / delete 操作;它仍可能携带至多 20k 文本,
  // 因此必须继续复用长消息的有界测量与折叠保护。
  // 引用 / 粘贴文本 / Slash 等结构化 atom 的 displayBubbleBody 已是紧凑投影,
  // 因此可继续参与同一套长消息判定;真正收起时改用静态结构化 renderer + 整体
  // 高度裁切,既不把完整 payload 摊开,也不会因含 chip 而永久失去长消息保护。
  const collapseMeasureEnabled = (isUser || hookSource !== undefined)
    && (item.message.kind === 'user' || hookSource !== undefined)
    && !item.message.systemCardType
    && !!displayBubbleBody
    && mayExceedVisualLineThreshold(displayBubbleBody, collapseThreshold);
  // 实测行数与被测 body 绑定存储:FlatList 复用组件实例时 body 可能原地变化
  // (服务端同步补丁等),旧实测值若不随内容失效,会在下一次 onTextLayout 到达
  // 前产生"过期行数"的错误收起判定;body 不匹配时视为未测量,回落估算兜底。
  const [measuredBody, setMeasuredBody] = useRecyclingState<{
    body: string;
    lines: number;
  } | null>(null);
  const measuredBodyLines =
    measuredBody && measuredBody.body === displayBubbleBody ? measuredBody.lines : null;
  const [longMessageExpanded, setLongMessageExpanded] = useRecyclingState(false);
  // 折叠判定单向闩锁(绑定 body,FlatList 复用换消息时自动失效):测量 Text
  // 的排版宽度跟随气泡宽度,而气泡宽度又随折叠状态变化(展开态的 markdown
  // 块级内容——公式 WebView / 表格等——会把气泡撑到最大宽)。行数恰好骑在
  // 阈值边界的消息会「收起态测 N 行 → 判展开 → 展开态测 N+1 行 → 判收起」
  // 无限振荡(2026-07 数学公式块实测:14/15 行边界整屏闪动)。闩锁让「该
  // 收起」的判定只进不出:后续宽度变化跌回阈值以下不再自动展开;用户手动
  // 点「展开」走 longMessageExpanded,不受闩锁影响。
  const [collapseLatchBody, setCollapseLatchBody] = useRecyclingState<string | null>(null);
  const collapseLatched = collapseLatchBody === displayBubbleBody;
  const collapseResolved = collapseMeasureEnabled
    && resolveUserMessageCollapse(displayBubbleBody, measuredBodyLines, collapseThreshold);
  useEffect(() => {
    if (collapseResolved && !collapseLatched) setCollapseLatchBody(displayBubbleBody);
  }, [collapseResolved, collapseLatched, displayBubbleBody]);
  const shouldCollapseLongMessage = (collapseMeasureEnabled && collapseLatched) || collapseResolved;
  const longMessageCollapsed = shouldCollapseLongMessage && !longMessageExpanded;
  // label 走 i18n.t,所以语言必须进依赖:否则用户在任务页挂载期间切语言,菜单会一直
  // 停在切换前的语言,直到 capability 变化或组件重挂。
  const messageMenu = useMemo(() => buildMobileMessageMenu({
    canSideChat,
    canAddToChat,
    canCopyLink,
    canDelete,
    canRewind,
  }), [canSideChat, canAddToChat, canCopyLink, canDelete, canRewind, i18nInstance.language]);
  const actionBar = useMemo(() => buildMessageActionBarPresentation({
    align: isUser ? 'user' : 'agent',
    canCopy,
    canFork,
    hasMoreActions: messageMenu.length > 0,
    hasTime: !!relativeTime,
    // 金额与 token 回退占同一格,任一有值就保留该位置。
    hasTurnCost: !!turnCost || !!turnTokens,
    isStreaming: isStreamingAssistant,
  }), [canCopy, canFork, isStreamingAssistant, isUser, messageMenu.length, relativeTime, turnCost, turnTokens]);
  const hasActions = actionBar.items.length > 0 || canShare;
  const reserveActionSlot = !shareSelectionActive
    && !actions.companion
    && isStreamingAssistant
    && !item.message.systemCardType
    && !hasActions;
  const actionBusy = !!clientId && actions.busyClientId === clientId;
  const forkBusy = actionBusy && actions.busyAction === 'fork';
  const disabled = !!actions.busyClientId;
  // 伙伴与普通任务都保留正文原生长按选字;消息操作由气泡下方按钮承接。
  const companionQuote = actions.companionQuoteActions;
  const bubbleTextSelectable = canSelectVisibleText;
  const replyQuote = companionQuote && item.message.kind === 'user' ? item.message.replyQuote : undefined;
  const replyTargetId = companionQuote?.showReplyTargets && item.message.kind === 'assistant' && clientId
    ? readReplyToClientId(item.message) : null;
  const replyTargetMessage = replyTargetId ? companionQuote?.getMessage(replyTargetId) : undefined;
  const replyTarget = replyTargetId && isOwnerTypedMessage(replyTargetMessage)
    && companionQuote?.isLastReplyFor(clientId)
    ? companionReplyQuoteFor(replyTargetMessage) : null;

  useEffect(() => {
    if (copyState === 'idle' || copyState === 'copying') return;
    const timer = setTimeout(() => setCopyState('idle'), 1500);
    return () => clearTimeout(timer);
  }, [copyState]);

  const copyOwnerRef = useRef(clientId);
  copyOwnerRef.current = clientId;
  const copyMessage = useCallback(() => {
    if (!canCopy || copyState === 'copying') return;
    setCopyState('copying');
    const owner = clientId;
    void copyMessageText(copyText).then((status) => {
      if (copyOwnerRef.current === owner) setCopyState(status);
    });
  }, [canCopy, clientId, copyState, copyText, setCopyState]);
  const selectControlAction = useCallback((id: MobileMessageControlActionId) => {
    if (id === 'copy') {
      copyMessage();
      return;
    }
    if (id === 'rewind' && clientId) {
      actions.onPreviewRewind?.(clientId, {
        document: composerDraftDocument ?? composerDocumentFromSerializedMessage(draftBody),
        text: draftText,
        quotes: messageQuotes,
        ...(item.message.quotesEncoded === true ? { orderedBody: draftBody } : {}),
      });
      return;
    }
    if (id === 'fork' && clientId) {
      actions.onForkMessage?.(
        clientId,
        item.message.kind === 'user'
          ? {
              document: composerDraftDocument ?? composerDocumentFromSerializedMessage(draftBody),
              text: draftText,
              quotes: messageQuotes,
              ...(item.message.quotesEncoded === true ? { orderedBody: draftBody } : {}),
            }
          : undefined,
      );
      return;
    }
    if (id === 'delete' && clientId) {
      actions.onDeleteMessage?.(clientId);
    }
  }, [
    actions,
    draftText,
    clientId,
    composerDraftDocument,
    copyMessage,
    draftBody,
    item.message.kind,
    item.message.quotesEncoded,
    messageQuotes,
  ]);
  const selectMenuAction = useCallback((id: MobileMessageMenuActionId) => {
    if (!clientId) return;
    if (id === 'rewind') return selectControlAction('rewind');
    if (id === 'delete') return selectControlAction('delete');
    if (id === 'add-to-chat') return actions.onAddMessageToComposer?.(clientId);
    if (id === 'side-chat') return actions.onSideChatMessage?.(copyText);
    actions.onCopyMessageLink?.(clientId);
  }, [actions, clientId, copyText, selectControlAction]);
  const openMessageActionMenu = useCallback(() => {
    if (usesSystemActionMenu()) {
      const disabled = actionBusy
        ? new Set<MobileMessageMenuActionId>(['rewind', 'delete'])
        : null;
      void showActionMenu({
        cancelLabel: t('session.common.cancel'),
        items: messageMenu.map((item) => ({
          destructive: item.destructive,
          disabled: disabled?.has(item.id) === true,
          key: item.id,
          label: item.label,
        })),
        userInterfaceStyle: mode,
      }).then((result) => {
        if (result.kind === 'action') selectMenuAction(result.key);
      });
      return;
    }
    setActionSheetOpen(true);
  }, [actionBusy, messageMenu, mode, selectMenuAction, t]);
  // 时间只展示发送时间;消息锚点复制移入语义明确的 More 菜单。
  const timeText = relativeTime ? (
    <Text
      accessibilityLabel={absoluteTime ? t('message.renderer.sentTime', { time: absoluteTime }) : undefined}
      key="time"
      style={styles.messageActionMeta}
      testID="message.timeText"
    >
      {relativeTime}
    </Text>
  ) : null;
  const costText = turnCost ? (
    <Text
      accessibilityLabel={item.message.turnMoney?.kind === 'value-estimate'
        ? t('message.renderer.turnCostEstimate', { cost: turnCost })
        : t('message.renderer.turnCost', { cost: turnCost })}
      key="cost"
      style={styles.messageActionMeta}
      testID="message.turnCostText"
    >
      {turnCost}
    </Text>
  ) : turnTokens ? (
    <Text
      accessibilityLabel={t('message.renderer.turnTokens', { tokens: turnTokens })}
      key="cost"
      style={styles.messageActionMeta}
      testID="message.turnTokensText"
    >
      {turnTokens}
    </Text>
  ) : null;
  // 附件条对齐桌面版:渲染在气泡外、文字气泡上方(用户消息右对齐);
  // 纯图片消息(无正文)不再渲染空气泡背景。
  const attachmentStripNode = item.message.attachments?.length ? (
    <AttachmentStrip
      align={isUser ? 'right' : 'left'}
      attachments={item.message.attachments}
      messageKey={item.message.key}
      clientId={item.message.source.clientId ?? item.message.source.id}
      getImagePreview={actions.getSentImagePreview}
      layout={contentLayout}
      onOpen={actions.onOpenPayload}
      onResolveRemoteMedia={actions.onResolveRemoteMedia}
    />
  ) : null;
  const hasPluginInvocations = isUser && actions.showPluginInvocations !== false
    && Boolean(item.message.pluginInvocations?.length);
  const hasBubbleContent = !!(
    item.message.systemCardType || displayBubbleBody || item.message.secondaryBody || hasPluginInvocations
    // A quote or reply target alone still needs the bubble, e.g. an attachment-only reply.
    || (companionQuote && (replyQuote || replyTarget))
  );
  const bubbleShown = item.message.role !== 'error'
    && (hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0));
  // 气泡是纯 View,不承接任何手势:文本选择走正文原生 Text selectable(长按文字就地选择复制),
  // 气泡上不能挂 Pressable——它会参与触摸协商,干扰正文里表格/代码块横向 ScrollView 的拖动。
  const bubble = (
    <View
      style={[
        styles.bubble,
        presentation.density === 'compact' && styles.bubbleCompact,
        presentation.density === 'rich' && styles.bubbleRich,
        isUser ? styles.userBubble : styles.agentBubble,
        actions.companion && !isUser && !item.message.systemCardType && styles.companionAnswer,
        hookSource && styles.hookSourceBubble,
        isUser && !item.message.systemCardType && userBubbleColors
          && isOwnUserBubble(item.message, { accountId: viewer?.id, remoteDeviceId: actions.remoteDeviceId })
          && { backgroundColor: userBubbleColors.background, borderColor: userBubbleColors.border },
      ]}
      testID={isUser ? 'message.userBubble' : 'message.agentBubble'}
    >
      {hasPluginInvocations ? (
        <PluginInvocationHeader
          key={clientId}
          plugins={item.message.pluginInvocations!}
          deviceId={actions.remoteDeviceId}
          sessionId={item.message.source.sessionId}
          running={actions.isSessionStreaming === true && clientId === actions.lastUserInputClientId}
        />
      ) : null}
      {hookSource ? (
        <View style={styles.hookSourceHeader} testID="message.hookSource">
          {hookSource.im === 'telegram'
            ? <Send color={colors.textSecondary} size={iconSize.xs} strokeWidth={iconStroke.regular} />
            : <MessageSquare color={colors.textSecondary} size={iconSize.xs} strokeWidth={iconStroke.regular} />}
          <Text numberOfLines={1} style={styles.hookSourceTitle}>
            {imSourceHeaderTitle(hookSource.im)}
          </Text>
          {hookSource.channelName ? (
            <Text numberOfLines={1} style={styles.hookSourceChannel}>
              {hookSource.channelName}
            </Text>
          ) : null}
        </View>
      ) : null}
      {replyQuote && companionQuote ? (
        <View style={styles.companionQuote}>
          <BotGroupQuote display={companionReplyQuoteDisplay(replyQuote, companionQuote.getMessage(replyQuote.clientId), companionQuote.names)}
            onPress={() => companionQuote.onLocate(replyQuote.clientId)} />
        </View>
      ) : replyTarget && replyTargetId && companionQuote ? (
        <View style={styles.companionQuote} testID="message.replyTarget">
          <BotGroupQuote display={companionReplyQuoteDisplay(replyTarget, replyTargetMessage, companionQuote.names)}
            onPress={() => companionQuote.onLocate(replyTargetId)} />
        </View>
      ) : null}
      {item.message.systemCardType === 'mcp-app' ? (
        <ViewabilityGatedMcpAppCard deviceId={actions.remoteDeviceId} sessionId={item.message.source.sessionId}
          clientId={item.message.source.clientId} title={String(item.message.systemCardData?.title ?? '')}
          fallbackText={String(item.message.systemCardData?.fallbackText ?? '')} />
      ) : item.message.systemCardType ? (
        <MobileSystemCard
          autoResumeInFlight={isMobileAutoResumeRowInFlight({
            isContinuationTurnOwner: clientId === actions.continuationTurnClientId,
            makerTurnRunning: actions.makerTurnRunning === true,
            isLastUserInput: clientId === actions.lastUserInputClientId,
            projectionCapability:
              actions.continuationInFlightProjectionCapability ?? 'unknown',
          })}
          data={item.message.systemCardData}
          type={item.message.systemCardType}
        />
      ) : displayBubbleBody ? (
        longMessageCollapsed ? (
          rendersSentInlineBody ? (
            <SentInlineAtomBody
              interactiveAtoms={false}
              maxVisibleLines={collapsedLineCount}
              numberOfLines={collapsedLineCount}
              selectable={bubbleTextSelectable}
              testID="message.collapsedSentInlineAtoms"
              textStyle={styles.messageText}
              tokens={sentInlineTokens}
            />
          ) : (
            // 普通长消息收起态降级为纯文本(对齐桌面:被裁切的富文本节点不该
            // 保留交互),展开后恢复 MarkdownBody。文本选择走与正文同款的
            // MarkdownSelectableText(iOS UITextView 原生支持 numberOfLines)。
            <MarkdownSelectableText
              numberOfLines={collapsedLineCount}
              selectable={bubbleTextSelectable}
              style={styles.messageText}
              testID="message.collapsedBody"
            >
              {displayBubbleBody}
            </MarkdownSelectableText>
          )
        ) : rendersSentInlineBody ? (
          <SentInlineAtomBody
            onOpenPayload={actions.onOpenPayload}
            renderText={(text, index) => (
              <View key={`text:${index}`} style={styles.sentInlineTextChunk}>
                <MarkdownBody
                  codeCopyEnabled={!shareSelectionActive}
                  layout={contentLayout}
                  markdownImageCacheKey={item.message.key}
                  onOpenPayload={actions.onOpenPayload}
                  onOpenSessionLink={actions.onOpenSessionLink}
                  pinContentWidth={!isUser}
                  selectable={bubbleTextSelectable}
                  streaming={false}
                  text={text}
                />
              </View>
            )}
            tokens={sentInlineTokens}
          />
        ) : (
          <MarkdownBody
            codeCopyEnabled={!shareSelectionActive}
            renderRichAnswers={item.message.kind === 'assistant'}
            richStateKey={item.message.source.clientId ?? item.message.key}
            allowIosUITextView={!shouldCollapseLongMessage || actions.companion === true}
            boundTextRuns={shouldCollapseLongMessage && actions.companion === true}
            markdownImageCacheKey={item.message.key}
            layout={contentLayout}
            onOpenPayload={actions.onOpenPayload}
            onOpenSessionLink={actions.onOpenSessionLink}
            pinContentWidth={!isUser}
            selectable={bubbleTextSelectable}
            streaming={isStreamingAssistant}
            text={bubbleBody}
          />
        )
      ) : null}
      {collapseMeasureEnabled ? (
        // 收起判定的测量节点:与正文同宽(left/right = 气泡 padding)同字号的
        // 纯文本,absolute 不占布局、opacity 0 不可见、pointerEvents none 不挡
        // 触摸。这里只需知道行数是否越过阈值,因此最多排到 threshold + 1 行:
        // 不让不可见节点为超长消息完整排版,避免 iOS 产生额外的超高原生
        // 文本布局,Android 也不用承担无意义的完整排版开销。伙伴展开态复用有界
        // 文本分组保留部分选字,普通任务继续使用 RN Text fallback。
        // 无障碍两端都要屏蔽:accessibilityElementsHidden 管 iOS VoiceOver
        // (opacity 0 不会让 VoiceOver 跳过,漏了会把正文重复朗读一遍),
        // importantForAccessibility 管 Android TalkBack。
        <View
          accessibilityElementsHidden
          accessible={false}
          importantForAccessibility="no-hide-descendants"
          pointerEvents="none"
          style={styles.collapseMeasureWrap}
        >
          <Text
            numberOfLines={collapseThreshold + 1}
            onTextLayout={(e) => setMeasuredBody({
              body: displayBubbleBody,
              lines: e.nativeEvent.lines.length,
            })}
            style={styles.messageText}
          >
            {displayBubbleBody}
          </Text>
        </View>
      ) : null}
      {shouldCollapseLongMessage ? (
        // 展开/收起入口用 Text onPress(与操作条 timeText 同款):气泡内禁挂
        // Pressable(参与触摸协商,干扰正文横向 ScrollView 手势,见
        // messageSelectionDesktopFirst 契约),Text onPress 只在自身文字区响应。
        <Text
          accessibilityLabel={longMessageExpanded ? t('message.renderer.collapseMessage') : t('message.renderer.expandMessage')}
          accessibilityRole="button"
          onPress={() => setLongMessageExpanded((expanded) => !expanded)}
          style={styles.collapseToggleText}
          suppressHighlighting
          testID="message.collapseToggle"
        >
          {longMessageExpanded ? t('message.renderer.collapse') : t('message.renderer.expand')}
        </Text>
      ) : null}
      {item.message.secondaryBody ? (
        <MarkdownSelectableText selectable={bubbleTextSelectable} style={styles.detailText}>
          {item.message.secondaryBody}
        </MarkdownSelectableText>
      ) : null}
    </View>
  );

  const messageNode = (
    <View
      ref={shareableMessage ? handleShareableMessageViewChange : undefined}
      style={[
        styles.messageItem,
        isUser ? styles.userMessageItem : styles.agentMessageItem,
      ]}
    >
      {item.message.kind === 'user' && item.message.sharedAuthorName ? (
        // 共享任务成员发的消息:作者名放在气泡上方(对齐桌面 UserMessage),不进气泡;
        // 与其它来源标签一样长按显示成员 ID。
        <SourceLabelWithId
          align={isUser ? 'user' : 'agent'}
          accessibilityLabel={t('message.renderer.sharedAuthor', { name: item.message.sharedAuthorName })}
          idText={item.message.sharedAuthorMemberId
            ? t('message.renderer.sourceMemberId', { id: item.message.sharedAuthorMemberId })
            : undefined}
          label={item.message.sharedAuthorName}
          testID="message.sharedAuthor"
        />
      ) : null}
      {item.message.kind === 'assistant' && item.message.sourceGroup ? (
        <SourceLabelWithId
          align="agent"
          label={item.message.sourceGroup.name
            ? t('message.renderer.groupSentNamed', { name: item.message.sourceGroup.name })
            : t('message.renderer.groupSent')}
          idText={t('message.renderer.sourceGroupId', { id: item.message.sourceGroup.groupId })}
          testID="message.groupSource"
        />
      ) : null}
      {automationOrigin ? (
        // 自动化任务注入的消息:气泡上方渲来源标签(对齐桌面;手机版暂不做
        // 点击跳转自动化页)。共享任务访客的脱敏来源没有名字与 ID,显示通用文案。
        <AutomationOriginLabel align={isUser ? 'user' : 'agent'} origin={automationOrigin} />
      ) : null}
      {/* 插件优先(与 messageSourceSenderFromMeta 同序):同时带来源任务 origin 时只显示插件。 */}
      {item.message.kind === 'user' && item.message.sessionOrigin && !item.message.sourcePlugin ? (
        <SessionOriginLabel
          align={isUser ? 'user' : 'agent'}
          origin={item.message.sessionOrigin}
          onOpen={actions.onOpenOriginSession}
          sourceMeta={item.message.source.agentMeta}
        />
      ) : null}
      {item.message.kind === 'user' && item.message.sourcePlugin ? (
        <SourcePluginLabel align={isUser ? 'user' : 'agent'} plugin={item.message.sourcePlugin} />
      ) : null}
      {item.message.kind === 'user'
        && shouldShowSourceDevice(item.message.sourceDevice, actions.viewerDeviceId) ? (
        <SourceDeviceLabel
          align={isUser ? 'user' : 'agent'}
          device={item.message.sourceDevice}
          onOpen={actions.onOpenSourceDevice}
        />
      ) : null}
      {attachmentStripNode}
      {item.message.failedSamplingAttempt ? (
        <Text style={styles.failedSamplingAttemptText}>
          {t('message.renderer.failedSamplingAttempt')}
        </Text>
      ) : null}
      {item.message.role === 'error' ? (
        <ErrorNotice message={displayBubbleBody}>
          {item.message.rawError ? <AgentErrorDetails key={item.message.key} message={item.message.rawError}
            onDiagnose={actions.onDiagnoseError ? () => actions.onDiagnoseError!({
              message: displayBubbleBody, details: item.message.rawError!,
            }) : undefined} /> : null}
        </ErrorNotice>
      ) : bubbleShown ? bubble : null}
      {actions.companion && item.message.kind === 'assistant' && item.message.body.trim() ? (
        <CompanionLearningFooter receipts={item.message.source.agentMeta?.botLearning}
          onOpenSettings={actions.onOpenCompanionSettings} />
      ) : null}
      {actions.companion && item.message.kind === 'assistant' && item.message.turnCompleted === true
        && item.message.body.trim() ? readBotTaskResults(item.message.source.agentMeta?.botTaskResults).map(meta => (
          <CompanionTaskResultCard key={botTaskResultKey(meta)} meta={meta} attached
            deviceId={actions.remoteDeviceId ?? ''} parentSessionId={item.message.source.sessionId}
            renderMarkdown={text => <CompanionCardMarkdown messageKey={`${item.key}:${botTaskResultKey(meta)}`} text={text} actions={actions} />} />
        )) : null}
      {item.message.kind === 'assistant' && item.message.modelMismatch ? (
        // 模型降级提示(对齐桌面 AssistantMessage):所选模型本轮被上游静默替换,
        // 常显在气泡下方,icon 用 warning 橙、文字保持 tertiary 灰阶。
        <View style={styles.modelMismatchRow} testID="message.modelMismatch">
          <TriangleAlert color={colors.statusAccent} size={iconSize.xs} strokeWidth={iconStroke.thin} />
          <Text numberOfLines={2} style={styles.modelMismatchText}>
            {t('message.renderer.modelMismatch', {
              actual: formatModelShortLabel(item.message.modelMismatch.actual) || item.message.modelMismatch.actual,
              selected: formatModelShortLabel(item.message.modelMismatch.selected) || item.message.modelMismatch.selected,
            })}
          </Text>
        </View>
      ) : null}
      {hasActions && actions.companion ? <CompanionMessageActions user={isUser} copied={copyState === 'copied'} copying={copyState === 'copying'} disabled={disabled}
        onCopy={canCopy ? copyMessage : undefined}
        actions={[
          ...(canCopy ? [{ id: 'copy', title: copyActionLabel(copyState), image: 'doc.on.doc', disabled: copyState === 'copying' }] : []),
          ...(canShare ? [{ id: 'share', title: t('session.shareImage.shareMessage'), image: 'square.and.arrow.up' }] : []),
          // Desktop's teammate action bar omits fork and per-turn cost/tokens: the Bot owns its one timeline.
          ...messageMenu.map(item => ({ id: item.id, title: item.label, image: item.image, destructive: item.destructive, disabled: actionBusy })),
          ...(absoluteTime ? [{ id: 'time', title: absoluteTime.slice(0, 16), disabled: true }] : []),
        ]}
        onAction={id => {
          // Reply quotes what can be quoted; other rows (errors, system cards) keep inserting their link.
          const quote = id === 'add-to-chat' && companionQuote ? companionReplyQuoteFor(item.message) : null;
          if (quote) companionQuote?.onQuote(quote);
          else if (id === 'copy') selectControlAction(id);
          else if (id === 'share') actions.onEnterShareSelection?.(clientId);
          else if (messageMenu.some(item => item.id === id)) selectMenuAction(id as MobileMessageMenuActionId);
        }} /> : hasActions || reserveActionSlot ? (
        <View
          style={[
            styles.messageActionBar,
            reserveActionSlot && styles.messageActionSlot,
            actionBar.align === 'right' ? styles.userMessageActionBar : styles.agentMessageActionBar,
          ]}
          testID={hasActions ? 'message.actionBar' : 'message.actionSlot'}
        >
          {hasActions ? actionBar.items.map((id) => {
            if (id === 'time') return timeText;
            if (id === 'cost') return costText;
            if (id === 'more') {
              return (
                <NativePullDownMenu
                  disabled={disabled && !forkBusy}
                  actions={messageMenu.map((item) => ({
                    image: item.image,
                    destructive: item.destructive,
                    disabled: actionBusy && (item.id === 'rewind' || item.id === 'delete'),
                    id: item.id,
                    title: item.label,
                  }))}
                  key="more"
                  onAction={(actionId) => selectMenuAction(actionId as MobileMessageMenuActionId)}
                >
                  <MessageMoreButton
                    buttonSize={actionBar.buttonSize}
                    // Fork has its own visible busy state. Keep More available
                    // only while that direct action is running; rewind/delete
                    // still block the menu while their requests are in flight.
                    disabled={disabled && !forkBusy}
                    iconSize={actionBar.iconSize}
                    onPress={usesNativePullDownMenu() ? () => undefined : openMessageActionMenu}
                  />
                </NativePullDownMenu>
              );
            }
            if (isMessageControlActionId(id)) {
              return (
                <Fragment key={id}>
                  <MessageControlButton
                    buttonSize={actionBar.buttonSize}
                    busy={id === 'fork' && forkBusy}
                    copyState={copyState}
                    disabled={disabled || actionBusy || (id === 'copy' && copyState === 'copying')}
                    id={id}
                    iconSize={actionBar.iconSize}
                    onPress={() => selectControlAction(id)}
                  />
                  {id === 'copy' && canShare ? (
                    <MessageShareButton
                      buttonSize={actionBar.buttonSize}
                      iconSize={actionBar.iconSize}
                      onPress={() => actions.onEnterShareSelection?.(clientId)}
                    />
                  ) : null}
                </Fragment>
              );
            }
            return null;
          }) : null}
          {hasActions && canShare && !actionBar.items.includes('copy') ? (
            <MessageShareButton
              buttonSize={actionBar.buttonSize}
              iconSize={actionBar.iconSize}
              onPress={() => actions.onEnterShareSelection?.(clientId)}
            />
          ) : null}
        </View>
      ) : null}
      <MessageActionSheet
        disabledActions={actionBusy ? ['rewind', 'delete'] : undefined}
        items={messageMenu}
        onAction={selectMenuAction}
        onClose={() => setActionSheetOpen(false)}
        visible={historyActive && actionSheetOpen}
      />
    </View>
  );

  // Desktop withAssistantAvatar: a teammate's reply hangs from its portrait (IM shape).
  const companionAvatar = actions.companion && !isUser && item.message.kind === 'assistant'
    && !item.message.systemCardType ? actions.companionAvatar : undefined;
  const rowNode = companionAvatar ? (
    <View style={styles.companionAvatarRow} testID="companion.replyRow">
      <View style={styles.companionAvatarSlot}>{companionAvatar}</View>
      <View style={styles.companionAvatarContent}>{messageNode}</View>
    </View>
  ) : messageNode;
  if (!shareSelectionActive) return rowNode;
  return (
    <ShareMessageCheckbox
      clientId={clientId}
      disabled={actions.shareSelectionBusy === true}
      fill
    >
      <View style={styles.shareSelectionContent}>
        {rowNode}
      </View>
    </ShareMessageCheckbox>
  );
}

/** Centered five-minute stamp above the first visible message of a teammate time group. */
function CompanionTimeGroupStamp({ timestamp }: { timestamp: number }) {
  const { i18n } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  return (
    <Text style={styles.companionTimeGroup} testID="companion.timeGroup">
      {formatBotMessageGroupTime(timestamp, i18n.language)}
    </Text>
  );
}

function copyActionLabel(state: CopyMessageStatus | 'idle' | 'copying'): string {
  if (state === 'copying') return i18n.t('message.renderer.copyStateCopying');
  if (state === 'copied') return i18n.t('message.renderer.copyStateCopied');
  if (state === 'failed') return i18n.t('message.renderer.copyStateFailed');
  return i18n.t('message.renderer.copyStateCopy');
}

/**
 * 流式思考的实时时长:界面只显示到秒,active 时每秒刷新一次自 sinceIso 起的耗时;
 * 非 active 或时间戳无效时返回 null(标题回退静态文案)。
 */
function useLiveElapsedMs(active: boolean, sinceIso: string | undefined): number | null {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    if (!active) return;
    setNow(Date.now());
    const timer = setInterval(() => setNow(Date.now()), 1_000);
    return () => clearInterval(timer);
  }, [active]);
  if (!active || !sinceIso) return null;
  const since = Date.parse(sinceIso);
  if (!Number.isFinite(since)) return null;
  return Math.max(0, now - since);
}

/** Lightweight shared reasoning markup (`**strong**` and code spans only). */
function ThinkingInlineText({ content }: { content: string }) {
  const styles = useThemedStyles(makeStyles);
  const tokens = useMemo(() => tokenizeThinkingText(content), [content]);
  return (
    <>
      {tokens.map((token, index) => {
        if (token.kind === 'strong') {
          return <Text key={`strong-${index}`} style={styles.thinkingStrong}>{token.value}</Text>;
        }
        if (token.kind === 'code') {
          return <Text key={`code-${index}`} style={styles.thinkingCode}>{token.value}</Text>;
        }
        return token.value;
      })}
    </>
  );
}

function ThinkingCard({
  item,
  isSessionStreaming = false,
  screenWidth,
}: {
  item: MobileThinkingItem;
  isSessionStreaming?: boolean;
  screenWidth?: number;
}) {
  const styles = useThemedStyles(makeStyles);
  const { t } = useTranslation();
  const layout = useMemo(() => buildMessageHierarchyLayout({
    screenWidth,
    summaryCount: 0,
  }), [screenWidth]);
  // 运行中判定要求消息自身仍在流式(isStreaming),避免历史被中断的思考
  // (durationMs 永久缺失)在会话再次流式时误转实时计时。
  const running = !item.redacted
    && item.durationMs === undefined
    && isSessionStreaming
    && item.message.isStreaming === true;
  const elapsedMs = useLiveElapsedMs(running, item.message.createdAt);
  const title = item.redacted
    ? t('message.renderer.thinkingHidden')
    : item.durationMs !== undefined
      ? t('message.renderer.thinkingDone', { duration: formatLocalizedDuration(item.durationMs) })
      : elapsedMs !== null
        ? t('message.renderer.thinkingActive', { elapsed: formatLocalizedDuration(elapsedMs) })
        : t('message.renderer.thinkingProcess');
  return (
    <FoldablePanel
      blockId={item.key}
      title={title}
      layout={layout}
      variant="plain"
    >
      <Rail layout={layout}>
        <Text style={[styles.detailText, styles.italicText]}>
          {item.redacted
            ? t('message.renderer.thinkingEmpty')
            : <ThinkingInlineText content={item.message.body || t('message.renderer.thinkingNoContent')} />}
        </Text>
      </Rail>
    </FoldablePanel>
  );
}

function ToolGroupCard({
  item,
  actions,
}: {
  item: MobileToolGroupItem;
  actions: MessageActions & { firstUserMessageClientId?: string };
}) {
  const { colors } = useTheme();
  const { i18n } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const rowOptions = useMemo(
    () => ({
      isSessionStreaming: actions.isSessionStreaming === true,
      wording: mobileToolRowWording,
      localizer: mobilePresentationLocalizer,
    }),
    [actions.isSessionStreaming, i18n.language],
  );
  const presentation = summarizeToolGroupPresentation(item, rowOptions);
  const header = presentation.header;
  const toolRows = useMemo(() => item.tools.map((tool) => ({
    key: tool.key,
    presentation: summarizeToolRowPresentation(tool, rowOptions),
    tool,
  })), [item.tools, rowOptions]);
  const layout = useMemo(() => buildMessageHierarchyLayout({
    screenWidth: actions.screenWidth,
    summaryCount: header.summaryCount,
  }), [actions.screenWidth, header.summaryCount]);
  const contentLayout = useMemo(() => buildMessageContentLayout({
    screenWidth: actions.screenWidth,
  }), [actions.screenWidth]);
  return (
    <FoldablePanel
      blockId={item.key}
      chevronPosition={header.chevronPosition}
      chevronSize={header.chevronSize}
      title={header.title}
      subtitle={header.subtitle ?? undefined}
      leadingIcon={presentation.hasRunning
        ? <CompactActivityIndicator color={colors.textTertiary} size={header.iconSize} />
        : <Bot color={colors.textTertiary} size={header.iconSize} strokeWidth={iconStroke.regular} />}
      layout={layout}
      testID="message.toolGroupToggle"
      variant={header.variant}
    >
      <Rail layout={layout}>
        <View style={styles.workActivityStack}>
          {toolRows.map(({ key, presentation: row, tool }) => (
            <ToolActionRow
              key={key}
              actions={actions}
              contentLayout={contentLayout}
              row={row}
              tool={tool}
            />
          ))}
        </View>
      </Rail>
    </FoldablePanel>
  );
}

/**
 * 单条工具行(对齐桌面 AgentActionRow 的「一行摘要,点击就地展开详情」模型):
 * 折叠态只有 状态图标 + 一行摘要 + chevron;点击行头就地展开 detail / diff /
 * 媒体条 / 结果预览,再点收起。展开态走共享进程内记忆(blockId 前缀 `toolrow-`,
 * 与组级 `tools-` key 空间天然隔离)。无详情可展的行不显示 chevron、不可点击。
 */
type ToolDetailActions = Pick<MessageActions, 'onRetryImageDelivery' | 'onLoadToolInput' | 'onOpenPayload' | 'onResolveRemoteMedia'>;

function ToolActionRow({
  actions,
  contentLayout,
  row,
  rowKey,
  tool,
}: {
  actions: ToolDetailActions;
  contentLayout: MessageContentLayout;
  row: ToolRowPresentation;
  rowKey?: string;
  tool: NormalizedRemoteMessage;
}) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  // 明确交付媒体仍由 ToolMediaBlock 承载;原生过程媒体留在所属工具步骤内。
  const hasDetails = !!(row.detail || tool.body || tool.diff || tool.secondaryBody);
  const [expanded, toggleExpanded] = useFoldableExpandedState(`toolrow-${rowKey ?? tool.key}`, false);
  const showDetails = expanded && hasDetails;
  const chevronNode = hasDetails
    ? (expanded
      ? <ChevronDown color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
      : <ChevronRight color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />)
    : null;
  return (
    <View style={styles.toolRow} testID="message.toolRow">
      <Pressable
        accessibilityLabel={expanded ? t('message.renderer.collapseRow', { label: row.label }) : t('message.renderer.expandRow', { label: row.label })}
        accessibilityRole="button"
        accessibilityState={{ expanded }}
        disabled={!hasDetails}
        hitSlop={{ bottom: 10, top: 10 }}
        onPress={toggleExpanded}
        style={({ pressed }) => [
          styles.toolRowHeader,
          pressed && hasDetails && styles.pressed,
        ]}
        testID="message.toolRowToggle"
      >
        <ToolRowStatusIcon hasError={row.hasError} status={row.status} />
        <Text style={[styles.toolName, styles.toolNameFlex]} numberOfLines={1}>{row.label}</Text>
        {chevronNode}
      </Pressable>
      {readToolProcessMedia(tool.secondaryBody).map((entry) => (
        <MediaPreview key={entry.url} label={mediaLabel({ ...entry, previewable: false })}
          layout={contentLayout} media={{ ...entry, previewable: false }}
          onOpen={actions.onOpenPayload ? () => actions.onOpenPayload!(buildMediaPayload(
            { ...entry, previewable: false }, mediaLabel({ ...entry, previewable: false }),
          )) : undefined}
          onResolveRemoteMedia={actions.onResolveRemoteMedia}
          variant={entry.kind === 'image' ? 'attachment' : 'card'} />
      ))}
      {showDetails ? (
        <View style={styles.toolRowDetails}>
          {row.detail || tool.body ? (
            <Text style={styles.toolRowDetailText}>{row.detail ?? tool.body}</Text>
          ) : null}
          {tool.toolInputProjection ? (
            <ProjectedToolInputButton
              key={tool.toolInputProjection.toolUseMessageId}
              actions={actions}
              projection={tool.toolInputProjection}
            />
          ) : null}
          {tool.diff ? <DiffPreview diff={tool.diff} layout={contentLayout} onOpen={actions.onOpenPayload} /> : null}
          {tool.secondaryBody ? <ToolResultPreview layout={contentLayout} tool={tool} onOpen={actions.onOpenPayload} onRetryImageDelivery={actions.onRetryImageDelivery} /> : null}
        </View>
      ) : null}
    </View>
  );
}

function ProjectedToolInputButton({
  actions,
  projection,
}: {
  actions: ToolDetailActions;
  projection: MobileToolInputProjection;
}) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const [status, setStatus] = useState<'error' | 'idle' | 'loading'>('idle');
  const requestSeqRef = useRef(0);

  useEffect(() => () => {
    requestSeqRef.current += 1;
  }, []);

  const openFullInput = useCallback(() => {
    if (!actions.onLoadToolInput || !actions.onOpenPayload || status === 'loading') return;
    const requestSeq = requestSeqRef.current + 1;
    requestSeqRef.current = requestSeq;
    setStatus('loading');
    void actions.onLoadToolInput(projection).then((detail) => {
      if (requestSeqRef.current !== requestSeq) return;
      setStatus('idle');
      actions.onOpenPayload?.(buildTextPayload(
        t('message.renderer.toolInputTitle', { label: detail.toolName }),
        detail.body,
      ));
    }).catch(() => {
      if (requestSeqRef.current === requestSeq) setStatus('error');
    });
  }, [actions, projection, status, t]);

  const label = status === 'loading'
    ? t('message.renderer.loadingToolInput')
    : status === 'error'
      ? t('message.renderer.retryToolInput')
      : t('message.renderer.viewToolInput');
  return (
    <MessageContentOpenButton
      accessibilityLabel={label}
      disabled={status === 'loading'}
      onPress={openFullInput}
      style={styles.toolInputPreview}
      testID="message.toolInputPayloadButton"
    >
      <View style={styles.toolInputActionRow}>
        {status === 'loading' ? (
          <CompactActivityIndicator color={colors.textTertiary} size={iconSize.sm} />
        ) : null}
        <Text style={styles.toolInputActionText}>{label}</Text>
      </View>
    </MessageContentOpenButton>
  );
}

function TodoCard({
  animated,
  item,
  screenWidth,
}: {
  animated: boolean;
  item: MobileTodoCardItem;
  screenWidth?: number;
}) {
  const { colors } = useTheme();
  const styles = useThemedStyles(makeStyles);
  const presentation = summarizeTodoCardPresentation(item);
  const header = presentation.header;
  const layout = useMemo(() => buildMessageHierarchyLayout({
    screenWidth,
    summaryCount: header.summaryCount,
  }), [header.summaryCount, screenWidth]);
  return (
    <>
      <FoldablePanel
        title={header.title}
        subtitle={header.subtitle ?? undefined}
        chevronPosition={header.chevronPosition}
        chevronSize={header.chevronSize}
        defaultExpanded={header.defaultExpanded}
        leadingIcon={<ListTodo color={colors.textPrimary} size={header.iconSize} strokeWidth={iconStroke.regular} />}
        layout={layout}
        variant={header.variant}
      >
        <View style={[styles.stackSmall, { gap: layout.stackSmallGap }]}>
          {item.todos.map((todo, index) => (
            <TodoRow
              animated={animated}
              key={`${todo.content}:${index}`}
              layout={layout}
              todo={todo}
            />
          ))}
        </View>
      </FoldablePanel>
    </>
  );
}

function TodoRow({
  animated,
  layout,
  todo,
}: {
  animated: boolean;
  layout: MessageHierarchyLayout;
  todo: MobileTodoItem;
}) {
  const styles = useThemedStyles(makeStyles);
  const presentation = todoStatusPresentation(todo.status);
  return (
    <View
      style={[
        styles.todoRow,
        {
          gap: layout.todoRowGap,
          minHeight: layout.todoRowMinHeight,
        },
        todo.status === 'pending' && styles.todoRowPending,
      ]}
      testID="message.todoRow"
    >
      <View style={[styles.todoMark, { width: layout.todoMarkWidth }]}>
        <TodoStatusIcon animated={animated} status={presentation.status} />
      </View>
      <View style={styles.todoCopy}>
        <Text
          style={[
            styles.todoText,
            todo.status === 'pending' && styles.todoPending,
            todo.status === 'completed' && styles.todoDone,
          ]}
          numberOfLines={2}
        >
          {todo.content}
        </Text>
      </View>
    </View>
  );
}

/** 桌面同款紧凑 spinner:LoaderCircle 弧形图标、1 秒一圈。
 * 固定外框避免运行态/完成态切换时发生布局位移。 */
function CompactActivityIndicator({ color, size }: { color: string; size: number }) {
  const [reduceMotionEnabled, setReduceMotionEnabled] = useState<boolean | null>(null);
  const rotation = useRef(new Animated.Value(0)).current;
  useEffect(() => {
    let active = true;
    void AccessibilityInfo.isReduceMotionEnabled()
      .then((enabled) => {
        if (active) setReduceMotionEnabled(enabled);
      })
      .catch(() => {
        if (active) setReduceMotionEnabled(false);
      });
    const subscription = AccessibilityInfo.addEventListener(
      'reduceMotionChanged',
      setReduceMotionEnabled,
    );
    return () => {
      active = false;
      subscription.remove();
    };
  }, []);
  useEffect(() => {
    if (reduceMotionEnabled !== false) {
      rotation.stopAnimation();
      rotation.setValue(0);
      return;
    }
    const loop = Animated.loop(Animated.timing(rotation, {
      duration: 1000,
      easing: Easing.linear,
      isInteraction: false,
      toValue: 1,
      useNativeDriver: true,
    }));
    loop.start();
    return () => {
      loop.stop();
      rotation.setValue(0);
    };
  }, [reduceMotionEnabled, rotation]);
  const rotate = rotation.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });
  return (
    <View style={[stylesStatic.compactActivityIndicator, { height: size, width: size }]}>
      <Animated.View style={reduceMotionEnabled === false ? { transform: [{ rotate }] } : undefined}>
        <LoaderCircle color={color} size={size} strokeWidth={iconStroke.regular} />
      </Animated.View>
    </View>
  );
}

/** 工具动作图标优先表达运行态;结束后再区分失败与成功。 */
function ToolRowStatusIcon({
  hasError,
  status,
}: {
  hasError: boolean;
  status: ToolRowStatus;
}) {
  const { colors } = useTheme();
  return (
    <View style={stylesStatic.workActivityIconSlot}>
      {status === 'running'
        ? <CompactActivityIndicator color={colors.textTertiary} size={iconSize.sm} />
        : hasError
          ? <CircleAlert color={colors.errorText} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          : <Check color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />}
    </View>
  );
}

function TodoStatusIcon({
  animated,
  status,
}: {
  animated: boolean;
  status: MobileTodoItem['status'];
}) {
  const { colors } = useTheme();
  if (status === 'completed') {
    return <CircleCheck color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.thin} />;
  }
  if (status === 'in_progress' && animated) {
    return <CompactActivityIndicator color={colors.textPrimary} size={iconSize.lg} />;
  }
  if (status === 'in_progress') {
    return <CircleDashed color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.thin} />;
  }
  return <Circle color={colors.textTertiary} size={iconSize.lg} strokeWidth={iconStroke.thin} />;
}

// 在调用点求值,避免模块顶层把 i18n.t 结果冻结成常量(冻结语言)。
function agentTaskStatusLabel(status: AgentTaskStatus): string {
  switch (status) {
    case 'running':
      return i18n.t('message.renderer.statusRunning');
    case 'completed':
      return i18n.t('message.renderer.statusCompleted');
    case 'failed':
      return i18n.t('message.renderer.statusFailed');
    case 'stopped':
      return i18n.t('message.renderer.statusStopped');
  }
}

const AGENT_TASK_PROVIDER_LABEL: Record<AgentTaskCardModel['provider'], string> = {
  'claude-code': 'Claude Code',
  codex: 'Codex',
  pi: 'Pi',
};

function AgentTaskStatusIcon({ status, size = iconSize.md }: { status: AgentTaskStatus; size?: number }) {
  const { colors } = useTheme();
  // Black/white reverse design: status reads from the icon SHAPE, not colour (no reds).
  if (status === 'completed') return <CircleCheck color={colors.textPrimary} size={size} strokeWidth={iconStroke.regular} />;
  if (status === 'failed') return <CircleAlert color={colors.errorText} size={size} strokeWidth={iconStroke.regular} />;
  if (status === 'stopped') return <CircleStop color={colors.textTertiary} size={size} strokeWidth={iconStroke.regular} />;
  if (status === 'running') return <CompactActivityIndicator color={colors.textTertiary} size={size} />;
  return <CircleDashed color={colors.textTertiary} size={size} strokeWidth={iconStroke.regular} />;
}

function buildAgentTaskMeta(model: AgentTaskCardModel): string[] {
  const parts: string[] = [AGENT_TASK_PROVIDER_LABEL[model.provider], agentTaskStatusLabel(model.status)];
  if (typeof model.totalTokens === 'number') parts.push(`${formatCompactTokens(model.totalTokens)} tokens`);
  if (typeof model.toolUses === 'number') parts.push(i18n.t('message.renderer.toolUseCount', { n: model.toolUses }));
  if (typeof model.durationMs === 'number') parts.push(formatLocalizedDuration(model.durationMs));
  return parts;
}

function readAgentTaskToolInput(toolCall: MobileAgentTaskItem['toolCall']): unknown {
  const content = toolCall?.source.content;
  return content && typeof content === 'object' && !Array.isArray(content)
    ? (content as Record<string, unknown>).input
    : undefined;
}

/**
 * Sub-agent task card (Claude `Task`/`Agent`, Codex `collab:*`) — mobile parity with the
 * desktop `AgentTaskCard`. Header shows the task title + a status-shaped icon; meta row carries
 * provider/status/usage; expanding reveals the prompt, summary, last tool, and output file.
 * Content comes from the shared `buildAgentTaskCardModel` (linked tool-call input + live update).
 */
function AgentTaskCard({
  item,
  screenWidth,
}: {
  item: MobileAgentTaskItem;
  screenWidth?: number;
}) {
  const { colors } = useTheme();
  const styles = useThemedStyles(makeStyles);
  const { t } = useTranslation();
  const model = useMemo(
    () => buildAgentTaskCardModel({
      toolName: item.toolCall?.label,
      toolInput: readAgentTaskToolInput(item.toolCall),
      update: item.update,
      // 重连后 live update 为空:协议级子任务错误结果必须恢复为 failed。
      result: item.toolCall?.secondaryBody,
      persistedStatus: item.toolCall?.agentTaskStatus,
    }),
    [item.toolCall, item.update],
  );
  const title = model.title
    ? `${t('message.renderer.subagent')} · ${model.title}`
    : t('message.renderer.subagentTaskTitle');
  const subtitle = buildAgentTaskMeta(model).join(' · ');
  const layout = useMemo(
    () => buildMessageHierarchyLayout({ screenWidth, summaryCount: 0 }),
    [screenWidth],
  );
  const hasDetails = !!(
    model.description || model.summary || model.spawnedAgentName || model.lastToolName || model.outputFile
  );
  return (
    <FoldablePanel
      blockId={item.key}
      title={title}
      subtitle={subtitle || undefined}
      chevronPosition="trailing"
      chevronSize={14}
      leadingIcon={<Bot color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />}
      trailingMeta={<AgentTaskStatusIcon status={model.status} />}
      layout={layout}
      variant="card"
      testID="message.agentTaskToggle"
    >
      {hasDetails ? (
        <View style={[styles.stackSmall, { gap: layout.stackSmallGap }]}>
          {model.description ? <Text style={styles.detailText}>{model.description}</Text> : null}
          {/* codex spawn 启动回执:shared model 只给结构化名字,句子按 locale 组装。 */}
          {model.spawnedAgentName ? (
            <Text style={styles.detailText}>
              {t('message.renderer.subagentStarted', { name: model.spawnedAgentName })}
            </Text>
          ) : null}
          {model.summary ? <Text style={styles.detailText}>{model.summary}</Text> : null}
          {model.lastToolName ? <Text style={styles.detailText}>{t('message.renderer.recentTool', { name: model.lastToolName })}</Text> : null}
          {model.outputFile ? <Text style={styles.detailText}>{t('message.renderer.outputFile', { file: model.outputFile })}</Text> : null}
        </View>
      ) : (
        <Text style={styles.detailText}>{t('message.renderer.noMoreDetail')}</Text>
      )}
    </FoldablePanel>
  );
}

function WorkGroupCard({
  item,
  actions,
}: {
  item: MobileWorkGroupItem;
  actions: MessageActions & { firstUserMessageClientId?: string };
}) {
  const { colors } = useTheme();
  const { t, i18n } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const presentation = useMemo(
    () => summarizeWorkGroupPresentation(item, mobilePresentationLocalizer),
    [i18n.language, item],
  );
  const header = presentation.header;
  const isStreaming = item.isStreaming === true;
  const [rememberedExpanded, toggleExpanded] = useFoldableExpandedState(item.key, false);
  const expanded = item.deferred?.setVisible ? rememberedExpanded : item.deferred?.expanded ?? rememberedExpanded;
  const lines = isStreaming ? item.deferred?.lines : undefined;
  const lineMode = lines !== undefined;
  const deferredRef = useRef(item.deferred);
  deferredRef.current = item.deferred;
  useLayoutEffect(() => {
    const current = deferredRef.current;
    current?.setVisible?.(expanded, isStreaming && !lineMode);
    return () => current?.setVisible?.(false, false);
  }, [item.deferred?.owner, item.deferred?.key, expanded, isStreaming, lineMode]);
  const layout = useMemo(() => buildMessageHierarchyLayout({
    screenWidth: actions.screenWidth,
    summaryCount: header.summaryCount,
  }), [actions.screenWidth, header.summaryCount]);
  const contentLayout = useMemo(() => buildMessageContentLayout({ screenWidth: actions.screenWidth }), [actions.screenWidth]);
  const liveActivities = useMemo(() => isStreaming && !lineMode
    ? projectRecentMobileWorkActivities(item.children, true, 5) : [], [item.children, isStreaming, lineMode]);
  // The outer group already occupies the reply column. Keep companion actions,
  // but neither repeat its portrait nor indent nested work groups a second time.
  const childActions = useMemo(() => actions.companion && actions.companionAvatar
    ? { ...actions, companionAvatar: undefined } : actions, [actions]);
  const activityProjection = useMemo(
    () => (expanded
      ? projectMobileWorkActivities(item.children, isStreaming)
      : null),
    [expanded, isStreaming, item.children],
  );
  // Tool detail rows do not consume message action/queue/share busy state.
  // Keep their callbacks and streaming flag stable across those unrelated updates.
  const toolActions = useMemo(() => ({
    onLoadToolInput: actions.onLoadToolInput,
    onRetryImageDelivery: actions.onRetryImageDelivery,
    onOpenPayload: actions.onOpenPayload,
    isSessionStreaming: actions.isSessionStreaming,
  }), [actions.onRetryImageDelivery, actions.onLoadToolInput, actions.onOpenPayload, actions.isSessionStreaming]);
  const startedAtIso = isStreaming && item.startedAtMs !== undefined
    ? new Date(item.startedAtMs).toISOString()
    : undefined;
  const explorationSummary = activityProjection?.isPureExploration
    ? [
        activityProjection.explorationCounts.read > 0
          ? t('message.renderer.filesRead', { n: activityProjection.explorationCounts.read })
          : null,
        activityProjection.explorationCounts.search > 0
          ? t('message.renderer.searchCount', { n: activityProjection.explorationCounts.search })
          : null,
        activityProjection.explorationCounts.list > 0
          ? t('message.renderer.listCount', { n: activityProjection.explorationCounts.list })
          : null,
      ].filter((value): value is string => value !== null).join(' · ')
    : '';
  const title = [
    actions.companion && isStreaming && actions.companionWorkingLabel ? actions.companionWorkingLabel : presentation.title,
    explorationSummary,
  ].filter(Boolean).join(' · ');
  const onToggle = item.deferred?.setVisible ? toggleExpanded : item.deferred?.toggle ?? toggleExpanded;
  const pluginWork = actions.companionPluginWork?.get(item.key);
  // The Host projects running lines for this view; folded groups render them as they are,
  // without building the hidden activity tree or reading any work details.
  // Expanding keeps these lines on screen until the detail read has rows to replace them.
  const holdLines = expanded && item.deferred?.awaitingDetails === true && !!lines?.length;
  const lineRows = lines?.length ? (
    <View style={styles.workActivityStack}>
      {lines.map((line) => <WorkLineRow key={line.key} line={line} onPress={onToggle} />)}
    </View>
  ) : !lineMode && liveActivities.length ? (
    <View style={styles.workActivityStack}>
      {liveActivities.map((activity) => activity.kind === 'tool'
        ? <WorkToolActivityRow key={activity.key} activity={activity} actions={toolActions} contentLayout={contentLayout} />
        : <WorkLineRow key={activity.key} line={{ kind: 'thinking', key: activity.key, text: activity.content }} onPress={onToggle} />)}
    </View>
  ) : null;
  return (
    <>
    {pluginWork ? <PluginInvocationHeader plugins={pluginWork.plugins} running={pluginWork.running}
      showCompletionBadge={false}
      deviceId={actions.remoteDeviceId} sessionId={pluginWork.sessionId} /> : null}
    <FoldablePanel
      chevronPosition={header.chevronPosition}
      chevronSize={header.chevronSize}
      controlledExpanded={expanded}
      collapsedBody={lineRows ? <Rail layout={layout}>{lineRows}</Rail> : undefined}
      onControlledToggle={onToggle}
      title={title}
      subtitle={header.subtitle ?? undefined}
      trailingMeta={isStreaming
        ? <WorkGroupElapsed sinceIso={startedAtIso} />
        : undefined}
      leadingIcon={isStreaming
        ? <CompactActivityIndicator color={colors.textTertiary} size={header.iconSize} />
        : <Layers color={colors.textTertiary} size={header.iconSize} strokeWidth={iconStroke.regular} />}
      layout={layout}
      testID="message.workGroupToggle"
      variant={header.variant}
    >
      {expanded ? (
        <Rail layout={layout}>
          <View style={styles.workGroupStack}>
            {holdLines && lineRows}
            {item.deferred?.loading && <CompactActivityIndicator color={colors.textTertiary} size={header.iconSize} />}
            {item.deferred?.failed && (
              <MessageListActionButton
                accessibilityLabel={t('message.renderer.retryPreview')}
                disabled={item.deferred.loading}
                onPress={item.deferred.retry}
                style={[styles.payloadOpenButton, { minHeight: MESSAGE_CONTROL_TOUCH_SIZE, minWidth: MESSAGE_CONTROL_TOUCH_SIZE }]}
                testID="message.workDetailsRetry"
              >
                <Text style={styles.payloadOpenButtonText}>{t('message.renderer.retryPreview')}</Text>
              </MessageListActionButton>
            )}
            {!holdLines && item.children.map((child) => {
              if (child.type === 'thinking') {
                return <ExpandedWorkThinkingRow key={child.key} item={child} />;
              }
              if (child.type === 'tool_group') {
                return (
                  <View key={child.key} style={styles.workActivityStack}>
                    {(activityProjection?.toolActivitiesByChildKey.get(child.key) ?? []).map((activity) => (
                      <WorkToolActivityRow
                        key={activity.key}
                        actions={toolActions}
                        activity={activity}
                        contentLayout={contentLayout!}
                      />
                    ))}
                  </View>
                );
              }
              return <RenderItemView key={child.key} item={child} actions={childActions} />;
            })}
          </View>
        </Rail>
      ) : null}
    </FoldablePanel>
    </>
  );
}

/** One Host-projected running line; pressing it opens the whole work group. */
const WorkLineRow = memo(function WorkLineRow({
  line,
  onPress,
}: {
  line: HistoryWorkLine;
  onPress: () => void;
}) {
  const { colors } = useTheme();
  const { i18n } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const label = useMemo(
    () => (line.kind === 'tool' ? formatToolRowText(line.descriptor, mobileToolRowWording).label || line.toolName : line.text),
    [i18n.language, line],
  );
  return (
    <Pressable
      accessibilityLabel={label}
      accessibilityRole="button"
      onPress={onPress}
      style={({ pressed }) => [line.kind === 'tool' ? styles.toolRowHeader : styles.workThinkingRow, pressed && styles.pressed]}
      testID="message.workLine"
    >
      {line.kind === 'tool' ? (
        <>
          <ToolRowStatusIcon hasError={line.hasError === true} status={line.status} />
          <Text numberOfLines={1} style={[styles.toolName, styles.toolNameFlex]}>{label}</Text>
        </>
      ) : (
        <>
          <View style={stylesStatic.workActivityIconSlot}>
            <Sparkles color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          </View>
          <Text numberOfLines={1} style={[styles.workActivityText, styles.italicText, styles.workThinkingText]}>
            <ThinkingInlineText content={label} />
          </Text>
        </>
      )}
    </Pressable>
  );
});

/** The clock must not re-render an expanded group's entire activity tree. */
function WorkGroupElapsed({ sinceIso }: { sinceIso: string | undefined }) {
  const styles = useThemedStyles(makeStyles);
  const elapsedMs = useLiveElapsedMs(true, sinceIso);
  return elapsedMs === null
    ? null
    : <Text style={styles.workGroupElapsed}>{formatLocalizedDuration(elapsedMs)}</Text>;
}

const WorkToolActivityRow = memo(function WorkToolActivityRow({
  actions,
  activity,
  contentLayout,
}: {
  actions: ToolDetailActions & Pick<MessageActions, 'isSessionStreaming'>;
  activity: MobileProjectedToolActivity;
  contentLayout: MessageContentLayout;
}) {
  const { i18n } = useTranslation();
  const tool = activity.message.normalized;
  const row = useMemo(() => summarizeToolRowPresentation(tool, {
    isSessionStreaming: actions.isSessionStreaming === true,
    intentOverride: activity.intentOverride,
    statusOverride: activity.status,
    wording: mobileToolRowWording,
  }), [actions.isSessionStreaming, activity.intentOverride, activity.status, i18n.language, tool]);
  return (
    <ToolActionRow
      actions={actions}
      contentLayout={contentLayout}
      row={row}
      rowKey={activity.key}
      tool={tool}
    />
  );
}, (previous, next) => (
  previous.actions === next.actions
  && previous.contentLayout === next.contentLayout
  && sameMobileWorkToolActivity(previous.activity, next.activity)
));

const ExpandedWorkThinkingRow = memo(function ExpandedWorkThinkingRow({
  item,
}: {
  item: MobileThinkingItem;
}) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const [expanded, toggleExpanded] = useFoldableExpandedState(`work-${item.key}`, false);
  const [measuredLineCount, setMeasuredLineCount] = useRecyclingState(1);
  const rawContent = item.message.body.trim();
  const canExpand = rawContent.includes('\n') || measuredLineCount > 1;
  return (
    <Pressable
      accessibilityLabel={expanded ? t('message.renderer.collapseThinking') : t('message.renderer.expandThinking')}
      accessibilityRole="button"
      accessibilityState={{ expanded: canExpand ? expanded : undefined }}
      disabled={!canExpand}
      onPress={canExpand ? toggleExpanded : undefined}
      style={({ pressed }) => [
        styles.workThinkingRow,
        expanded && styles.workThinkingRowExpanded,
        pressed && canExpand && styles.pressed,
      ]}
      testID="message.workThinkingToggle"
    >
      <View style={stylesStatic.workActivityIconSlot}>
        <Sparkles color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
      </View>
      <View style={styles.workThinkingText}>
        <Text
          numberOfLines={expanded ? undefined : 1}
          style={[styles.workActivityText, styles.italicText]}
        >
          <ThinkingInlineText content={rawContent || t('message.renderer.thinkingNoContent')} />
        </Text>
        {!expanded ? (
          <View
            accessibilityElementsHidden
            accessible={false}
            importantForAccessibility="no-hide-descendants"
            pointerEvents="none"
            style={styles.workThinkingMeasureWrap}
          >
            <Text
              numberOfLines={2}
              onTextLayout={(event) => setMeasuredLineCount(event.nativeEvent.lines.length)}
              style={[styles.workActivityText, styles.italicText]}
            >
              <ThinkingInlineText content={rawContent || t('message.renderer.thinkingNoContent')} />
            </Text>
          </View>
        ) : null}
      </View>
      {canExpand
        ? expanded
          ? <ChevronDown color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          : <ChevronRight color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
        : null}
    </Pressable>
  );
});

// 真·子 agent 嵌套卡片(手机端净新能力):复用 FoldablePanel(与 ToolGroupCard/WorkGroupCard 同款折叠
// 路径,滚动安全已验证)、默认折叠;展开递归渲染内层 childItems(经 RenderItemView)+ 子 agent 终稿。
// 颜色全走主题 token,不新增 hex。
function SubagentCard({
  item,
  actions,
}: {
  item: MobileSubagentGroupItem;
  actions: MessageActions & { firstUserMessageClientId?: string };
}) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const [expanded, toggleExpanded] = useFoldableExpandedState(item.key, false);
  const deferred = item.deferred;
  useEffect(() => {
    deferred?.setVisible?.(expanded, false);
    return () => deferred?.setVisible?.(false, false);
  }, [deferred?.owner, deferred?.key, expanded]);
  const title = item.header.subagentType
    ? t('message.renderer.subagentTyped', { type: item.header.subagentType })
    : t('message.renderer.subagent');
  const statusText = item.status === 'completed' && item.durationMs !== undefined
      ? t('message.renderer.workedDuration', { duration: formatLocalizedDuration(item.durationMs) })
      : agentTaskStatusLabel(item.status);
  const subtitle = [item.header.description, statusText].filter(Boolean).join(' · ');
  return (
    <CollabCardShell
      blockId={item.key}
      controlledExpanded={expanded}
      onControlledToggle={toggleExpanded}
      leadingIcon={<Bot color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />}
      title={title}
      subtitle={subtitle || undefined}
      screenWidth={actions.screenWidth}
      testID="message.subagentToggle"
    >
      {(layout) => (
        <View style={[styles.stack, { gap: layout.stackGap }]}>
          {deferred?.loading ? <CompactActivityIndicator color={colors.textTertiary} size={iconSize.md} /> : null}
          {deferred?.failed ? (
            <MessageListActionButton
              accessibilityLabel={t('message.renderer.retryPreview')}
              disabled={deferred.loading}
              onPress={deferred.retry}
              style={[styles.payloadOpenButton, { minHeight: MESSAGE_CONTROL_TOUCH_SIZE, minWidth: MESSAGE_CONTROL_TOUCH_SIZE }]}
              testID="message.subagentDetailsRetry"
            >
              <Text style={styles.payloadOpenButtonText}>{t('message.renderer.retryPreview')}</Text>
            </MessageListActionButton>
          ) : null}
          {/* 两级展开(与 WorkGroupCard 同规则):内层子卡保持各自折叠头行,按需下钻。 */}
          {item.childItems.map((child) => (
            <RenderItemView key={child.key} item={child} actions={actions} />
          ))}
          {item.summary ? (
            <View style={styles.stackSmall}>
              <Text style={styles.foldSubtitle}>{t('message.renderer.subagentSummary')}</Text>
              <Text selectable style={styles.detailText} testID="message.subagentSummary">
                {item.summary}
              </Text>
            </View>
          ) : null}
        </View>
      )}
    </CollabCardShell>
  );
}

function FoldablePanel({
  blockId,
  title,
  subtitle,
  children,
  collapsedBody,
  controlledExpanded,
  defaultExpanded = false,
  layout,
  variant,
  footer,
  testID,
  leadingIcon,
  trailingMeta,
  onControlledToggle,
  chevronSize = 18,
  chevronPosition = 'leading',
}: {
  /**
   * 传入则展开态走共享进程内记忆(默认折叠,虚拟化重挂/切会话/重分组不丢,
   * 见 expandedBlockMemory),**此时 defaultExpanded 无效**;不传则回退
   * 本地 state + defaultExpanded(TodoCard / Orca 协同卡这类无需记忆的卡)。
   */
  blockId?: string;
  title: string;
  subtitle?: string;
  children: ReactNode;
  /** Running work lines shown under a folded header; the full body is still built only when expanded. */
  collapsedBody?: ReactNode;
  /** Controlled mode used by work groups. */
  controlledExpanded?: boolean;
  /** 仅无 blockId 的本地 state 路径生效;blockId 存在时由共享记忆决定(默认折叠)。 */
  defaultExpanded?: boolean;
  layout: MessageHierarchyLayout;
  variant: 'plain' | 'card';
  footer?: ReactNode;
  testID?: string;
  leadingIcon?: ReactNode;
  trailingMeta?: ReactNode;
  onControlledToggle?: () => void;
  chevronSize?: number;
  chevronPosition?: 'leading' | 'trailing';
}) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const [rememberedExpanded, toggleRememberedExpanded] = useFoldableExpandedState(blockId, defaultExpanded);
  // Todo/Orca panels intentionally do not use the process-wide block memory.
  // Their local default must still be restored when LegendList assigns this
  // recycled cell to another render item.
  const [recycledLocalExpanded, setRecycledLocalExpanded] = useRecyclingState(defaultExpanded);
  const localExpanded = blockId ? rememberedExpanded : recycledLocalExpanded;
  const toggleLocalExpanded = useCallback(
    () => setRecycledLocalExpanded((value) => !value),
    [setRecycledLocalExpanded],
  );
  const expanded = controlledExpanded ?? localExpanded;
  const toggleExpanded = onControlledToggle
    ?? (blockId ? toggleRememberedExpanded : toggleLocalExpanded);
  const headerLayoutStyle = variant === 'plain'
    ? styles.foldHeaderPlain
    : {
      gap: layout.foldHeaderGap,
      minHeight: layout.foldHeaderMinHeight,
      paddingHorizontal: layout.foldHeaderPaddingHorizontal,
      paddingVertical: layout.foldHeaderPaddingVertical,
    };
  const chevron = expanded ? (
    <ChevronDown color={colors.textTertiary} size={chevronSize} strokeWidth={iconStroke.regular} />
  ) : (
    <ChevronRight color={colors.textTertiary} size={chevronSize} strokeWidth={iconStroke.regular} />
  );
  return (
    <View style={variant === 'card' ? styles.foldCard : styles.foldPlain}>
      <FoldableHeaderButton
        accessibilityLabel={expanded ? t('message.renderer.collapseRow', { label: title }) : t('message.renderer.expandRow', { label: title })}
        expanded={expanded}
        hitSlop={variant === 'plain' ? FOLDABLE_HEADER_HIT_SLOP : undefined}
        onPress={toggleExpanded}
        style={headerLayoutStyle}
        testID={testID}
      >
        {chevronPosition === 'leading' ? chevron : null}
        {leadingIcon}
        <View style={styles.foldText}>
          <Text
            style={[
              styles.foldTitle,
              variant === 'plain' && styles.foldTitlePlain,
            ]}
            numberOfLines={1}
          >
            {title}
          </Text>
          {subtitle ? <Text style={styles.foldSubtitle} numberOfLines={1}>{subtitle}</Text> : null}
        </View>
        {trailingMeta}
        {chevronPosition === 'trailing' ? chevron : null}
      </FoldableHeaderButton>
      {footer}
      {expanded ? (
        <View style={[
          styles.foldBody,
          variant === 'plain'
            ? styles.foldBodyPlain
            : {
              paddingBottom: layout.foldBodyPaddingBottom,
              paddingHorizontal: layout.foldBodyPaddingHorizontal,
            },
        ]}>
          {children}
        </View>
      ) : collapsedBody ? (
        <View style={[
          styles.foldBody,
          variant === 'plain'
            ? styles.foldBodyPlain
            : {
              paddingBottom: layout.foldBodyPaddingBottom,
              paddingHorizontal: layout.foldBodyPaddingHorizontal,
            },
        ]}>
          {collapsedBody}
        </View>
      ) : null}
    </View>
  );
}

function FoldableHeaderButton({
  accessibilityLabel,
  children,
  expanded,
  hitSlop,
  onPress,
  style,
  testID,
}: {
  accessibilityLabel: string;
  children: ReactNode;
  expanded: boolean;
  hitSlop?: typeof FOLDABLE_HEADER_HIT_SLOP;
  onPress: () => void;
  style?: StyleProp<ViewStyle>;
  testID?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  return (
    <Pressable
      accessibilityLabel={accessibilityLabel}
      accessibilityRole="button"
      accessibilityState={{ expanded }}
      hitSlop={hitSlop}
      onPress={onPress}
      style={({ pressed }) => [
        styles.foldHeader,
        style,
        pressed && styles.pressed,
      ]}
      testID={testID}
    >
      {children}
    </Pressable>
  );
}

function Rail({ children, layout }: { children: ReactNode; layout: MessageHierarchyLayout }) {
  const styles = useThemedStyles(makeStyles);
  return <View style={[styles.rail, { paddingLeft: layout.railPaddingLeft }]}>{children}</View>;
}

// 协同卡片统一外壳:FoldablePanel(card 变体)+ leadingIcon + title + 可折叠 body(经 Rail 缩进)。
// 子 agent 嵌套卡(SubagentCard)与 Orca 协同卡(OrcaCollabCard,派活/回报)共用同一套 chrome,
// 视觉一致;各自数据路径独立(SubagentCard 走 parentUuid 分组,OrcaCollabCard 走 message.orcaCard)。
// children 用 render-prop 拿到 layout(内层 stack 间距等)。
function CollabCardShell({
  blockId,
  controlledExpanded,
  onControlledToggle,
  leadingIcon,
  title,
  subtitle,
  defaultExpanded = false,
  screenWidth,
  testID,
  children,
}: {
  blockId?: string;
  controlledExpanded?: boolean;
  onControlledToggle?: () => void;
  leadingIcon: ReactNode;
  title: string;
  subtitle?: string;
  /** 仅无 blockId 时生效;blockId 存在时由共享记忆决定。 */
  defaultExpanded?: boolean;
  screenWidth?: number;
  testID?: string;
  children: (layout: MessageHierarchyLayout) => ReactNode;
}) {
  const layout = useMemo(() => buildMessageHierarchyLayout({
    screenWidth,
    summaryCount: 0,
  }), [screenWidth]);
  return (
    <FoldablePanel
      blockId={blockId}
      controlledExpanded={controlledExpanded}
      onControlledToggle={onControlledToggle}
      title={title}
      subtitle={subtitle}
      defaultExpanded={defaultExpanded}
      leadingIcon={leadingIcon}
      layout={layout}
      testID={testID}
      variant="card"
    >
      <Rail layout={layout}>{children(layout)}</Rail>
    </FoldablePanel>
  );
}

// 模块级常量:不依赖任何 prop/state,避免 MobileAgentSwitchCard 每次重渲染重建闭包。
const agentSwitchEngineLabel = mobileAgentLabelFromUnknown;

// 交接正文是否为英文格式(与 desktop SystemCard.tsx 同款判据)。content.handoff 是持久化
// 数据:英文化之前落库的行仍是中文正文,升级后展开老卡片看到的就是中文——标题里「原文为
// 英文」那句只能对新格式说。判据取英文结束标记的公共尾巴:三种英文标记都含它,旧中文标记不含。
const ENGLISH_HANDOFF_TERMINATOR_TAIL = "; the user's new message follows ==";

function isEnglishSourceHandoff(handoff: string): boolean {
  // 锚在尾部而非 includes(与 desktop SystemCard.tsx 同款):正文里嵌着历史原文,
  // 可能自身就含这段尾串,那样旧中文交接会被误判成英文。
  return handoff.trimEnd().endsWith(ENGLISH_HANDOFF_TERMINATOR_TAIL);
}

// session-agent-switch 边界卡 —— 1:1 对齐桌面 SystemCard.tsx 的 AgentSwitchCard:
// 「分隔线 + 居中药丸」语言(⇄ + 已从 X 切换到 Y + · 目标模型 + 可选 · 已续接原会话),
// 而非通用盒子卡片。药丸可点展开交接摘要面板(切换时发给新引擎的上下文全文,数据来自
// desktop 落库 agent_switch 行 content.handoff)。全灰度、走主题 token,无 chromatic 色。
function MobileAgentSwitchCard({ data }: { data?: Record<string, unknown> }) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  const [expanded, setExpanded] = useRecyclingState(false);
  const from = agentSwitchEngineLabel(data?.fromAgentKind);
  const to = agentSwitchEngineLabel(data?.toAgentKind);
  const toModel = typeof data?.toModel === 'string' ? data.toModel : '';
  const handoff = typeof data?.handoff === 'string' ? data.handoff : '';
  const resumed = data?.resumed === true;
  // 远程 Agent 换了电脑:药丸说位置(「Agent 改到 X 运行」),否则仍是「已从 X 切换到 Y」。
  const modelOnly = data?.modelOnly === true;
  const label = modelOnly ? `${data?.fromModel ?? ''} → ${toModel}` : formatAgentSwitchLocationLabel(data, (key, options) => t(key, options))
    ?? t('message.renderer.agentSwitchLabel', { from, to });

  return (
    <View style={styles.agentSwitchWrap} testID="message.systemCard.agent-switch">
      <View style={styles.agentSwitchRow}>
        <View style={styles.agentSwitchDivider} />
        <Pressable
          onPress={handoff ? () => setExpanded((v) => !v) : undefined}
          disabled={!handoff}
          accessibilityRole={handoff ? 'button' : undefined}
          accessibilityLabel={handoff ? t('message.renderer.agentSwitchViewHandoff', { label }) : label}
          style={styles.agentSwitchPill}
        >
          <ArrowLeftRight color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />
          <Text style={styles.agentSwitchPillText} numberOfLines={1}>{label}</Text>
          {toModel && !modelOnly ? (
            <>
              <Text style={styles.agentSwitchDot}>·</Text>
              <Text style={styles.agentSwitchModel} numberOfLines={1}>{toModel}</Text>
            </>
          ) : null}
          {resumed || data?.nativeHistory === 'fallback' ? (
            <>
              <Text style={styles.agentSwitchDot}>·</Text>
              <Text style={styles.agentSwitchPillText} numberOfLines={1}>{t(data?.nativeHistory === 'fallback' ? 'message.renderer.sessionFallbackPill' : 'message.renderer.sessionResumedPill')}</Text>
            </>
          ) : null}
          {handoff ? (
            expanded
              ? <ChevronDown color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />
              : <ChevronRight color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />
          ) : null}
        </Pressable>
        <View style={styles.agentSwitchDivider} />
      </View>
      {expanded && handoff ? (
        <View style={styles.agentSwitchHandoffPanel}>
          <Text style={styles.agentSwitchHandoffTitle}>
            {t(
              isEnglishSourceHandoff(handoff)
                ? 'message.renderer.handoffContentDescEnglishSource'
                : 'message.renderer.handoffContentDesc',
            )}
          </Text>
          {/* 交接全文内联展开:卡片本身在消息列表(LegendList)内,不再套内层 ScrollView——
              Android 上嵌套竖向滚动会被父列表截获手势导致内层滚不动(Fabric 更甚)。
              内联让外层列表统一滚动,iOS/Android 行为一致。 */}
          <Text selectable style={styles.agentSwitchHandoffText}>{handoff}</Text>
        </View>
      ) : null}
    </View>
  );
}

function MobileSystemCard({
  autoResumeInFlight,
  data,
  type,
}: {
  autoResumeInFlight?: boolean;
  data?: Record<string, unknown>;
  type: NonNullable<NormalizedRemoteMessage['systemCardType']>;
}) {
  const styles = useThemedStyles(makeStyles);
  if (type === 'compact' || type === 'goal-complete' || type === 'goal-resumed' || type === 'context-rebuild') {
    return <MobileBoundaryNotice type={type} data={data} />;
  }
  // agent-switch 走专用「分隔线 + 药丸」渲染(对齐桌面),不落通用盒子卡片。
  if (type === 'agent-switch') return <MobileAgentSwitchCard data={data} />;
  if (type === 'input-handoff') return <InputHandoffRecordRow data={data} />;
  // auto-resume 复用桌面 AgentActionRow 的单行状态布局:默认只显示当前状态和压缩后的
  // 中断原因,完整诊断按需展开,避免底层错误全文把手机消息流撑成一张大卡片。
  if (type === 'auto-resume') {
    return <MobileAutoResumeActionRow data={data} inFlight={autoResumeInFlight === true} />;
  }
  const card = formatMobileSystemCard(type, data);
  return (
    <View style={styles.systemCard} testID={`message.systemCard.${type}`}>
      <Text style={styles.systemCardTitle}>{card.title}</Text>
      {card.subtitle ? <Text style={styles.systemCardBody}>{card.subtitle}</Text> : null}
      {card.body ? <Text style={styles.systemCardBody}>{card.body}</Text> : null}
      {card.rows.length > 0 ? (
        <View style={styles.systemCardRows}>
          {card.rows.map((row, index) => (
            <View key={`${row.label}:${index}`} style={styles.systemCardRow}>
              <Text style={styles.systemCardLabel} numberOfLines={1}>{row.label}</Text>
              <Text style={styles.systemCardValue}>{row.value}</Text>
            </View>
          ))}
        </View>
      ) : null}
    </View>
  );
}

function MobileAutoResumeActionRow({
  data,
  inFlight,
}: {
  data?: Record<string, unknown>;
  inFlight: boolean;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  const [expanded, setExpanded] = useRecyclingState(false);
  const presentation = getMobileAutoResumePresentation(data, inFlight);
  const { canExpand, hasProgress, info, state, summary } = presentation;

  if (state === 'separator') {
    const label = t('message.systemCard.autoResume.separator');
    return (
      <View style={styles.autoResumeSeparator} testID="message.systemCard.auto-resume-separator">
        <View style={styles.autoResumeDivider} />
        <View style={styles.autoResumeSeparatorPill}>
          <RefreshCw color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />
          <Text style={styles.autoResumeSeparatorText}>{label}</Text>
        </View>
        <View style={styles.autoResumeDivider} />
      </View>
    );
  }

  const label = info.groupSwitchPending
    ? t('message.systemCard.autoResume.groupSwitchPending')
    : info.agentSwitch
    ? t(`message.systemCard.autoResume.agentSwitch.${info.agentSwitch.cause}`, {
        from: info.agentSwitch.from,
        to: info.agentSwitch.to,
      })
    : info.agentReconnect
    ? info.agentReconnect.computer
      ? t('message.systemCard.autoResume.agentReconnect.named', { computer: info.agentReconnect.computer })
      : t('message.systemCard.autoResume.agentReconnect.unnamed')
    : info.groupSwitch
    ? t('message.systemCard.autoResume.groupSwitch')
    : info.usageLimitReset
    ? t('message.systemCard.autoResume.usageReset')
    : state === 'live'
    ? hasProgress
      ? t('message.systemCard.autoResume.pendingWithProgress', {
          attempt: info.attempt,
          total: info.maxAttempts,
        })
      : t('message.systemCard.autoResume.pending')
    : state === 'succeeded'
      ? t('message.systemCard.autoResume.succeeded')
      : state === 'failed'
        ? t('message.systemCard.autoResume.failed')
        : t('message.systemCard.autoResume.neutral');
  const accessibilityLabel = summary ? `${label}: ${summary}` : label;

  return (
    <View style={styles.autoResumeRow} testID="message.systemCard.auto-resume">
      <Pressable
        accessibilityLabel={accessibilityLabel}
        accessibilityRole={canExpand ? 'button' : undefined}
        accessibilityState={canExpand ? { expanded } : undefined}
        disabled={!canExpand}
        onPress={canExpand
          ? () => setExpanded((value) => toggleMobileAutoResumeExpanded(value, canExpand))
          : undefined}
        style={({ pressed }) => [styles.autoResumeHeader, pressed && styles.pressed]}
      >
        <View
          accessible={false}
          accessibilityElementsHidden
          importantForAccessibility="no-hide-descendants"
          style={styles.autoResumeIconSlot}
        >
          {state === 'live' ? (
            <CompactActivityIndicator color={colors.textTertiary} size={iconSize.sm} />
          ) : state === 'succeeded' ? (
            <Check color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          ) : state === 'failed' ? (
            <X color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          ) : (
            <RefreshCw color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          )}
        </View>
        <Text style={styles.autoResumeTitle} numberOfLines={1}>{label}</Text>
        {summary ? (
          <Text style={styles.autoResumeSummary} numberOfLines={1}>{summary}</Text>
        ) : (
          <View style={styles.autoResumeHeaderSpacer} />
        )}
        {canExpand ? (
          expanded ? (
            <ChevronDown color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          ) : (
            <ChevronRight color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          )
        ) : null}
      </Pressable>
      {expanded && canExpand ? (
        <View style={styles.autoResumeDetailPanel}>
          {info.error ? (
            <>
              <Text style={styles.autoResumeDetailLabel}>
                {t('message.systemCard.autoResume.detail.reason')}
              </Text>
              <Text selectable style={styles.autoResumeDetailText}>{info.error}</Text>
            </>
          ) : null}
          {(hasProgress || info.sessionTotal !== undefined) ? (
            <View style={[styles.autoResumeDetailMeta, info.error && styles.autoResumeDetailMetaWithReason]}>
              {hasProgress ? (
                <Text style={styles.autoResumeDetailMetaText}>
                  {t('message.systemCard.autoResume.detail.attempt', {
                    attempt: info.attempt,
                    total: info.maxAttempts,
                  })}
                </Text>
              ) : null}
              {info.sessionTotal !== undefined ? (
                <Text style={styles.autoResumeDetailMetaText}>
                  {t('message.systemCard.autoResume.detail.sessionTotal', {
                    count: info.sessionTotal,
                  })}
                </Text>
              ) : null}
            </View>
          ) : null}
        </View>
      ) : null}
    </View>
  );
}

// Orca 协同卡片:Lead 派活(dispatch)/ worker 回报(report)。与 SubagentCard 共用 CollabCardShell
// chrome(同款 leadingIcon+title+可折叠 body),视觉一致;数据路径仍是 message.orcaCard,不碰 parentUuid。
// Lead 派活和 worker 回报均默认收起;正文可选中(长按复制)。识别/文案抽取在 @/session/orcaCollab。
function OrcaCollabCard({ card, screenWidth, blockKey }: {
  card: OrcaCollabCardModel; screenWidth?: number; blockKey: string;
}) {
  const { accountGeneration } = useAuth();
  // Remember manual expansions using the
  // existing bounded block store, including across native route reconstruction.
  // Key prefix orca-expanded- (not the old orca-toggled-): dispatch cards used to default open, so a
  // remembered legacy toggle meant "collapsed"; never reinterpret it as "expanded".
  const [expanded, toggleExpanded] = useFoldableExpandedState(
    `orca-expanded-${JSON.stringify([accountGeneration, blockKey, card.variant])}`, false,
  );
  const { colors } = useTheme();
  const styles = useThemedStyles(makeStyles);
  const body = card.body && card.body.trim() ? card.body : null;
  // body 为空时不渲染折叠件(无 chevron、无空 body 区),退化成静态卡,只显图标 + 标题。
  if (!body) {
    return (
      <View style={styles.foldCard} testID={`message.orcaCard.${card.variant}`}>
        <View style={styles.orcaStaticHeader}>
          <Bot color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />
          <Text style={styles.foldTitle} numberOfLines={1}>{card.title}</Text>
        </View>
      </View>
    );
  }
  return (
    <CollabCardShell
      leadingIcon={<Bot color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />}
      title={card.title}
      controlledExpanded={expanded}
      onControlledToggle={toggleExpanded}
      screenWidth={screenWidth}
      testID={`message.orcaCard.${card.variant}`}
    >
      {() => (
        <Text selectable style={styles.systemCardBody} testID="message.orcaCardBody">
          {body}
        </Text>
      )}
    </CollabCardShell>
  );
}

const ViewabilityGatedMcpAppCard = memo(function ViewabilityGatedMcpAppCard(
  props: Omit<ComponentProps<typeof McpAppCard>, 'active'>,
) {
  const heavyContentVisible = useContext(MessageHeavyContentVisibilityContext);
  return <McpAppCard {...props} active={heavyContentVisible} />;
});

const ViewabilityGatedMermaidDiagram = memo(function ViewabilityGatedMermaidDiagram({
  source,
  testID,
}: {
  source: string;
  testID?: string;
}) {
  const heavyContentVisible = useContext(MessageHeavyContentVisibilityContext);
  return (
    <MermaidDiagramWebView
      active={heavyContentVisible}
      cachePreview
      source={source}
      testID={testID}
    />
  );
});

const ViewabilityGatedMathFormula = memo(function ViewabilityGatedMathFormula({
  source,
  testID,
}: {
  source: string;
  testID?: string;
}) {
  const heavyContentVisible = useContext(MessageHeavyContentVisibilityContext);
  return (
    <MathFormulaWebView
      active={heavyContentVisible}
      source={source}
      testID={testID}
    />
  );
});

/** A frozen task result reads like a reply: same Markdown, links and file chips (Desktop MarkdownRenderer). */
function CompanionCardMarkdown({ text, actions, messageKey }: { text: string; actions: MessageActions; messageKey: string }) {
  const layout = useMemo(() => buildMessageContentLayout({ screenWidth: actions.screenWidth }), [actions.screenWidth]);
  return <MarkdownBody renderRichAnswers markdownImageCacheKey={messageKey} layout={layout} text={text} selectable
    onOpenPayload={actions.onOpenPayload} onOpenSessionLink={actions.onOpenSessionLink} />;
}

// 消息正文统一走原生 markdown 渲染(流式与完成态同一条路径,完成时无"原生→WebView"的切换跳变)。
// 文本选择 = 完成态消息的各块 Text 原生 selectable:长按文字就地弹系统选择手柄/Copy 菜单,
// 不跳转界面;整条复制走操作条按钮。选择按块进行(原生 Text 能力边界,跨段选择做不到)。
function MarkdownBodyBase({
  allowIosUITextView = true,
  codeCopyEnabled = true,
  boundTextRuns = false,
  markdownImageCacheKey,
  layout,
  onOpenPayload,
  onOpenSessionLink,
  pinContentWidth = false,
  selectable,
  streaming,
  text,
}: {
  renderRichAnswers?: boolean;
  /** Persisted row ids may replace stream ids; clientId stays stable across that handoff. */
  richStateKey?: string;
  /** 普通任务的超长展开正文可禁用 UITextView,伙伴改用有界文本分组。 */
  allowIosUITextView?: boolean;
  /** Reuse bounded native text runs for expanded companion messages on iOS. */
  boundTextRuns?: boolean;
  /** 本地 Markdown 图片的稳定消息身份,避免后续消息复用同一路径的旧媒体缓存。 */
  markdownImageCacheKey?: string;
  layout: MessageContentLayout;
  onOpenPayload?: (payload: MessagePayload) => void;
  /** 会话深链 chip 点击回调(app 内跳转)。 */
  onOpenSessionLink?: (url: string) => void;
  /**
   * 仅 agent 拉伸气泡启用:用户气泡是 hug + maxWidth 86%,钉死测宽会把展开态撑出
   * 气泡(长代码围栏横向裁切 + 纵向巨高空白)。
   */
  pinContentWidth?: boolean;
  /** 分享图片选择态关闭块级操作,避免把按钮带进导出内容。 */
  codeCopyEnabled?: boolean;
  /** 完成态消息为 true:各块 Text 开原生选中(含内嵌图片 View 的块除外,Android 上有风险)。 */
  selectable?: boolean;
  /** 消息流式中:文件 chip 层跳过远端验证。 */
  streaming?: boolean;
  text: string;
}) {
  const { colors } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const chatFilePathContext = useContext(ChatFilePathContext);
  const resolveMarkdownMedia = useContext(MarkdownRemoteMediaContext);
  // iOS UITextView 在 stretch/百分比宽度下会偶发只量出部分高度,LegendList 按这次
  // 偏矮的 onLayout 裁切 agent 回复;点分享会换上确定宽度的容器从而完整显示。
  // 外层始终 stretch 测可用宽,内层再钉像素宽:测宽不能钉在自己身上,否则旋转/
  // 分屏变宽后 onLayout 仍报旧值。1px 内抖动忽略,避免公式 WebView 重挂。
  const [contentWidth, setContentWidth] = useRecyclingState(0);
  const handleSettledWidthLayout = useCallback((event: LayoutChangeEvent) => {
    if (!pinContentWidth) return;
    const nextWidth = Math.round(event.nativeEvent.layout.width);
    setContentWidth((current) => nextSettledContentWidth(current, nextWidth));
  }, [pinContentWidth]);
  const pinSettledWidth = pinContentWidth && contentWidth > 0;
  const settledTextStyle = useMemo(() => pinSettledWidth
    ? [styles.messageText, { width: contentWidth }]
    : styles.messageText, [contentWidth, pinSettledWidth, styles.messageText]);
  const markdownParseRef = useRef<MobileMarkdownParseResult | null>(null);
  const markdownParse = useMemo(() => {
    const startedAt = typeof performance !== 'undefined' && typeof performance.now === 'function'
      ? performance.now()
      : Date.now();
    const result = parseMobileMarkdownIncremental(text, markdownParseRef.current);
    const finishedAt = typeof performance !== 'undefined' && typeof performance.now === 'function'
      ? performance.now()
      : Date.now();
    return {
      result,
      durationMs: Math.max(0, finishedAt - startedAt),
    };
  }, [text]);
  useLayoutEffect(() => {
    markdownParseRef.current = markdownParse.result;
    if (__DEV__ || mobileDebugEnabled()) recordMobileMarkdownParse(markdownParse.result, markdownParse.durationMs);
    if (mobileDebugEnabled()) mobileDebugLog('debug', 'performance', 'markdown parsed', {
      durationMs: markdownParse.durationMs, incremental: markdownParse.result.incremental,
      reusedBlockCount: markdownParse.result.reusedBlockCount, parsedSourceUtf16Length: markdownParse.result.parsedSourceUtf16Length,
    });
  }, [markdownParse]);
  const blocks = markdownParse.result.blocks;
  const managedImagePreviewUrl = useCallback((url: string) => resolveMarkdownMedia
    ? mobileMarkdownManagedImagePreviewUrl(
      url, chatFilePathContext?.workdir, markdownImageCacheKey,
      chatFilePathContext?.remoteHostId, chatFilePathContext?.sessionId,
    ) : null, [chatFilePathContext, markdownImageCacheKey, resolveMarkdownMedia]);
  const imageRendersPreview = useCallback((inline: Extract<MobileMarkdownInline, { type: 'image' }>) => (
    isMobileMarkdownImageDirectUrl(inline.url) || managedImagePreviewUrl(inline.url) !== null
  ), [managedImagePreviewUrl]);
  // 图片预览内嵌 View,不能放进 Android selectable Text 或 iOS UITextView。
  const inlinesSelectable = useCallback((inlines: readonly MobileMarkdownInline[]) => (
    selectable === true
    && !inlines.some((inline) => inline.type === 'image' && imageRendersPreview(inline))
  ), [imageRendersPreview, selectable]);
  // 正文 Markdown 图片(![](url) / 安全 <img>)点击后走既有媒体 payload 查看器,与附件图片同一条链路。
  const openMarkdownImage = useCallback((url: string, alt?: string) => {
    if (!onOpenPayload) return;
    // Match the scoped preview/gallery URL; outside-workdir chips remain
    // explicitly openable through the existing single-image fallback.
    const resolvedUrl = managedImagePreviewUrl(url) ?? mobileMarkdownImageUrlForWorkdir(
      url,
      chatFilePathContext?.workdir,
      markdownImageCacheKey,
      chatFilePathContext?.remoteHostId,
      chatFilePathContext?.sessionId,
    );
    if (!resolvedUrl) return;
    const title = mobileMarkdownImageTitle(resolvedUrl, alt);
    // http(s) 直连预览;xdt 系 scheme 非直连,ImageLightbox 经 remote-media resolver 取图。
    onOpenPayload(buildMediaPayload(
      { kind: 'image', url: resolvedUrl, title, previewable: isMobileMarkdownImageDirectUrl(resolvedUrl) },
      title,
    ));
  }, [
    chatFilePathContext?.remoteHostId,
    chatFilePathContext?.sessionId,
    chatFilePathContext?.workdir,
    markdownImageCacheKey,
    managedImagePreviewUrl,
    onOpenPayload,
  ]);
  const openMarkdownMedia = useMemo(() => onOpenPayload
    ? (url: string, title: string, kind: 'video') => {
      onOpenPayload(buildMediaPayload({ kind, url, title, previewable: false }, title));
    }
    : undefined, [onOpenPayload]);
  const renderManagedImage = useCallback((inline: Extract<MobileMarkdownInline, { type: 'image' }>) => {
    const url = managedImagePreviewUrl(inline.url);
    if (!url) return null;
    const size = mobileMarkdownInlineImageSize(inline);
    const label = mobileMarkdownImageTitle(url, inline.alt);
    return (
      <View style={size}>
        <MediaPreview
          key={url}
          layout={{ ...layout, imagePreviewWidth: size.width, imagePreviewHeight: size.height }}
          media={{ kind: 'image', url, title: label, previewable: false }}
          label={label}
          onOpen={onOpenPayload ? () => openMarkdownImage(inline.url, inline.alt) : undefined}
          onResolveRemoteMedia={resolveMarkdownMedia}
        />
      </View>
    );
  }, [layout, managedImagePreviewUrl, onOpenPayload, openMarkdownImage, resolveMarkdownMedia]);
  // Preserve the inline renderer while streaming or unrelated task metadata
  // changes; referenced task title changes still refresh every affected chip.
  const sessionLinkTitles = useMarkdownSessionLinkTitles(text);
  const renderInlines = useCallback(
    (
      inlines: readonly MobileMarkdownInline[],
      SpanText?: typeof Text,
      baseStyle?: StyleProp<TextStyle>,
      keyPrefix?: string,
    ) => (
      inlines.map((inline, index) => renderInline(inline, index, styles, {
        baseStyle,
        keyPrefix,
        onOpenImage: openMarkdownImage,
        renderManagedImage,
        onOpenMedia: openMarkdownMedia,
        onOpenSessionLink,
        sessionLinkTitles,
        SpanText,
        streaming,
      }))
    ),
    // renderInline also reads translated fallback labels. Invalidate completed
    // memoized text blocks when useTranslation refreshes its bound translator.
    [onOpenSessionLink, openMarkdownImage, openMarkdownMedia, renderManagedImage, sessionLinkTitles, streaming, styles, t],
  );
  const textRunGroupingOptions = useMemo(() => ({
    ...(Platform.OS === 'android' ? ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS : {}),
    ...(boundTextRuns ? ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS : {}),
    imageRendersPreview,
  }), [boundTextRuns, imageRendersPreview]);
  // 连续纯文本块合并为 text_run,图片预览保持独立。
  // Android selectable Text 在超长原生文本视图里会偶发高度/滚动协商异常,长 run 分块
  // 后仍保留块内跨段选择。伙伴的 iOS 长消息展开也复用同一分块,避免巨型 UITextView。
  const groups = useMemo(
    () => groupMobileMarkdownSelectableBlocks(blocks, textRunGroupingOptions),
    [blocks, textRunGroupingOptions],
  );
  // 块可选中且 iOS → 嵌套 span 必须是 UITextView 家族;其余场景缺省 RN Text。
  const spanFor = useCallback((blockSelectable: boolean) => (
    blockSelectable && allowIosUITextView && Platform.OS === 'ios'
      ? MarkdownSelectableSpan
      : undefined
  ), [allowIosUITextView]);
  // 文本运行组:连续纯文本块(段落/标题/列表项)合进同一个原生文本视图,
  // 原生选择手柄即可横跨段落(单个 text view 是 iOS/Android 原生选择的天然边界)。
  // 段间距用「lineHeight = markdownBodyGap 的空行 span」还原:原生文本树内没有块级 gap 可用,
  // 一个高度恰为 gap 的空行在视觉上与原块间距一致。由单块切出的 continuation 不插间距。
  // 列表项在树内表达为「marker 前缀 span + 正文」
  // (无悬挂缩进;任务项以 ☑/☐ 字符替代原边框小方块)。
  const renderTextRunBlock = useCallback((block: MobileMarkdownBlock, leadingGap: boolean): ReactNode => {
    if (block.type !== 'paragraph' && block.type !== 'heading' && block.type !== 'list_item') return null;
    const runSelectable = selectable === true;
    const RunSpan = spanFor(runSelectable) ?? Text;
    const spans: ReactNode[] = [];
    if (leadingGap) {
      spans.push(
        <RunSpan key={`${block.key}:gap`} style={{ lineHeight: layout.markdownBodyGap }}>
          {'\n\n'}
        </RunSpan>,
      );
    }
    const baseStyle: StyleProp<TextStyle> = block.type === 'heading'
      ? [styles.markdownHeading, headingSizeStyle(styles, block.level)]
      : styles.messageText;
    if (block.type === 'list_item' && !('textRunContinuation' in block && block.textRunContinuation)) {
      const task = typeof block.checked === 'boolean';
      spans.push(
        <RunSpan key={`${block.key}:marker`} style={[styles.messageText, styles.markdownListMarkerInline]}>
          {task ? (block.checked ? '☑ ' : '☐ ') : block.ordered ? `${block.marker} ` : '• '}
        </RunSpan>,
      );
    }
    spans.push(...renderInlines(block.inlines, spanFor(runSelectable), baseStyle, block.key));
    return spans;
  }, [layout.markdownBodyGap, renderInlines, selectable, spanFor, styles]);
  const renderTextRun = (group: Extract<MobileMarkdownBlockGroup, { type: 'text_run' }>): ReactNode => {
    const runSelectable = selectable === true;
    return (
      <MarkdownSelectableText
        allowIosUITextView={allowIosUITextView}
        alignmentTextStyles={group.blocks.map((block) => block.type === 'heading'
          ? headingSizeStyle(styles, block.level)
          : styles.messageText)}
        key={`${group.key}:${pinSettledWidth ? contentWidth : 'hug'}`}
        selectable={runSelectable}
        style={settledTextStyle}
        testID="message.markdownTextRun"
      >
        {group.blocks.map((block, index) => (
          <MarkdownBlockContent
            key={block.key}
            block={block}
            leadingGap={index > 0 && !block.textRunContinuation}
            renderBlock={renderTextRunBlock}
          />
        ))}
      </MarkdownSelectableText>
    );
  };
  const renderSingleBlock = useCallback((block: MobileMarkdownBlock): ReactNode => {
    // Only text_run groups are bounded. Code, quotes and table cells retain
    // the stable RN Text fallback in expanded long companion messages.
    const singleBlockAllowsIosUITextView = allowIosUITextView && !boundTextRuns;
    const singleBlockSpanFor = (blockSelectable: boolean) => singleBlockAllowsIosUITextView
      ? spanFor(blockSelectable)
      : undefined;
    if (block.type === 'mermaid') {
      // 内联图表按「图片」形态呈现:无卡片 chrome、无标签文字、无按钮,
      // 就是一块圆角图表;点击任意位置打开沉浸式全屏详情(透明 Pressable
      // 盖住整块——WebView 会吞掉触摸事件,不盖层拿不到点击)。
      return (
        <View key={block.key} testID="message.mermaidPreviewButton">
          <ViewabilityGatedMermaidDiagram source={block.text} testID="message.mermaidDiagram" />
          {onOpenPayload ? (
            <Pressable
              accessibilityLabel={t('message.renderer.openDiagramDetail')}
              accessibilityRole="button"
              onPress={() => onOpenPayload(buildMermaidPayload(block.text))}
              style={StyleSheet.absoluteFill}
              testID="message.mermaidPreviewTap"
            />
          ) : null}
        </View>
      );
    }
    if (block.type === 'math') {
      // display 公式:WebView + KaTeX(形态对齐 mermaid 块,无 chip 卡壳——
      // 公式在视觉上是正文的一部分,背景与气泡底色一致)。
      return (
        <ViewabilityGatedMathFormula
          key={block.key}
          source={block.text}
          testID="message.mathFormula"
        />
      );
    }
    if (block.type === 'code') {
      // 围栏代码在气泡内换行,不用横向 ScrollView:后者在展开长用户消息时
      // 会按未折行内容报出超高,气泡巨幅空白并把每行裁在右侧圆角外。
      const showCodeCopyButton = codeCopyEnabled && block.text.trim().length > 0;
      return (
        <View key={block.key} style={styles.markdownCodeFrame}>
          {showCodeCopyButton ? <MarkdownCodeCopyButton text={block.text} /> : null}
          <View
            style={[
              styles.markdownCodeContent,
              {
                paddingHorizontal: layout.codePaddingHorizontal,
                paddingBottom: layout.codePaddingVertical,
                paddingTop: showCodeCopyButton ? 0 : layout.codePaddingVertical,
              },
            ]}
          >
            <HighlightedCodeText
              SpanComponent={spanFor(selectable === true && singleBlockAllowsIosUITextView) ?? Text}
              allowIosUITextView={singleBlockAllowsIosUITextView}
              language={block.language}
              selectable={selectable === true}
              styles={styles}
              text={block.text}
            />
          </View>
        </View>
      );
    }
    if (block.type === 'heading') {
      const headingStyle = [
        styles.markdownHeading,
        headingSizeStyle(styles, block.level),
      ];
      const headingSelectable = inlinesSelectable(block.inlines);
      return (
        <MarkdownSelectableText
          allowIosUITextView={singleBlockAllowsIosUITextView}
          key={block.key}
          selectable={headingSelectable}
          style={headingStyle}
          testID="message.markdownHeading"
        >
          {renderInlines(block.inlines, singleBlockSpanFor(headingSelectable))}
        </MarkdownSelectableText>
      );
    }
    if (block.type === 'blockquote') {
      return (
        <View key={block.key} style={styles.markdownQuote} testID="message.markdownQuote">
          <MarkdownSelectableText
            allowIosUITextView={singleBlockAllowsIosUITextView}
            selectable={inlinesSelectable(block.inlines)}
            style={[styles.messageText, styles.markdownQuoteText]}
          >
            {renderInlines(block.inlines, singleBlockSpanFor(inlinesSelectable(block.inlines)))}
          </MarkdownSelectableText>
        </View>
      );
    }
    if (block.type === 'list_item') {
      const task = typeof block.checked === 'boolean';
      return (
        <View
          key={block.key}
          style={[styles.markdownListRow, { gap: layout.markdownListGap }]}
          testID={task ? 'message.markdownTaskItem' : undefined}
        >
          <Text style={[
            styles.markdownListMarker,
            { width: layout.markdownListMarkerWidth },
            task && styles.markdownTaskMarker,
          ]}>
            {task ? (block.checked ? '✓' : '') : block.ordered ? block.marker : '•'}
          </Text>
          <MarkdownSelectableText
            allowIosUITextView={singleBlockAllowsIosUITextView}
            selectable={inlinesSelectable(block.inlines)}
            style={[styles.messageText, styles.markdownListText]}
          >
            {renderInlines(block.inlines, singleBlockSpanFor(inlinesSelectable(block.inlines)))}
          </MarkdownSelectableText>
        </View>
      );
    }
    if (block.type === 'table') {
      const columnWidths = buildMobileMarkdownTableColumnWidths({
        header: block.header,
        rows: block.rows,
        availableWidth: layout.markdownTableAvailableWidth,
        minWidth: layout.markdownTableCellMinWidth,
      });
      return (
        <ScrollView
          horizontal
          key={block.key}
          style={styles.markdownTableScroll}
          testID="message.markdownTable"
        >
          <View style={styles.markdownTable}>
            <View style={[styles.markdownTableRow, styles.markdownTableHeaderRow]}>
              {columnWidths.map((columnWidth, index) => {
                const cell = block.header[index] ?? [];
                return (
                  <MarkdownSelectableText
                    adjustVerticalAlignment={false}
                    allowIosUITextView={singleBlockAllowsIosUITextView}
                    key={`${block.key}:th:${index}`}
                    selectable={inlinesSelectable(cell)}
                    style={[
                      styles.markdownTableCell,
                      { width: columnWidth },
                      styles.markdownTableHeaderCell,
                    ]}
                  >
                    {renderInlines(cell, singleBlockSpanFor(inlinesSelectable(cell)))}
                  </MarkdownSelectableText>
                );
              })}
            </View>
            {block.rows.map((row) => (
              <View key={row.key} style={styles.markdownTableRow}>
                {columnWidths.map((columnWidth, index) => {
                  const cell = row.cells[index] ?? [];
                  return (
                    <MarkdownSelectableText
                      adjustVerticalAlignment={false}
                      allowIosUITextView={singleBlockAllowsIosUITextView}
                      key={`${row.key}:td:${index}`}
                      selectable={inlinesSelectable(cell)}
                      style={[styles.markdownTableCell, { width: columnWidth }]}
                    >
                      {renderInlines(cell, singleBlockSpanFor(inlinesSelectable(cell)))}
                    </MarkdownSelectableText>
                  );
                })}
              </View>
            ))}
          </View>
        </ScrollView>
      );
    }
    return (
      <MarkdownSelectableText
        allowIosUITextView={singleBlockAllowsIosUITextView}
        key={`${block.key}:${pinSettledWidth ? contentWidth : 'hug'}`}
        selectable={inlinesSelectable(block.inlines)}
        style={settledTextStyle}
      >
        {renderInlines(block.inlines, singleBlockSpanFor(inlinesSelectable(block.inlines)))}
      </MarkdownSelectableText>
    );
  }, [allowIosUITextView, boundTextRuns, codeCopyEnabled, contentWidth, inlinesSelectable, layout, onOpenPayload, pinSettledWidth, renderInlines, selectable, settledTextStyle, spanFor, styles, t]);
  return (
    <View
      collapsable={false}
      onLayout={handleSettledWidthLayout}
      style={[
        styles.markdownBody,
        { maxWidth: '100%' },
        pinContentWidth ? { alignSelf: 'stretch' } : null,
      ]}
      testID="message.markdownBody"
    >
      <View
        collapsable={false}
        style={pinSettledWidth ? { width: contentWidth, maxWidth: '100%' } : null}
      >
      {groups.flatMap((group, groupIndex) => {
        const renderedGroup = group.type === 'text_run'
          ? renderTextRun(group)
          : <MarkdownBlockContent key={group.key} block={group.block} renderBlock={renderSingleBlock} />;
        if (groupIndex === 0 || isTextRunContinuationGroup(group)) {
          return [renderedGroup];
        }
        return [
          <View key={`${group.key}:body-gap`} style={{ height: layout.markdownBodyGap }} />,
          renderedGroup,
        ];
      })}
      </View>
    </View>
  );
}

/**
 * 「下划线 ⇔ 可点」的**唯一判据**(DESIGN.md §14.5 规则①要求双向成立:可点的一定有
 * 下划线,有下划线的一定可点)。onPress 缺席时不给 `markdownLink`,所以在结构上
 * 无法造出「有下划线却点不动」的元素。
 *
 * 为什么要收成一处:PR #1144 的两轮 review 各捉到一个反例(文件阅读器的会话 chip、
 * 以及同一面上本就带下划线 + pointer 的图片 chip),根因都是「加不加下划线」与
 * 「有没有 onPress」在各自的分支里独立决定 —— 判据分散必然漂移。本文件的会话 chip /
 * 图片 chip 的 onPress 也是条件式的(handler 由上层可选注入),同款隐患成立。
 *
 * 所有可点 inline 一律经此取样式,**不要在 case 分支里直接写 `styles.markdownLink`**
 * (chatPathCandidate.test.ts 有源码级守卫钉住这条)。路径 chip 不走这里:它的可点性
 * 由 ChatPathChipSpan 的 `lit` 单点裁决,同样是「一个判据」。
 */
function clickableInlineStyle(
  styles: ReturnType<typeof makeStyles>,
  onPress: undefined | (() => void),
  base: StyleProp<TextStyle>,
  extra?: StyleProp<TextStyle>,
): StyleProp<TextStyle> {
  return [base, onPress ? underlineDecoration(styles, base, styles.markdownLink) : undefined, extra];
}

/**
 * 可点下划线与外层删除线共存:RN 的 textDecorationLine 是单值,后叠的 underline 会盖掉
 * `~~链接~~` 的 line-through。base 已带删除线时改用合并值,两条线都画。
 */
function underlineDecoration(
  styles: ReturnType<typeof makeStyles>,
  base: StyleProp<TextStyle>,
  underline: StyleProp<TextStyle>,
): StyleProp<TextStyle> {
  return StyleSheet.flatten(base)?.textDecorationLine === 'line-through'
    ? [underline, styles.markdownUnderlineStrike]
    : underline;
}

function markdownMarkStyle(
  styles: ReturnType<typeof makeStyles>,
  mark: MobileMarkdownInlineMark,
): StyleProp<TextStyle> {
  if (mark === 'strong') return styles.markdownStrong;
  if (mark === 'emphasis') return styles.markdownEmphasis;
  return styles.markdownStrike;
}

/** 本地路径链接形态的路径 chip 包装:candidate 按 url memo,保证引用稳定——
 *  renderInline 是普通函数,若在其内直接 classify 会每次 render 产新对象,
 *  击穿 ChatPathChipSpan 的 memo/effect 依赖,unknown verdict(不落缓存)的
 *  chip 会随重渲染熄灭再点亮地闪烁(bot review 实捉,规则 7)。 */
function LinkPathChipSpan({
  url,
  display,
  bare,
  baseStyle,
  SpanText,
  styles,
  streaming,
}: {
  url: string;
  display: string;
  /** 正文裸写的路径(非作者手写的 `[label](url)`),决定点亮后是否套等宽 chip。 */
  bare?: boolean;
  baseStyle?: StyleProp<TextStyle>;
  SpanText: typeof Text;
  styles: ReturnType<typeof makeStyles>;
  streaming?: boolean;
}) {
  const candidate = useMemo(() => classifyChatPathLinkTarget(url), [url]);
  // 点亮后是否套等宽 chip,按 DESIGN.md §14.5 的落地推论分三档(与桌面
  // shouldRenderCodeReferenceLabel 的分流一一对应):
  //   - 正文裸写的路径 → **不套**。它的未点亮态是普通正文,套上会让同一句里点亮的
  //     `src/a.ts` 与未点亮的 `src/b.ts` 在字体、底色、下划线三处齐变。
  //   - 作者手写、label 读起来是文件引用(`[README.md](path)`)→ **套**。那是作者的
  //     排版意图,对齐桌面 FileTargetChip。
  //   - 作者手写、散文 label(`[看这份规则](path)`)→ 不套,对齐桌面 ResolvedLocalLink。
  const codeStyled = useMemo(
    () => !bare && candidate !== null && chatPathLabelReadsAsFileReference(display, candidate, url),
    [bare, candidate, display, url],
  );
  return (
    <ChatPathChipSpan
      candidate={candidate}
      explicitLink={!bare}
      chipStyle={
        codeStyled
          ? [baseStyle, styles.markdownInlineCode, underlineDecoration(styles, baseStyle, styles.markdownPathChip)]
          : [baseStyle, underlineDecoration(styles, baseStyle, styles.markdownPathChip)]
      }
      display={display}
      // 未点亮一律回落正文样式(与桌面一致:未解析的 local-candidate 渲染成纯 span)。
      plainStyle={baseStyle}
      SpanText={SpanText}
      streaming={streaming}
    />
  );
}

/** inline code 形态的路径 chip 包装:候选判定 + code 底色样式。 */
function InlineCodePathSpan({
  text,
  baseStyle,
  SpanText,
  styles,
  streaming,
}: {
  text: string;
  baseStyle?: StyleProp<TextStyle>;
  SpanText: typeof Text;
  styles: ReturnType<typeof makeStyles>;
  streaming?: boolean;
}) {
  const candidate = useMemo(() => classifyInlineCodePathCandidate(text), [text]);
  return (
    <ChatPathChipSpan
      candidate={candidate}
      chipStyle={[baseStyle, styles.markdownInlineCode, underlineDecoration(styles, baseStyle, styles.markdownPathChip)]}
      display={text}
      plainStyle={[baseStyle, styles.markdownInlineCode]}
      SpanText={SpanText}
      streaming={streaming}
    />
  );
}

function renderInline(
  inline: MobileMarkdownInline,
  index: number,
  styles: ReturnType<typeof makeStyles>,
  ctx: {
    /** text_run 合并树里,每个 span 都要自带块级基础样式(扁平两级 flatten 不做深层继承)。 */
    baseStyle?: StyleProp<TextStyle>;
    /** text_run 合并树里多个块共父,key 需要块级前缀防冲突。 */
    keyPrefix?: string;
    onOpenImage?: (url: string, alt?: string) => void;
    renderManagedImage?: (inline: Extract<MobileMarkdownInline, { type: 'image' }>) => ReactNode;
    onOpenMedia?: (url: string, title: string, kind: 'video') => void;
    onOpenPayload?: (payload: MessagePayload) => void;
    onOpenSessionLink?: (url: string) => void;
    sessionLinkTitles?: Readonly<Record<string, string>>;
    /** 块可选中且 iOS 时为 MarkdownSelectableSpan(嵌套进 UITextView 原生树);缺省 RN Text。 */
    SpanText?: typeof Text;
    /** 消息流式中:文件 chip 层跳过远端验证(半截路径不发 stat)。 */
    streaming?: boolean;
  } = {},
): ReactNode {
  // 强调里的链接 / 代码等:外层强调样式叠进 baseStyle,其余照常渲染(span 平铺,不嵌套)。
  if (inline.marks?.length) {
    return renderInline({ ...inline, marks: undefined }, index, styles, {
      ...ctx,
      baseStyle: [ctx.baseStyle, ...inline.marks.map((mark) => markdownMarkStyle(styles, mark))],
    });
  }
  const SpanText = ctx.SpanText ?? MessageBodyText;
  const openImage = ctx.onOpenImage ?? (ctx.onOpenPayload
    ? (url: string, alt?: string) => {
        const title = mobileMarkdownImageTitle(url, alt);
        ctx.onOpenPayload?.(buildMediaPayload(
          { kind: 'image', url, title, previewable: isMobileMarkdownImageDirectUrl(url) },
          title,
        ));
      }
    : undefined);
  const spanKey = (suffix: string) => (ctx.keyPrefix ? `${ctx.keyPrefix}:${suffix}` : suffix);
  switch (inline.type) {
    case 'text':
      return <SpanText key={spanKey(`text:${index}`)} style={ctx.baseStyle}>{inline.text}</SpanText>;
    case 'link': {
      if (inline.managedMediaKind) {
        const mediaKind = inline.managedMediaKind;
        const openManagedMedia = ctx.onOpenMedia
          ? () => ctx.onOpenMedia?.(inline.url, inline.text, mediaKind)
          : undefined;
        return (
          <SpanText
            key={spanKey(`media-link:${index}:${inline.url}`)}
            onPress={openManagedMedia}
            style={clickableInlineStyle(styles, openManagedMedia, ctx.baseStyle)}
          >
            {inline.text}
          </SpanText>
        );
      }
      const session = parseSessionDeepLinkUrl(inline.url);
      if (session) {
        return (
          <MarkdownSessionLinkSpan
            baseStyle={ctx.baseStyle}
            inline={inline}
            key={spanKey(`session-link:${index}:${inline.url}`)}
            onOpenSessionLink={ctx.onOpenSessionLink}
            session={session}
            sessionLinkTitles={ctx.sessionLinkTitles}
            SpanText={SpanText}
            styles={styles}
          />
        );
      }
      // 非 session 的 Cindy 深链(project 等,双 scheme:cindy 主 + xdt-maker
      // 兼容存量;桌面端粘贴 chip 化后按 `[标题](深链)` / 裸链接发送):手机端
      // 没有对应跳转目标,渲染 label 纯文本;绝不落 Linking.openURL(这些
      // scheme 未注册到手机 OS,openURL 必失败,还会在部分 Android 上弹系统
      // 报错)。裸项目链接(text === url,侧边栏复制的无标题形态)推导目录名
      // 展示,不给用户看 percent-encoded 原串(review P2)。
      if (isCindyDeepLinkUrl(inline.url)) {
        const explicitLabel =
          inline.text.trim() && inline.text.trim() !== inline.url ? inline.text.trim() : null;
        const projectTarget = explicitLabel ? null : parseProjectDeepLinkUrl(inline.url);
        const display =
          explicitLabel
          ?? (projectTarget ? projectDisplayName(projectTarget.workingDir) : inline.url);
        return (
          <SpanText key={spanKey(`xdt-link:${index}:${inline.url}`)} style={ctx.baseStyle}>
            {display}
          </SpanText>
        );
      }
      // 本地路径链接([README.md](/abs/README.md:17)):走文件 chip 链路——
      // 存在则点亮进预览/文件浏览器,不存在/未验证只显示 label 纯文本,
      // 绝不落 Linking.openURL(本地路径交给系统必失败)。此处 classify 只做
      // 分支判定(廉价纯函数),对象引用不下传;组件内按 url 重新 memo 一份。
      if (classifyChatPathLinkTarget(inline.url)) {
        return (
          <LinkPathChipSpan
            key={spanKey(`path-link:${index}:${inline.url}`)}
            bare={inline.bare}
            baseStyle={ctx.baseStyle}
            display={inline.text}
            SpanText={SpanText}
            streaming={ctx.streaming}
            styles={styles}
            url={inline.url}
          />
        );
      }
      // onPress 与下划线取同一个值,不可能一边有一边没有。
      const openExternalUrl = () => {
        void Linking.openURL(inline.url).catch(() => undefined);
      };
      return (
        <MailLinkSpan
          key={spanKey(`link:${index}:${inline.url}`)}
          url={inline.url}
          SpanText={SpanText}
          style={clickableInlineStyle(styles, openExternalUrl, ctx.baseStyle)}
        >
          {inline.text}
        </MailLinkSpan>
      );
    }
    case 'strong':
      return <SpanText key={spanKey(`strong:${index}`)} style={[ctx.baseStyle, styles.markdownStrong]}>{inline.text}</SpanText>;
    case 'emphasis':
      return <SpanText key={spanKey(`em:${index}`)} style={[ctx.baseStyle, styles.markdownEmphasis]}>{inline.text}</SpanText>;
    case 'code':
      return (
        <InlineCodePathSpan
          key={spanKey(`code:${index}`)}
          baseStyle={ctx.baseStyle}
          SpanText={SpanText}
          streaming={ctx.streaming}
          styles={styles}
          text={inline.text}
        />
      );
    case 'strikethrough':
      return <SpanText key={spanKey(`strike:${index}`)} style={[ctx.baseStyle, styles.markdownStrike]}>{inline.text}</SpanText>;
    case 'math':
      // inline 公式:原生 Text 流内嵌不了 KaTeX,用 Unicode 近似(上标 ²、
      // 希腊字母、√ 等)保持文本流/选择/性能;复杂公式的精确渲染走 display
      // 块的 WebView KaTeX。
      return (
        <SpanText key={spanKey(`math:${index}`)} style={[ctx.baseStyle, styles.markdownMathInline]}>
          {latexToUnicodeApproximation(inline.text)}
        </SpanText>
      );
    case 'image': {
      const managedPreview = ctx.renderManagedImage?.(inline);
      if (managedPreview) {
        return <Text key={spanKey(`image:${index}:${inline.url}`)} testID="message.markdownManagedImage">{managedPreview}</Text>;
      }
      // openImage 由上层可选注入 → 缺席时 chip 不可点,下划线也必须跟着不加
      // (clickableInlineStyle 保证两者同源)。
      const openImageChip = openImage ? () => openImage(inline.url, inline.alt) : undefined;
      // 缺少路径上下文时保留文字入口;合法受管图由上面的 MediaPreview 取件。
      if (!isMobileMarkdownImageDirectUrl(inline.url)) {
        const imageChipText = inline.alt
          ? mobileMarkdownImageAltChipText(inline.alt)
          : i18n.t('message.renderer.imageFallbackTitle');
        return (
          <SpanText
            key={spanKey(`image:${index}:${inline.url}`)}
            onPress={openImageChip}
            style={clickableInlineStyle(styles, openImageChip, ctx.baseStyle)}
            testID="message.markdownInlineImageChip"
          >
            {imageChipText}
          </SpanText>
        );
      }
      // 直连图统一按缩略图形态渲染(无法预知原图比例,cover 裁切 + 封顶尺寸),流式与完成态同一条路径;点按走全屏查看原图。
      // Android 不支持 <Text> 直接内嵌 <Image>(不渲染/行为未定义),用「Text 内嵌显式尺寸 View 包 Image」
      // 的形态承载(RN 对 Text 内嵌 View 双端支持,要求显式尺寸;规则 15,Android 真机待验证)。
      const size = mobileMarkdownInlineImageSize(inline);
      return (
        <Text
          key={`image:${index}:${inline.url}`}
          onPress={openImage ? () => openImage(inline.url, inline.alt) : undefined}
          testID="message.markdownInlineImage"
        >
          <View style={size}>
            <MessageLoadingImage
              accessibilityLabel={inline.alt || i18n.t('message.renderer.imageFallbackTitle')}
              contentFit="cover"
              recyclingKey={inline.url}
              source={{ uri: inline.url }}
              style={[styles.markdownInlineImage, size]}
            />
          </View>
        </Text>
      );
    }
  }
}

function MarkdownSessionLinkSpan({
  baseStyle,
  inline,
  onOpenSessionLink,
  session,
  sessionLinkTitles,
  SpanText,
  styles,
}: {
  baseStyle?: StyleProp<TextStyle>;
  inline: Extract<MobileMarkdownInline, { type: 'link' }>;
  onOpenSessionLink?: (url: string) => void;
  session: SessionDeepLinkTarget;
  sessionLinkTitles?: Readonly<Record<string, string>>;
  SpanText: typeof Text;
  styles: ReturnType<typeof makeStyles>;
}) {
  const messages = useRemoteSessionMessages(session.sessionId);
  const explicit =
    inline.text.trim() && inline.text.trim() !== inline.url ? inline.text.trim() : null;
  const targetMessage = session.messageClientId
    ? messages.find((message) => (
        message.clientId === session.messageClientId || message.id === session.messageClientId
      ))
    : null;
  // 消息数组更新(流式 / 列表重渲)时,目标消息没变就不重算摘要。
  const messageLabel = useMemo(() => {
    const messageText = targetMessage ? mobileSessionMessageDisplayText(targetMessage) : null;
    return messageText ? sentSessionMessageChipLabel(messageText) : '';
  }, [targetMessage]);
  const title = session.messageClientId
    ? messageLabel || i18n.t('message.renderer.messageChipFallback')
    : explicit
      ?? sessionLinkTitles?.[session.sessionId]
      ?? i18n.t('message.renderer.sessionChipFallback');
  // handler 由上层可选注入 → 缺席时 chip 不可点,下划线也必须跟着不加
  // (clickableInlineStyle 保证两者同源)。
  const openSessionLink = onOpenSessionLink ? () => onOpenSessionLink(inline.url) : undefined;
  // 发给模型的上下文范围(条数 / 是否截断)不在气泡里展示:用户无从理解也无从操作。
  return (
    <SpanText
      onPress={openSessionLink}
      style={clickableInlineStyle(styles, openSessionLink, baseStyle, styles.sessionLinkChipText)}
    >
      {`${session.messageClientId ? '❝' : '↳'} ${title}`}
    </SpanText>
  );
}

/** The caller selects this once for the strip's lifetime: recycled rows use list state,
 * while ordinary ScrollView children use React state. Keep the choice fixed while mounted. */
type MediaPreviewStateHook = <T>(initial: T | (() => T)) => readonly [T, Dispatch<SetStateAction<T>>];

/** 用户消息的附件条(图片缩略图 + 文件 chip);群聊时间线复用同一实现。 */
export function AttachmentStrip({
  attachments,
  messageKey,
  clientId,
  getImagePreview,
  align,
  layout,
  onOpen,
  onOpenFile,
  onImageError,
  imageReloadKeys,
  onResolveRemoteMedia,
  usePreviewState = useRecyclingState,
}: {
  attachments: readonly NormalizedAttachment[];
  messageKey: string;
  clientId?: string;
  getImagePreview?: GetSentMessageImagePreview;
  align: 'left' | 'right';
  layout: MessageContentLayout;
  onOpen?: (payload: MessagePayload) => void;
  /** Index within this strip's file chips, for callers that resolve files by ID on tap. */
  onOpenFile?: (index: number) => void;
  /** Index within this strip's images, for owners that refresh short-lived authorization. */
  onImageError?: (index: number) => void;
  /** Reset only the failed image when authorization returns the same URL. */
  imageReloadKeys?: readonly number[];
  onResolveRemoteMedia?: ResolveRemoteMediaFn;
  usePreviewState?: MediaPreviewStateHook;
}) {
  const styles = useThemedStyles(makeStyles);
  // 订阅本地缩略兜底版本:hydrate / 新注册落盘后,已渲染的 cindy-oss-attach:// 气泡
  // 自动从占位卡切到本地图(返回值不消费,订阅本身驱动重渲染)。
  useSentAttachmentThumbsVersion();
  const fileContext = useContext(ChatFilePathContext);
  const { imageAttachments, fileAttachments } = partitionMessageAttachments(attachments.map((attachment) =>
    svgAttachmentForDisplay(attachment, fileContext?.workdir, messageKey, fileContext?.remoteHostId, fileContext?.sessionId),
  ));
  const alignStyle = align === 'right' ? styles.attachmentStripRight : styles.attachmentStripLeft;

  return (
    <View style={[styles.attachmentStrip, alignStyle, { gap: layout.attachmentGap }]}>
      {/* 图片附件对齐桌面版:逐张竖排(不换行拼贴),各自按原始宽高比 contain。
          overlay:本机上传的图在被控端物化改写前 url 仍是 cindy-oss-attach://,本地
          兜底命中时替换成 file:// 直接渲染(payload 同源替换,点开查看器同图)。 */}
      {imageAttachments.map((item, index) => (
        <MediaPreview
          key={`${item.kind}:${item.uri ?? item.name}:${index}:${imageReloadKeys?.[index] ?? 0}`}
          label={item.name}
          layout={layout}
          media={{ kind: 'image', url: item.uri ?? '', previewable: item.previewable }}
          localPreview={clientId ? getImagePreview?.(clientId, index, item.name, undefined, item.sha256, item.uri) : undefined}
          onOpen={onOpen ? () => onOpen(buildAttachmentPayload(applySentAttachmentThumbOverlay(item))) : undefined}
          onResolveRemoteMedia={onResolveRemoteMedia}
          onImageError={onImageError ? () => onImageError(index) : undefined}
          variant="attachment"
          usePreviewState={usePreviewState}
        />
      ))}
      {fileAttachments.length > 0 ? (
        <View style={[
          styles.attachmentFileColumn,
          {
            gap: layout.attachmentGap,
            maxWidth: layout.fileChipMaxWidth,
          },
          align === 'right' && styles.attachmentFileColumnRight,
        ]}>
          {fileAttachments.map((item, index) => (
            <FileChip
              key={`${item.kind}:${item.path ?? item.name}:${index}`}
              layout={layout}
              name={item.name}
              onOpen={onOpenFile ? () => onOpenFile(index) : onOpen ? () => onOpen(buildAttachmentPayload(item)) : undefined}
              path={item.path}
            />
          ))}
        </View>
      ) : null}
    </View>
  );
}

/**
 * ToolMediaBlock — tool 产出媒体的独立视觉消息(对齐桌面 'tool_media' RenderItem):
 * agent 出的图 / 视频(lizi_art、飞书拉图等)跳出 tool_group 折叠卡,紧跟其后作为
 * 独立块渲染,用户不展开工具行也能一眼看到。图片走 attachment 变体(原始宽高比
 * contain 进 max 框,xdt-image:// 经取件队列懒取缩略图);video/audio 保持占位
 * 卡片、点开查看器播放。媒体按 url 去重(与 shared 发射判定同一口径)。
 */
function ToolMediaBlock({
  item,
  actions,
}: {
  item: MobileToolMediaItem;
  actions: MessageActions & { firstUserMessageClientId?: string };
}) {
  const styles = useThemedStyles(makeStyles);
  const contentLayout = useMemo(() => buildMessageContentLayout({
    screenWidth: actions.screenWidth,
  }), [actions.screenWidth]);
  const media = useMemo(
    () => dedupeToolMediaByUrl(item.tools.flatMap((tool) => tool.media ?? [])),
    [item.tools],
  );
  const openPayload = actions.onOpenPayload;
  const files = [...new Map(item.tools.flatMap((tool) => tool.files ?? []).map((file) => [file.url, file])).values()];
  const cards = [...new Map(item.tools.flatMap((tool) => (tool.cardIds ?? []).map((callId) => ({ callId, sessionId: tool.source.sessionId }))).map((card) => [card.callId, card])).values()];
  if (media.length === 0 && files.length === 0 && cards.length === 0) return null;
  return (
    <View
      style={[styles.toolMediaBlock, { gap: contentLayout.attachmentGap }]}
      testID="message.toolMediaBlock"
    >
      {cards.map((card) => <PluginResultCard key={card.callId} {...card} actions={actions}
        excludedUrls={[...item.tools.flatMap((tool) => extractPayloadToolResultMedia(tool.secondaryBody ?? '').map((entry) => entry.url)), ...files.map((file) => file.url)]} />)}
      {files.map((file) => <FileChip key={file.url} name={file.title} path={file.url} layout={contentLayout}
        onOpen={openPayload ? () => openPayload(buildFilePayload(file.title, file.url)) : undefined} />)}
      {media.map((entry, index) => (
        <MediaPreview
          key={`${entry.kind}:${entry.url}:${index}`}
          label={entry.title || mediaLabel(entry)}
          layout={contentLayout}
          media={entry}
          onOpen={openPayload
            ? () => openPayload(buildMediaPayload(entry, entry.title || mediaLabel(entry)))
            : undefined}
          onResolveRemoteMedia={actions.onResolveRemoteMedia}
          variant={entry.kind === 'image' ? 'attachment' : 'card'}
        />
      ))}
    </View>
  );
}

/** Read-only fallback for desktop plugin cards. Reuse native text/media/file
 * components rather than executing plugin HTML or pretending its buttons work. */
function PluginResultCard({ callId, sessionId, excludedUrls, actions }: {
  callId: string; sessionId: string; excludedUrls: string[]; actions: MessageActions;
}) {
  const { blocks, error, retry, hidden } = usePluginResultCard(actions.remoteDeviceId, sessionId, callId);
  const layout = buildMessageContentLayout({ screenWidth: actions.screenWidth });
  const styles = useThemedStyles(makeStyles);
  const { t } = useTranslation();
  if (hidden) return null;
  return <View style={styles.toolMediaBlock} testID="message.pluginResultCard">
    {blocks?.map((block) => {
      if (block.primitive === 'plugin-card-actions') return <PluginCardActions key={block.id} data={block.data} deviceId={actions.remoteDeviceId} sessionId={sessionId} callId={callId}
        onOpenAttachment={actions.onOpenPayload ? (url, name) => actions.onOpenPayload!(buildMediaPayload({ kind: 'image', url, previewable: true }, name)) : undefined} />;
      const url = (block.data as { url?: unknown } | undefined)?.url;
      const kind = managedToolMediaKind(url);
      if (typeof url === 'string' && excludedUrls.includes(url)) return null;
      if (kind && typeof url === 'string') {
        const media = { kind, url, previewable: false };
        return <MediaPreview key={block.id} label={mediaLabel(media)} layout={layout} media={media}
          onOpen={actions.onOpenPayload ? () => actions.onOpenPayload!(buildMediaPayload(media, mediaLabel(media))) : undefined}
          onResolveRemoteMedia={actions.onResolveRemoteMedia} variant={kind === 'image' ? 'attachment' : 'card'} />;
      }
      if (block.primitive === 'file' && typeof url === 'string' && /^cindy-media:\/\/blobs\/[0-9a-f]{64}\.glb$/.test(url)) {
        const name = url.split('/').pop()!;
        return <FileChip key={block.id} name={name} path={url} layout={layout}
          onOpen={actions.onOpenPayload ? () => actions.onOpenPayload!(buildFilePayload(name, url)) : undefined} />;
      }
      return <MarkdownBody key={block.id} text={block.fallbackMarkdown} layout={layout} streaming={false} selectable
        onOpenPayload={actions.onOpenPayload} onOpenSessionLink={actions.onOpenSessionLink} />;
    })}
    {!blocks && !error ? <Text style={styles.detailText}>{t('message.renderer.loading')}</Text> : null}
    {error ? <MessageContentOpenButton onPress={retry} accessibilityLabel={t('message.renderer.retryPreview')}>
      <Text style={styles.detailText}>{t('message.renderer.retryPreview')}</Text>
    </MessageContentOpenButton> : null}
  </View>;
}

/**
 * 附件图原图尺寸的模块级缓存(键 = 源 media.url,跨 presign 刷新稳定)。
 * FlatList 虚拟化反复 unmount/remount MediaPreview,组件态存不住尺寸;
 * 上限兜底防长会话无界增长(整表清空即可,下次解码时重新记录)。
 */
const attachmentIntrinsicSizeCache = new Map<string, AttachmentImageIntrinsicSize>();
const ATTACHMENT_INTRINSIC_CACHE_MAX = 500;

// 相册候选仍可能是 ph://,必须由 expo-image 加载;只复用正式附件的布局,
// 不把本地相册地址声明为 RN Image / 远端查看器可直接预览的媒体。
function PendingAttachmentImage({ layout, uri, sourceUri = uri, onError, onSize, usePreviewState = useRecyclingState }: {
  layout: MessageContentLayout; uri: string; sourceUri?: string; onError?: () => void;
  onSize?: (size: AttachmentImageIntrinsicSize) => void;
  usePreviewState?: MediaPreviewStateHook;
}) {
  const styles = useThemedStyles(makeStyles);
  const [intrinsicSize, setIntrinsicSize] = usePreviewState<AttachmentImageIntrinsicSize | null>(
    () => attachmentIntrinsicSizeCache.get(sourceUri) ?? attachmentIntrinsicSizeCache.get(uri) ?? null,
  );
  // The upload copy and materialized reference describe the same pixels. Carry their measured frame.
  useLayoutEffect(() => {
    if (!intrinsicSize) return;
    if (attachmentIntrinsicSizeCache.size >= ATTACHMENT_INTRINSIC_CACHE_MAX) attachmentIntrinsicSizeCache.clear();
    attachmentIntrinsicSizeCache.set(sourceUri, intrinsicSize);
    attachmentIntrinsicSizeCache.set(uri, intrinsicSize);
  }, [intrinsicSize, sourceUri, uri]);
  const displaySize = attachmentImageDisplaySize(
    intrinsicSize, layout.attachmentImageMaxWidth, layout.attachmentImageMaxHeight,
  );
  return (
    <View style={styles.attachmentImageWrap}>
      <MessageLoadingImage
        source={{ uri }}
        recyclingKey={uri}
        contentFit="contain"
        onError={onError}
        onLoad={({ source: { width, height } }) => {
          if (!(width > 0 && height > 0)) return;
          if (attachmentIntrinsicSizeCache.size >= ATTACHMENT_INTRINSIC_CACHE_MAX) {
            attachmentIntrinsicSizeCache.clear();
          }
          attachmentIntrinsicSizeCache.set(uri, { width, height });
          attachmentIntrinsicSizeCache.set(sourceUri, { width, height });
          setIntrinsicSize({ width, height });
          onSize?.({ width, height });
        }}
        style={[styles.attachmentImage, displaySize]}
      />
    </View>
  );
}

/**
 * MediaPreview — 聊天列表里的媒体缩略图 / 占位卡片。
 * 图片:可直接预览的(http/data:)直接渲染缩略图;桌面端媒体(xdt-image://)mount 时
 * 经取件队列懒取件后渲染缩略图(取件中为同尺寸静默占位帧,失败回落占位卡片文案但
 * 保持同尺寸帧避免列表 reflow)。点击一律走 onOpen 打开 payload 查看器看原图。
 * video/audio 与非桌面端不可预览图片保持占位卡片现状。
 *
 * variant(对齐桌面版 ChatImageView 的两档):
 *   - 'card'      :工具产出媒体,固定小帧 cover 裁切;
 *   - 'attachment':用户消息图片附件,按原始宽高比 contain 进 max 框(桌面
 *     user-attached 同款 280×180 语义),圆角、无边框、无文件名。
 */
function MediaPreview({
  layout,
  media,
  label,
  onOpen,
  onResolveRemoteMedia,
  onImageError,
  variant = 'card',
  presentationOnly = false,
  localPreview,
  usePreviewState = useRecyclingState,
}: {
  layout: MessageContentLayout;
  media: NormalizedToolMedia;
  label: string;
  onOpen?: () => void;
  onResolveRemoteMedia?: ResolveRemoteMediaFn;
  onImageError?: () => void;
  variant?: 'card' | 'attachment';
  presentationOnly?: boolean;
  localPreview?: SentMessageImagePreview;
  usePreviewState?: MediaPreviewStateHook;
}) {
  const styles = useThemedStyles(makeStyles);
  const preview = summarizeMessagePayloadPreview(buildMediaPayload(media, label));
  const durableUri = media.kind === 'image' && variant === 'attachment'
    ? getSentAttachmentThumbUri(localPreview?.sourceRef ?? media.url)
    : null;
  const localCandidate = localPreview?.uri ?? durableUri;
  const [failedLocalUris, setFailedLocalUris] = usePreviewState<readonly string[]>([]);
  // Keep the sent source when a durable copy appears later; switch only after an actual load error.
  const localUri = [localCandidate, durableUri].find((uri) => uri && !failedLocalUris.includes(uri)) ?? null;
  const autoResolve = !localUri && shouldAutoResolveMediaThumbnail(media, !!onResolveRemoteMedia);
  const [resolveState, setResolveState] = usePreviewState<MediaThumbnailResolveState>({ status: 'idle' });
  // attachment 变体的原图尺寸。初值走模块级缓存:FlatList 虚拟化会反复
  // unmount/remount 本组件,不缓存的话每次划回都重新 getSize、重演一次
  // 占位帧 → 真图尺寸的切换(规则 7 的跳变)。
  const [intrinsicSize, setIntrinsicSize] = usePreviewState<AttachmentImageIntrinsicSize | null>(
    () => attachmentIntrinsicSizeCache.get(localPreview?.uri ?? media.url)
      ?? attachmentIntrinsicSizeCache.get(localCandidate ?? media.url) ?? null,
  );
  // Image 加载失败(典型:presign 过期)只强制重取一次,防 onError↔重取死循环。
  const imageRetryUsedRef = useRef(false);

  const resolveThumbnail = useCallback((forceRefresh: boolean, signal?: AbortSignal) => {
    if (!onResolveRemoteMedia) return;
    let cancelled = false;
    setResolveState({ status: 'loading' });
    void onResolveRemoteMedia(
      // thumbnail:列表缩略图只要被控端缩好的小图(1024px webp inline 回包),
      // 不为一个气泡预览拉整张原图;点开查看器仍按原图键另行取件(可缩放)。
      { kind: media.kind, url: media.url, previewable: media.previewable, thumbnail: media.kind === 'image' },
      { signal, forceRefresh },
    )
      .then((resolved) => {
        if (!cancelled && !signal?.aborted) setResolveState({ status: 'ready', media: resolved });
      })
      .catch((error: unknown) => {
        if (!cancelled && !signal?.aborted) setResolveState({ status: 'error', error });
      });
    return () => {
      cancelled = true;
    };
  }, [media.kind, media.previewable, media.url, onResolveRemoteMedia]);

  useEffect(() => {
    if (!autoResolve) return;
    imageRetryUsedRef.current = false;
    const controller = new AbortController();
    const cancel = resolveThumbnail(false, controller.signal);
    return () => {
      cancel?.();
      controller.abort();
    };
  }, [autoResolve, resolveThumbnail]);

  const phase = mediaThumbnailPhase(media, resolveState, !!onResolveRemoteMedia);
  const { t } = useTranslation();
  const fallbackDetail = phase.kind === 'fallback' && phase.reason === 'error'
    ? t(mediaLoadFailureKey(resolveState.status === 'error' ? resolveState.error : undefined)) : preview.detail;
  const thumbUri = phase.kind === 'direct' ? media.url : phase.kind === 'resolved' ? phase.uri : null;

  const handleImageError = useCallback(() => {
    if (media.previewable) {
      setResolveState({ status: 'error' });
      onImageError?.();
      return;
    }
    if (imageRetryUsedRef.current) {
      setResolveState({ status: 'error' });
      return;
    }
    imageRetryUsedRef.current = true;
    resolveThumbnail(true);
  }, [media.previewable, onImageError, resolveThumbnail]);

  // Measure with the same decoder that displays the image: RN getSize cannot
  // decode SVG. Reuse the decoded dimensions without a second image request.
  const handleImageLoad = useCallback(({ source: { width, height } }: { source: AttachmentImageIntrinsicSize }) => {
    if (!(width > 0 && height > 0)) return;
    if (attachmentIntrinsicSizeCache.size >= ATTACHMENT_INTRINSIC_CACHE_MAX) {
      attachmentIntrinsicSizeCache.clear();
    }
    attachmentIntrinsicSizeCache.set(media.url, { width, height });
    setIntrinsicSize({ width, height });
  }, [media.url, setIntrinsicSize]);

  if (localUri) {
    return (
      <MessageContentOpenButton presentationOnly={presentationOnly}
        accessibilityLabel={`${preview.actionLabel} ${preview.title}`} onPress={onOpen}
        style={styles.attachmentImageWrap} testID="message.mediaPreviewButton">
        <PendingAttachmentImage key={localPreview?.uri ?? localUri} layout={layout}
          uri={localUri} sourceUri={localPreview?.uri ?? localUri}
          usePreviewState={usePreviewState}
          onSize={setIntrinsicSize}
          onError={() => setFailedLocalUris((failed) => failed.includes(localUri) ? failed : [...failed, localUri])} />
      </MessageContentOpenButton>
    );
  }

  if (variant === 'attachment' && media.kind === 'image') {
    const displaySize = attachmentImageDisplaySize(
      intrinsicSize,
      layout.attachmentImageMaxWidth,
      layout.attachmentImageMaxHeight,
    );
    return (
      <MessageContentOpenButton
      presentationOnly={presentationOnly}
        accessibilityLabel={`${preview.actionLabel} ${preview.title}`}
        onPress={onOpen}
        style={styles.attachmentImageWrap}
        testID="message.mediaPreviewButton"
      >
        {phase.kind === 'fallback' ? (
          // 取件失败保持附件帧尺寸(不回落小卡片帧造成 reflow);点开查看器可重试。
          <View
            style={[styles.attachmentImagePending, styles.attachmentImageFallback, displaySize]}
            testID="message.mediaThumbFallback"
          >
            <Text style={styles.mediaKind}>{preview.meta[0] ?? payloadMediaKindLabel(media.kind)}</Text>
            <Text style={styles.mediaHint} numberOfLines={2}>{fallbackDetail}</Text>
          </View>
        ) : thumbUri ? (
          <MessageLoadingImage
            // 尺寸未知时先 contain 进最大框,解码后收敛到真实比例。
            contentFit="contain"
            recyclingKey={thumbUri}
            source={{ uri: thumbUri }}
            onLoad={handleImageLoad}
            onError={handleImageError}
            style={[styles.attachmentImage, displaySize]}
          />
        ) : (
          <MessageImagePlaceholder style={displaySize} />
        )}
      </MessageContentOpenButton>
    );
  }

  if (phase.kind === 'direct' || phase.kind === 'resolving' || phase.kind === 'resolved'
    || (phase.kind === 'fallback' && (phase.reason === 'error' || phase.reason === 'unsupported-mime'))) {
    const uri = thumbUri;
    const frameSize = { height: layout.imagePreviewHeight, width: layout.imagePreviewWidth };
    return (
      <MessageContentOpenButton
      presentationOnly={presentationOnly}
        accessibilityLabel={`${preview.actionLabel} ${preview.title}`}
        onPress={onOpen}
        style={[
          styles.imagePreviewWrap,
          { width: layout.imagePreviewWidth },
        ]}
        testID="message.mediaPreviewButton"
      >
        {uri ? (
          <MessageLoadingImage
            contentFit="cover"
            recyclingKey={uri}
            source={{ uri }}
            onError={handleImageError}
            style={[styles.imagePreview, frameSize]}
          />
        ) : phase.kind === 'resolving' ? (
          <MessageImagePlaceholder style={[styles.imagePreview, frameSize]} />
        ) : (
          <View
            style={[styles.imagePreview, styles.imagePreviewFallback, frameSize]}
            testID="message.mediaThumbFallback"
          >
            <Text style={styles.mediaKind}>{preview.meta[0] ?? payloadMediaKindLabel(media.kind)}</Text>
            <Text style={styles.mediaHint} numberOfLines={2}>{fallbackDetail}</Text>
          </View>
        )}
      </MessageContentOpenButton>
    );
  }

  return (
    <MessageContentOpenButton
      presentationOnly={presentationOnly}
      accessibilityLabel={`${preview.actionLabel} ${preview.title}`}
      onPress={onOpen}
      style={[
        styles.mediaPlaceholder,
        {
          minHeight: layout.mediaPlaceholderMinHeight,
          width: layout.mediaPreviewWidth,
        },
      ]}
      testID="message.mediaPreviewButton"
    >
      <Text style={styles.mediaKind}>{preview.meta[0] ?? payloadMediaKindLabel(media.kind)}</Text>
      <Text style={styles.mediaTitle} numberOfLines={1}>{preview.title}</Text>
      <Text style={styles.mediaHint} numberOfLines={2}>
        {preview.detail}
      </Text>
    </MessageContentOpenButton>
  );
}

const FILE_CHIP_TEST_IDS = {
  default: 'message.filePreviewButton',
  pdf: 'message.filePreviewButton.pdf',
  drawio: 'message.filePreviewButton.drawio',
} as const;

const FILE_FALLBACK_STATUS_TEST_IDS = {
  pdf: 'message.fileFallbackStatus.pdf',
  drawio: 'message.fileFallbackStatus.drawio',
  other: 'message.fileFallbackStatus.other',
} as const;

function fileChipTestId(pathOrName: string): string {
  const kind = remoteFilePreviewKind(pathOrName);
  if (kind === 'pdf') return FILE_CHIP_TEST_IDS.pdf;
  if (kind === 'drawio') return FILE_CHIP_TEST_IDS.drawio;
  return FILE_CHIP_TEST_IDS.default;
}

function filePreviewStatusTestId(kind: ReturnType<typeof remoteFilePreviewKind>): string {
  if (kind === 'pdf') return FILE_FALLBACK_STATUS_TEST_IDS.pdf;
  if (kind === 'drawio') return FILE_FALLBACK_STATUS_TEST_IDS.drawio;
  if (kind !== 'text') return FILE_FALLBACK_STATUS_TEST_IDS.other;
  return 'message.filePreviewStatus';
}

function FileChip({
  layout,
  name,
  onOpen,
  path,
  presentationOnly = false,
}: {
  layout: MessageContentLayout;
  name: string;
  onOpen?: () => void;
  path?: string;
  presentationOnly?: boolean;
}) {
  const { colors } = useTheme();
  const styles = useThemedStyles(makeStyles);
  const preview = summarizeMessagePayloadPreview(buildFilePayload(name, path ?? ''));
  return (
    <MessageContentOpenButton
      presentationOnly={presentationOnly}
      accessibilityLabel={`${preview.actionLabel} ${name}`}
      onPress={onOpen}
      style={[
        styles.fileChip,
        {
          maxWidth: layout.fileChipMaxWidth,
          minHeight: layout.fileChipMinHeight,
        },
      ]}
      testID={fileChipTestId(path ?? name)}
    >
      <View style={[styles.fileIconFrame, { width: layout.fileChipIconWidth }]}>
        <FileTypeIcon name={name || path} color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
      </View>
      <View style={styles.fileText}>
        <Text style={styles.fileName} numberOfLines={1}>{preview.title}</Text>
      </View>
    </MessageContentOpenButton>
  );
}

function DiffPreview({
  diff,
  layout,
  onOpen,
}: {
  diff: NormalizedToolDiff;
  layout: MessageContentLayout;
  onOpen?: (payload: MessagePayload) => void;
}) {
  const styles = useThemedStyles(makeStyles);
  const { t } = useTranslation();
  const first = diff.segments[0];
  const payload = buildDiffPayload(diff);
  const preview = summarizeMessagePayloadPreview(payload);
  return (
    <MessageContentOpenButton
      accessibilityLabel={`${preview.actionLabel} ${preview.title}`}
      onPress={onOpen ? () => onOpen(payload) : undefined}
      style={[
        styles.diffCard,
        {
          gap: layout.diffCardGap,
          padding: layout.diffCardPadding,
        },
      ]}
      testID="message.diffPreviewButton"
    >
      <Text style={styles.diffPath} numberOfLines={1}>{preview.title}</Text>
      <Text style={styles.diffStats}>{preview.meta.join(' · ')}</Text>
      {first ? (
        <View style={styles.diffRows}>
          {first.oldString ? (
            <Text style={[styles.diffLine, styles.diffDelete]} numberOfLines={2}>
              - {first.oldString}
            </Text>
          ) : null}
          {first.newString ? (
            <Text style={[styles.diffLine, styles.diffAdd]} numberOfLines={2}>
              + {first.newString}
            </Text>
          ) : null}
        </View>
      ) : null}
      {diff.segments.length > 1 ? (
        <Text style={styles.diffMore}>{t('message.renderer.diffEditCount', { n: diff.segments.length })}</Text>
      ) : null}
    </MessageContentOpenButton>
  );
}

const TOOL_RESULT_PREVIEW_MAX_CHARS = 520;

function ToolResultPreview({
  layout,
  tool,
  onOpen,
  onRetryImageDelivery,
}: {
  layout: MessageContentLayout;
  tool: NormalizedRemoteMessage;
  onOpen?: (payload: MessagePayload) => void;
  onRetryImageDelivery?: (imageId: string) => Promise<void>;
}) {
  const styles = useThemedStyles(makeStyles);
  const imageId = readFailedImageDelivery(tool.secondaryBody);
  if (imageId) return <GeneratedImageRetry imageId={imageId} onRetry={onRetryImageDelivery} />;
  const payload = buildToolResultPayload({ ...tool, secondaryBody: readToolProcessText(tool.secondaryBody) });
  if (!payload) return null;
  const preview = summarizeMessagePayloadPreview(payload, { maxPreviewChars: TOOL_RESULT_PREVIEW_MAX_CHARS });
  // 「查看内容」hint 只在纯文本结果确实被截断(字符上限或行数上限)时显示——预览已
  // 完整呈现的短结果不需要这行提示(整个框仍可点开全屏)。非 text 类 payload(媒体/
  // diff 等)的 actionLabel 是打开方式说明,保持常显。长单行折行导致的视觉截断检测
  // 不到,漏显 hint 危害低(框可点),不为它引入逐行测量。
  const clipped = payload.body.trim().length > TOOL_RESULT_PREVIEW_MAX_CHARS
    || preview.previewText.split('\n').length > layout.toolResultMaxLines;
  const showHint = payload.kind !== 'text' || clipped;
  return (
    <MessageContentOpenButton
      accessibilityLabel={`${preview.actionLabel} ${preview.title}`}
      onPress={onOpen ? () => onOpen(payload) : undefined}
      style={styles.toolResultPreview}
      testID="message.toolPayloadButton"
    >
      <Text style={styles.toolResult} numberOfLines={layout.toolResultMaxLines}>{preview.previewText}</Text>
      {showHint ? <Text style={styles.toolResultHint}>{preview.actionLabel}</Text> : null}
    </MessageContentOpenButton>
  );
}

function MessageContentOpenButton({
  accessibilityLabel,
  children,
  disabled = false,
  presentationOnly = false,
  onPress,
  style,
  testID,
}: {
  accessibilityLabel: string;
  children: ReactNode;
  disabled?: boolean;
  presentationOnly?: boolean;
  onPress?: () => void;
  style?: StyleProp<ViewStyle>;
  testID?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const interactionDisabled = disabled || !onPress;
  if (presentationOnly) return <View style={style} testID={testID}>{children}</View>;
  return (
    <Pressable
      accessibilityLabel={accessibilityLabel}
      accessibilityRole="button"
      accessibilityState={{ disabled: interactionDisabled }}
      disabled={interactionDisabled}
      onPress={interactionDisabled ? undefined : onPress}
      style={({ pressed }) => [
        style,
        pressed && styles.pressed,
        interactionDisabled && styles.disabled,
      ]}
      testID={testID}
    >
      {children}
    </Pressable>
  );
}

function MessagePayloadModal({
  payload,
  imageAnnotation,
  onClose,
  onReadTextFilePreview,
  onReleaseRemoteMedia,
  onResolveRemoteMedia,
  onShareImage,
}: {
  payload: MessagePayload | null;
  /** 图表导出图的标注配置(来自聊天 lightbox 的同一份 chatAnnotation)。 */
  imageAnnotation?: ImageLightboxAnnotationConfig;
  onClose(): void;
  onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
  onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;
  onResolveRemoteMedia?: ResolveRemoteMediaFn;
  onShareImage?: ComponentProps<typeof ImageLightbox>['onShareImage'];
}) {
  const { colors } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const [payloadCopyState, setPayloadCopyState] = useState<PayloadHeaderCopyState>('idle');
  const payloadCopySeqRef = useRef(0);
  // 沉浸式图表查看器的导出:WebView 内光栅化 → 临时 PNG → 系统分享单
  // (含「存储图像 / 拷贝」,与图片消息同款路径)。
  const [mermaidExporting, setMermaidExporting] = useState(false);
  const mermaidViewRef = useRef<MermaidDiagramWebViewHandle | null>(null);
  // 图表标注:导出图的 lightbox 渲染在**本 Modal 的 children 里**——RN Modal 从
  // 所在组件树的 VC present,挂在外层(session 屏)树里会因该 VC 已 present 本
  // Modal 而挂起排队,表现为「点了没反应,关图表后标注才弹出」。嵌进来后 inner
  // Modal 从本 Modal 的 VC present,真正叠在图表之上;取消回图表,提交两层全关。
  const [annotatePayload, setAnnotatePayload] = useState<Extract<MessagePayload, { kind: 'media' }> | null>(null);
  const closeAnnotatePayload = useCallback(() => setAnnotatePayload(null), []);
  const annotateImages = useMemo(
    () => annotatePayload ? lightboxImagesForPayload([], annotatePayload) : null,
    [annotatePayload],
  );
  const annotateLightboxAnnotation = useMemo<ImageLightboxAnnotationConfig | undefined>(() => {
    if (!imageAnnotation) return undefined;
    return {
      ...imageAnnotation,
      onSubmit: async (image, uri, strokes, ctx) => {
        await imageAnnotation.onSubmit(image, uri, strokes, ctx);
        onClose(); // 提交成功:图表查看器一并关闭,回聊天看托盘
      },
    };
  }, [imageAnnotation, onClose]);
  const payloadSummary = useMemo(
    () => payload ? summarizeMessagePayload(payload) : null,
    [i18nInstance.language, payload],
  );
  const payloadPreview = useMemo(
    () => payload ? summarizeMessagePayloadPreview(payload) : null,
    [i18nInstance.language, payload],
  );
  const payloadDetailText = payloadHeaderDetailText(payloadPreview, payloadSummary?.subtitle);
  const canCopyPayload = !!payloadSummary?.copyableText?.trim();
  const canOpenPayloadUrl = payloadSummary?.openTarget?.kind === 'url'
    && isDirectPreviewableMediaUrl(payloadSummary.openTarget.value);
  const { width: screenWidth, height: screenHeight } = useWindowDimensions();
  const safeAreaInsets = useSafeAreaInsets();
  const headerLayout = buildPayloadHeaderLayout({
    canCopy: canCopyPayload,
    canOpen: canOpenPayloadUrl,
    canPageGallery: false, // 图片已走 ImageLightbox,本查看器不再有图库翻页
    screenHeight,
    screenWidth,
  });
  const modalSafeArea = buildPayloadModalSafeArea({
    androidStatusBarHeight: StatusBar.currentHeight ?? 0,
    landscape: headerLayout.landscape,
    platform: Platform.OS,
    safeAreaBottom: safeAreaInsets.bottom,
    safeAreaTop: safeAreaInsets.top,
  });

  useEffect(() => {
    payloadCopySeqRef.current += 1;
    setPayloadCopyState('idle');
  }, [payloadSummary?.copyableText]);

  useEffect(() => {
    if (payloadCopyState === 'idle' || payloadCopyState === 'copying') return;
    const timer = setTimeout(() => setPayloadCopyState('idle'), 1500);
    return () => clearTimeout(timer);
  }, [payloadCopyState]);

  const copyPayload = useCallback(() => {
    const text = payloadSummary?.copyableText ?? '';
    if (!text.trim() || payloadCopyState === 'copying') return;
    const seq = ++payloadCopySeqRef.current;
    setPayloadCopyState('copying');
    void writeClipboardText(text)
      .then(() => {
        if (payloadCopySeqRef.current === seq) setPayloadCopyState('copied');
      })
      .catch(() => {
        if (payloadCopySeqRef.current === seq) setPayloadCopyState('failed');
      });
  }, [payloadCopyState, payloadSummary?.copyableText]);

  const openPayloadUrl = useCallback(() => {
    const target = payloadSummary?.openTarget;
    if (target?.kind !== 'url' || !isDirectPreviewableMediaUrl(target.value)) return;
    void Linking.openURL(target.value).catch(() => undefined);
  }, [payloadSummary?.openTarget]);

  const exportMermaidPng = useCallback(async () => {
    const handle = mermaidViewRef.current;
    if (!handle || mermaidExporting) return;
    setMermaidExporting(true);
    try {
      const base64 = await handle.exportPng();
      const uri = await writeMermaidExportPngTemp(base64);
      if (!uri) throw new Error('write temp failed');
      // 动态 import:expo-sharing 在模块顶层 requireNativeModule('ExpoSharing'),
      // 旧 dev client 缺原生模块时顶层 import 会炸整个 bundle(同 lightbox 先例)。
      const sharing = await import('expo-sharing');
      await sharing.shareAsync(uri, { mimeType: 'image/png' });
    } catch {
      Alert.alert(t('message.renderer.mermaidExportFailedTitle'), t('message.renderer.mermaidRenderIncompleteBody'));
    } finally {
      setMermaidExporting(false);
    }
  }, [mermaidExporting, t]);

  // 标注 / 发送到对话:导出 PNG 后打开嵌套标注 lightbox(见 annotatePayload
  // 注释),标注圆钮、直发进 composer 托盘等能力全部复用图片消息的既有链路。
  const annotateMermaid = useCallback(async () => {
    const handle = mermaidViewRef.current;
    if (!handle || !imageAnnotation || mermaidExporting) return;
    setMermaidExporting(true);
    try {
      const base64 = await handle.exportPng();
      const uri = await writeMermaidExportPngTemp(base64);
      if (!uri) throw new Error('write temp failed');
      setAnnotatePayload(buildMediaPayload(
        { kind: 'image', url: uri, previewable: true, title: t('message.renderer.mermaidDiagramTitle') },
        t('message.renderer.mermaidDiagramTitle'),
      ));
    } catch {
      Alert.alert(t('message.renderer.mermaidAnnotateFailedTitle'), t('message.renderer.mermaidRenderIncompleteBody'));
    } finally {
      setMermaidExporting(false);
    }
  }, [mermaidExporting, imageAnnotation, t]);

  // mermaid 走沉浸式全屏查看器:图表铺满整个 Modal(标题与源码区都不渲染,
  // 图表最大化优先),仅右上角浮动「复制源码 / 关闭」;源码用复制按钮获取。
  const immersiveMermaid = payload?.kind === 'mermaid';

  return (
    <Modal
      animationType="slide"
      onRequestClose={onClose}
      presentationStyle="fullScreen"
      supportedOrientations={['portrait', 'landscape']}
      visible={!!payload}
    >
      {immersiveMermaid && payload ? (
        <View style={styles.payloadModal} testID="message.payloadModal">
          <MermaidDiagramWebView
            bare
            deferSource
            fill
            ref={mermaidViewRef}
            source={payload.body}
            testID="message.payloadMermaidDiagram"
            zoomable
          />
          <View style={[styles.payloadFloatingActions, { top: modalSafeArea.paddingTop, right: safeAreaInsets.right + spacing.lg }]}>
            {imageAnnotation ? (
              <PayloadHeaderActionButton
                accessibilityLabel={t('message.renderer.annotateSendToChat')}
                disabled={mermaidExporting}
                onPress={() => { void annotateMermaid(); }}
                style={[styles.payloadHeaderButton, styles.payloadFloatingButton]}
                testID="message.payloadAnnotateButton"
              >
                <PencilLine color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.regular} />
              </PayloadHeaderActionButton>
            ) : null}
            <PayloadHeaderActionButton
              accessibilityLabel={t('message.renderer.exportDiagramImage')}
              disabled={mermaidExporting}
              onPress={() => { void exportMermaidPng(); }}
              style={[styles.payloadHeaderButton, styles.payloadFloatingButton]}
              testID="message.payloadExportButton"
            >
              {mermaidExporting ? (
                <ActivityIndicator color={colors.textSecondary} size="small" />
              ) : (
                <ShareIcon color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.regular} />
              )}
            </PayloadHeaderActionButton>
            <PayloadHeaderActionButton
              accessibilityLabel={t('message.renderer.closeDetail')}
              onPress={onClose}
              style={[styles.payloadCloseButton, styles.payloadFloatingButton]}
              testID="message.payloadCloseButton"
            >
              <X color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />
            </PayloadHeaderActionButton>
          </View>
          {annotatePayload && annotateImages ? (
            // 嵌套标注层:必须渲染在本 Modal 的 children 内(见 annotatePayload 注释)。
            // 入口本身就是「标注」:打开即进标注模式;放弃标注直接回图表(对齐桌面)。
            <ImageLightbox
              annotation={annotateLightboxAnnotation}
              autoAnnotate
              images={annotateImages}
              initialUrl={annotatePayload.media.url}
              onClose={closeAnnotatePayload}
              onResolveRemoteMedia={onResolveRemoteMedia}
              onShareImage={onShareImage}
            />
          ) : null}
        </View>
      ) : (
      <View
        style={[
          styles.payloadModal,
          {
            paddingBottom: modalSafeArea.paddingBottom,
            // Landscape side insets hold the notch or a vertical system bar (Duo).
            paddingLeft: safeAreaInsets.left,
            paddingRight: safeAreaInsets.right,
            paddingTop: modalSafeArea.paddingTop,
          },
        ]}
        testID="message.payloadModal"
      >
        <View
          style={[
            styles.payloadHeader,
            {
              // 横屏压成紧凑单行(标题/按钮垂直居中),纵向空间全部让给 body。
              alignItems: headerLayout.landscape ? 'center' : 'flex-start',
              flexDirection: headerLayout.headerDirection,
              gap: headerLayout.headerGap,
              minHeight: headerLayout.headerMinHeight,
              paddingHorizontal: headerLayout.headerPaddingHorizontal,
            },
          ]}
          testID="message.payloadViewerHeader"
        >
          <View style={styles.payloadHeaderText}>
            <Text style={styles.payloadTitle} numberOfLines={headerLayout.titleNumberOfLines}>{payloadSummary?.title ?? ''}</Text>
            {payloadDetailText && headerLayout.showSubtitle ? (
              <Text style={styles.payloadGalleryCount} numberOfLines={1} testID="message.payloadSubtitle">
                {payloadDetailText}
              </Text>
            ) : null}
          </View>
          <View
            style={[
              styles.payloadHeaderActions,
              {
                alignItems: headerLayout.actionsAlignItems,
                flexDirection: headerLayout.actionsDirection,
                width: headerLayout.actionsWidth,
              },
            ]}
          >
            <View
              style={[
                styles.payloadHeaderPrimaryActions,
                {
                  gap: headerLayout.actionGap,
                  justifyContent: headerLayout.primaryActionsJustifyContent,
                },
              ]}
            >
              {canCopyPayload ? (
                <PayloadHeaderActionButton
                  accessibilityLabel={t('message.renderer.copyDetailContent')}
                  disabled={payloadCopyState === 'copying'}
                  onPress={copyPayload}
                  style={[
                    styles.payloadHeaderButton,
                    { minWidth: headerLayout.actionButtonMinWidth },
                  ]}
                  testID="message.payloadCopyButton"
                >
                  {payloadCopyState === 'copying' ? (
                    <ActivityIndicator color={colors.textSecondary} size="small" />
                  ) : payloadCopyState === 'copied' ? (
                    <Check color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.regular} />
                  ) : (
                    <Copy color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.regular} />
                  )}
                </PayloadHeaderActionButton>
              ) : null}
              {canOpenPayloadUrl ? (
                <PayloadHeaderActionButton
                  accessibilityLabel={t('message.renderer.openDetailLink')}
                  onPress={openPayloadUrl}
                  style={[
                    styles.payloadHeaderButton,
                    { minWidth: headerLayout.actionButtonMinWidth },
                  ]}
                  testID="message.payloadOpenButton"
                >
                  <ExternalLink color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.regular} />
                </PayloadHeaderActionButton>
              ) : null}
            </View>
            {payloadCopyState === 'copied' || payloadCopyState === 'failed' ? (
              <Text style={styles.payloadHeaderStatus} testID="message.payloadCopyStatus">
                {payloadCopyState === 'copied' ? t('message.renderer.copyStateCopied') : t('message.renderer.copyStateFailed')}
              </Text>
            ) : null}
            <PayloadHeaderActionButton
              accessibilityLabel={t('message.renderer.closeDetail')}
              onPress={onClose}
              style={[
                styles.payloadCloseButton,
                { minWidth: headerLayout.closeButtonMinWidth },
              ]}
              testID="message.payloadCloseButton"
            >
              <X color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />
            </PayloadHeaderActionButton>
          </View>
        </View>
        {payload ? (
          <View style={styles.payloadViewerBody} testID="message.payloadViewerBody">
            <MessagePayloadBody
              onReadTextFilePreview={onReadTextFilePreview}
              onReleaseRemoteMedia={onReleaseRemoteMedia}
              onResolveRemoteMedia={onResolveRemoteMedia}
              payload={payload}
            />
          </View>
        ) : null}
      </View>
      )}
    </Modal>
  );
}

type RemoteMediaState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; media: MobileResolvedRemoteMedia }
  | { status: 'error'; message: string };

type PayloadHeaderCopyState = 'idle' | 'copying' | 'copied' | 'failed';

function PayloadHeaderActionButton({
  accessibilityLabel,
  children,
  disabled = false,
  onPress,
  style,
  testID,
}: {
  accessibilityLabel: string;
  children: ReactNode;
  disabled?: boolean;
  onPress?: () => void;
  style?: StyleProp<ViewStyle>;
  testID?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const interactionDisabled = disabled || !onPress;
  return (
    <Pressable
      accessibilityLabel={accessibilityLabel}
      accessibilityRole="button"
      accessibilityState={{ disabled: interactionDisabled }}
      disabled={interactionDisabled}
      onPress={interactionDisabled ? undefined : onPress}
      style={({ pressed }) => [
        style,
        pressed && styles.pressed,
        interactionDisabled && styles.disabled,
      ]}
      testID={testID}
    >
      {children}
    </Pressable>
  );
}

function payloadHeaderDetailText(
  preview: MessagePayloadPreview | null,
  fallback?: string,
): string | undefined {
  if (!preview) return fallback;
  if (preview.kind === 'diff') return fallback || preview.detail;
  return preview.detail || fallback;
}

function MessagePayloadBody({
  payload,
  onReadTextFilePreview,
  onReleaseRemoteMedia,
  onResolveRemoteMedia,
}: {
  payload: MessagePayload;
  onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
  onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;
  onResolveRemoteMedia?: ResolveRemoteMediaFn;
}) {
  const { colors } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const { width: screenWidth } = useWindowDimensions();
  const [remoteState, setRemoteState] = useState<RemoteMediaState>({ status: 'idle' });
  const [playerStatus, setPlayerStatus] = useState<MobileMediaPlayerStatus | null>(null);
  const resolvedRemoteMediaRef = useRef<MobileResolvedRemoteMedia | null>(null);
  const bodyPresentation = useMemo(
    () => summarizeMessagePayloadBody(payload),
    [i18nInstance.language, payload],
  );
  const payloadLayout = useMemo(() => buildPayloadBodyLayout({
    kind: payload.kind,
    screenWidth,
  }), [payload.kind, screenWidth]);
  const remoteMedia = payload.kind === 'media' && !payload.media.previewable && isDesktopLocalMediaUrl(payload.media.url)
    ? payload.media
    : null;
  const mediaPlayerSourceKey = payload.kind === 'media'
    ? `${payload.media.kind}:${remoteState.status === 'ready' ? remoteState.media.url : payload.media.url}`
    : '';
  // forceRefresh:重试按钮显式重试时穿透取件队列的 20s 负缓存(挂载取件不传)。
  const resolve = useCallback((forceRefresh = false) => {
    if (!remoteMedia || !onResolveRemoteMedia) return;
    let cancelled = false;
    const startedAt = Date.now();
    setRemoteState({ status: 'loading' });
    // 用户主动打开的原图插队头,优先于列表缩略图的懒取件。
    void onResolveRemoteMedia(remoteMedia, { front: true, forceRefresh })
      .then((media) => {
        mobileDebugLog('debug', 'files', 'message media fetch done', {
          kind: remoteMedia.kind, ms: Date.now() - startedAt, source: resolvedUrlKind(media.url),
          previewable: media.previewable, size: media.size, left: cancelled, forceRefresh,
        });
        if (!cancelled) setRemoteState({ status: 'ready', media });
      })
      .catch((err) => {
        mobileDebugLog(cancelled ? 'debug' : 'warn', 'files', 'message media fetch failed', {
          kind: remoteMedia.kind, ms: Date.now() - startedAt, left: cancelled, forceRefresh, error: errorText(err),
        });
        if (!cancelled) setRemoteState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
      });
    return () => {
      cancelled = true;
    };
  }, [onResolveRemoteMedia, remoteMedia]);

  useEffect(() => {
    setRemoteState({ status: 'idle' });
    resolvedRemoteMediaRef.current = null;
    return resolve();
  }, [resolve]);

  useEffect(() => {
    setPlayerStatus(null);
  }, [mediaPlayerSourceKey]);

  useEffect(() => {
    if (remoteState.status === 'ready') {
      resolvedRemoteMediaRef.current = remoteState.media;
    }
  }, [remoteState]);

  useEffect(() => () => {
    const resolved = resolvedRemoteMediaRef.current;
    // image 缩略图常驻列表,不随 payload viewer 关闭逐出。video/audio 关闭时只
    // 逐出 JS cache,OSS 对象延迟到换会话/页面卸载统一删除(见 [sessionId].tsx)。
    if (remoteMedia?.url && resolved && remoteMedia.kind !== 'image') {
      onReleaseRemoteMedia?.(remoteMedia.url, resolved);
    }
  }, [onReleaseRemoteMedia, remoteMedia?.kind, remoteMedia?.url]);

  if (payload.kind === 'media') {
    const resolved = remoteState.status === 'ready' ? remoteState.media : null;
    const displayUrl = resolved?.url ?? payload.media.url;
    // 聊天里的图片 / 视频已分流到 ImageLightbox 全屏查看器,本查看器主要承载音频与其它媒体。
    const playerKind = payload.media.kind === 'video' || payload.media.kind === 'audio' ? payload.media.kind : null;
    const canInlinePlayer = playerKind !== null
      && isDirectPreviewableMediaUrl(displayUrl)
      && ((bodyPresentation.media?.canInlineDirectPlayer ?? false) || resolved?.previewable);
    const canOpenUrl = isDirectPreviewableMediaUrl(displayUrl);
    return (
      <View style={styles.payloadBody}>
        {canInlinePlayer && playerKind ? (
          <View style={[styles.payloadMediaPlayerFrame, { minHeight: payloadLayout.mediaFrameMinHeight }]}>
            <RemoteMediaPlayerWebView
              kind={playerKind}
              mimeType={resolved?.mimeType}
              onStatusChange={setPlayerStatus}
              style={[styles.payloadMediaPlayer, { minHeight: payloadLayout.mediaPlayerMinHeight }]}
              testID="message.remoteMediaPlayer"
              title={payload.title}
              url={displayUrl}
            />
            <Text style={styles.payloadMediaPlayerStatus} testID="message.remoteMediaPlayerStatus">
              {formatMediaPlayerStatus(playerStatus, playerKind)}
            </Text>
          </View>
        ) : (
          <View style={[
            styles.payloadMediaPlaceholder,
            {
              minHeight: payloadLayout.mediaPlaceholderMinHeight,
              padding: payloadLayout.bodyPadding,
            },
          ]}>
            <Text style={styles.payloadMediaKind}>{bodyPresentation.media?.kindLabel ?? payloadMediaKindLabel(payload.media.kind)}</Text>
            {remoteState.status === 'loading' ? <ActivityIndicator color={colors.textSecondary} /> : null}
            <Text style={styles.payloadMediaHint}>
              {remoteMedia
                ? remoteMediaStatusText(remoteState, bodyPresentation.media?.remoteIdleText)
                : bodyPresentation.media?.unsupportedText ?? t('message.renderer.mediaNotPreviewable')}
            </Text>
            {remoteState.status === 'error' && remoteMedia && onResolveRemoteMedia ? (
              <PayloadActionButton
                accessibilityLabel={t('message.renderer.retryRemoteMediaFetch')}
                label={t('message.renderer.retryFetch')}
                // 不能直接 onPress={resolve}:Pressable 会把事件对象塞进 forceRefresh 参数
                onPress={() => {
                  resolve(true);
                }}
                layout={payloadLayout}
                testID="message.remoteMediaRetryButton"
              />
            ) : null}
            {canOpenUrl ? (
              <PayloadActionButton
                accessibilityLabel={t('message.renderer.openMedia')}
                label={t('message.renderer.openMedia')}
                onPress={() => {
                  void Linking.openURL(displayUrl).catch(() => undefined);
                }}
                layout={payloadLayout}
                testID="message.remoteMediaOpenButton"
              />
            ) : null}
          </View>
        )}
        <ScrollView
          style={[styles.payloadScroll, { maxHeight: payloadLayout.textScrollMaxHeight }]}
          contentContainerStyle={[styles.payloadScrollContent, { padding: payloadLayout.bodyPadding }]}
        >
          <Text selectable style={styles.payloadText}>
            {formatMediaPayloadBody(payload, resolved, remoteState, bodyPresentation.bodyText)}
          </Text>
        </ScrollView>
      </View>
    );
  }

  if (payload.kind === 'file') {
    return (
      <FilePayloadBody
        onResolveRemoteMedia={onResolveRemoteMedia}
        layout={payloadLayout}
        onReadTextFilePreview={onReadTextFilePreview}
        payload={payload}
      />
    );
  }

  // mermaid 不经过本组件:MessagePayloadModal 里走沉浸式全屏查看器分支。

  if (payload.kind === 'diff') {
    return (
      <DiffPayloadBody
        diff={payload.diff}
        layout={payloadLayout}
        onReadTextFilePreview={onReadTextFilePreview}
      />
    );
  }

  return (
    <ScrollView
      style={styles.payloadBody}
      contentContainerStyle={[styles.payloadScrollContent, { padding: payloadLayout.bodyPadding }]}
    >
      <Text selectable style={styles.payloadText}>{bodyPresentation.bodyText || bodyPresentation.emptyText}</Text>
    </ScrollView>
  );
}

function DiffPayloadBody({
  diff,
  layout,
  onReadTextFilePreview,
}: {
  diff: NormalizedToolDiff;
  layout: PayloadBodyLayout;
  onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
}) {
  const { colors } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const view = useMemo(
    () => formatDiffPayloadView(diff),
    [diff, i18nInstance.language],
  );
  const [filePreviewVisible, setFilePreviewVisible] = useState(false);
  const { canPreview, loadPreview, previewKind, previewState } = useRemoteTextFilePreview(view.filePath, onReadTextFilePreview);
  const openFilePreview = useCallback(() => {
    setFilePreviewVisible(true);
    loadPreview();
  }, [loadPreview]);

  return (
    <View style={styles.payloadBody} testID="message.diffPayloadBody">
      <View style={[styles.payloadDiffHeaderBlock, { padding: layout.bodyPadding }]}>
        <Text selectable style={styles.payloadDiffPath} numberOfLines={2}>
          {view.filePath}
        </Text>
        <Text style={styles.payloadDiffStats}>{view.stats}</Text>
        <PayloadPathActions layout={layout} path={view.filePath}>
          {canPreview ? (
            <PayloadActionButton
              accessibilityLabel={t('message.renderer.readCurrentRemoteFile')}
              busy={previewState.status === 'loading'}
              label={previewState.status === 'unavailable'
                ? t('message.renderer.retryFilePreview')
                : t('message.renderer.readCurrentFile')}
              layout={layout}
              onPress={openFilePreview}
              testID="message.diffFilePreviewLoadButton"
            />
          ) : null}
        </PayloadPathActions>
      </View>
      {filePreviewVisible ? (
        <View
          style={[
            styles.payloadDiffFilePreviewBlock,
            {
              gap: layout.diffContentGap,
              padding: layout.bodyPadding,
            },
          ]}
          testID="message.diffFilePreviewBlock"
        >
          <Text style={styles.payloadDiffSectionTitle}>{t('message.renderer.currentFilePreview')}</Text>
          {previewState.status === 'loading' ? <ActivityIndicator color={colors.textSecondary} /> : null}
          <Text
            style={styles.payloadMediaHint}
            testID={previewState.status === 'ready' ? 'message.diffFilePreviewReady' : 'message.diffFilePreviewStatus'}
          >
            {textPreviewStatusText(previewState, canPreview, previewKind)}
          </Text>
          <ScrollView
            style={[styles.payloadDiffFilePreviewScroll, { maxHeight: layout.filePreviewMaxHeight }]}
            contentContainerStyle={[styles.payloadScrollContent, { padding: layout.bodyPadding }]}
          >
            <Text selectable style={[styles.payloadText, styles.payloadMonoText]} testID="message.diffFilePreviewText">
              {previewState.status === 'ready'
                ? previewState.data
                : textPreviewStatusText(previewState, canPreview, previewKind)}
            </Text>
          </ScrollView>
        </View>
      ) : null}
      <ScrollView
        style={styles.payloadDiffScroll}
        contentContainerStyle={[
          styles.payloadDiffContent,
          {
            gap: layout.diffContentGap,
            padding: layout.bodyPadding,
          },
        ]}
      >
        {view.sections.map((section) => (
          <View key={section.key} style={styles.payloadDiffSection} testID="message.diffCompareSection">
            <Text style={styles.payloadDiffSectionTitle}>{section.label}</Text>
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator
              style={styles.payloadDiffCompareScroll}
              testID="message.diffCompareScroll"
            >
              <View style={[
                styles.payloadDiffCompareRow,
                {
                  gap: layout.diffPaneGap,
                  paddingBottom: layout.diffContentGap,
                },
              ]}>
                <DiffPayloadPane
                  emptyText={t('message.renderer.diffNoOldContent')}
                  layout={layout}
                  lines={section.oldLines}
                  prefix="-"
                  testID="message.diffCompareOldPane"
                  title={t('message.renderer.diffOldTitle')}
                  variant="old"
                />
                <DiffPayloadPane
                  emptyText={t('message.renderer.diffNoNewContent')}
                  layout={layout}
                  lines={section.newLines}
                  prefix="+"
                  testID="message.diffCompareNewPane"
                  title={t('message.renderer.diffNewTitle')}
                  variant="new"
                />
              </View>
            </ScrollView>
          </View>
        ))}
      </ScrollView>
    </View>
  );
}

function DiffPayloadPane({
  emptyText,
  layout,
  lines,
  prefix,
  testID,
  title,
  variant,
}: {
  emptyText: string;
  layout: PayloadBodyLayout;
  lines: FormattedDiffPayloadLine[];
  prefix: '-' | '+';
  testID: string;
  title: string;
  variant: 'old' | 'new';
}) {
  const styles = useThemedStyles(makeStyles);
  return (
    <View style={[styles.payloadDiffPane, { width: layout.diffPaneWidth }]} testID={testID}>
      <View style={styles.payloadDiffPaneHeader}>
        <Text style={styles.payloadDiffPaneTitle}>{title}</Text>
      </View>
      <View style={styles.payloadDiffPaneBody}>
        {lines.length > 0 ? lines.map((line) => (
          <View
            key={line.key}
            style={[
              styles.payloadDiffCompareLine,
              { minHeight: layout.diffLineMinHeight },
              variant === 'old' ? styles.payloadDiffCompareLineOld : styles.payloadDiffCompareLineNew,
            ]}
            testID={variant === 'old' ? 'message.diffPayloadRow.delete' : 'message.diffPayloadRow.add'}
          >
            <Text style={[styles.payloadDiffLineNumber, { width: layout.diffLineNumberWidth }]}>{line.lineNumber}</Text>
            <Text style={[
              styles.payloadDiffLinePrefix,
              { width: layout.diffLinePrefixWidth },
              variant === 'old' ? styles.payloadDiffLinePrefixOld : styles.payloadDiffLinePrefixNew,
            ]}>
              {prefix}
            </Text>
            <Text selectable style={[
              styles.payloadDiffLineText,
              variant === 'old' ? styles.payloadDiffLineTextOld : styles.payloadDiffLineTextNew,
            ]} testID={variant === 'old' ? 'message.diffCompareOldLine' : 'message.diffCompareNewLine'}>
              {line.text || ' '}
            </Text>
          </View>
        )) : (
          <Text style={styles.payloadDiffEmptyLine}>{emptyText}</Text>
        )}
      </View>
    </View>
  );
}

function FilePayloadBody({
  onResolveRemoteMedia,
  layout,
  payload,
  onReadTextFilePreview,
}: {
  onResolveRemoteMedia?: ResolveRemoteMediaFn;
  layout: PayloadBodyLayout;
  payload: Extract<MessagePayload, { kind: 'file' }>;
  onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
}) {
  const { colors } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const sourcePath = payload.sourcePath ?? '';
  const { accountGeneration } = useAuth();
  const fileContext = useContext(ChatFilePathContext);
  const [exporting, setExporting] = useState(false);
  const exportIdentity = JSON.stringify([accountGeneration, fileContext?.deviceId, fileContext?.sessionId, sourcePath]);
  const exportCurrent = useRef(exportIdentity); exportCurrent.current = exportIdentity;
  const exportBusy = useRef(false);
  const exportGeneration = useRef(0);
  useLayoutEffect(() => {
    exportCurrent.current = exportIdentity;
    exportGeneration.current += 1;
    exportBusy.current = false;
    setExporting(false);
    return () => { exportGeneration.current += 1; exportCurrent.current = ''; };
  }, [exportIdentity, onResolveRemoteMedia]);
  const exportFile = async () => {
    if (!onResolveRemoteMedia || exportBusy.current) return;
    const identity = exportIdentity;
    const generation = exportGeneration.current;
    const valid = () => exportCurrent.current === identity && exportGeneration.current === generation;
    exportBusy.current = true; setExporting(true);
    try {
      const resolved = await onResolveRemoteMedia({ kind: 'file', url: sourcePath, previewable: false }, { front: true });
      if (!valid()) return;
      const localUri = resolved.url.startsWith('file://') ? resolved.url : await downloadRemoteMediaShareTemp(resolved.url, resolved.mimeType, payload.title);
      if (!valid()) return;
      if (!localUri) throw new Error('download failed');
      const sharing = await import('expo-sharing');
      if (valid()) await sharing.shareAsync(localUri, { mimeType: resolved.mimeType });
    } catch {
      if (valid()) Alert.alert(t('files.browser.shareFailed'));
    } finally {
      if (valid()) { exportBusy.current = false; setExporting(false); }
    }
  };
  const bodyPresentation = useMemo(
    () => summarizeMessagePayloadBody(payload),
    [i18nInstance.language, payload],
  );
  const { canPreview, loadPreview, previewKind, previewState } = useRemoteTextFilePreview(sourcePath, onReadTextFilePreview);

  return (
    <View style={styles.payloadBody} testID="message.filePayloadBody">
      <View style={[
        styles.payloadMediaPlaceholder,
        {
          minHeight: layout.mediaPlaceholderMinHeight,
          padding: layout.bodyPadding,
        },
      ]}>
        <Text style={styles.payloadMediaKind}>{t('message.renderer.fileKind')}</Text>
        <Text selectable style={styles.payloadText}>
          {bodyPresentation.file?.displayPath ?? bodyPresentation.emptyText}
        </Text>
        {previewState.status === 'loading' ? <ActivityIndicator color={colors.textSecondary} /> : null}
        <Text style={styles.payloadMediaHint} testID={filePreviewStatusTestId(previewKind)}>
          {textPreviewStatusText(previewState, canPreview, previewKind)}
        </Text>
        <PayloadPathActions layout={layout} path={sourcePath}>
          {onResolveRemoteMedia && isDesktopLocalMediaUrl(sourcePath) ? <PayloadActionButton
            accessibilityLabel={t('files.browser.exportShare')} label={t('files.browser.exportShare')}
            layout={layout} busy={exporting} onPress={() => { void exportFile(); }} testID="message.fileExportButton" /> : null}

          {canPreview && previewState.status !== 'ready' ? (
            <PayloadActionButton
              accessibilityLabel={t('message.renderer.loadRemoteTextPreview')}
              busy={previewState.status === 'loading'}
              label={previewState.status === 'unavailable' ? t('message.renderer.retryPreview') : t('message.renderer.loadPreview')}
              layout={layout}
              onPress={loadPreview}
              testID="message.filePreviewLoadButton"
            />
          ) : null}
        </PayloadPathActions>
      </View>
      <ScrollView
        style={[styles.payloadScroll, { maxHeight: layout.textScrollMaxHeight }]}
        contentContainerStyle={[styles.payloadScrollContent, { padding: layout.bodyPadding }]}
      >
        <Text selectable style={[styles.payloadText, styles.payloadMonoText]} testID="message.filePreviewText">
          {previewState.status === 'ready' ? previewState.data : bodyPresentation.bodyText || bodyPresentation.emptyText}
        </Text>
      </ScrollView>
    </View>
  );
}

type RemoteTextFilePreviewLoadState =
  | Exclude<TextFilePreviewState, { status: 'unavailable' }>
  | { status: 'unavailable'; result: RemoteTextFilePreviewResult }
  | { status: 'unavailable'; message: string; size: number; limitMb?: number };

function useRemoteTextFilePreview(
  sourcePath: string,
  onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>,
) {
  const { i18n: i18nInstance } = useTranslation();
  const [previewLoadState, setPreviewLoadState] = useState<RemoteTextFilePreviewLoadState>(
    { status: 'idle' },
  );
  const previewSeqRef = useRef(0);
  const previewAbortRef = useRef<AbortController | null>(null);
  const previewKind = useMemo(() => remoteFilePreviewKind(sourcePath), [sourcePath]);
  const canPreview = previewKind === 'text' && !!sourcePath && !!onReadTextFilePreview;

  useEffect(() => {
    previewSeqRef.current += 1;
    setPreviewLoadState({ status: 'idle' });
    return () => {
      previewSeqRef.current += 1;
      previewAbortRef.current?.abort();
    };
  }, [sourcePath, onReadTextFilePreview]);

  const loadPreview = useCallback(() => {
    if (!canPreview || previewLoadState.status === 'loading') return;
    const seq = ++previewSeqRef.current;
    previewAbortRef.current?.abort();
    const abort = new AbortController();
    previewAbortRef.current = abort;
    setPreviewLoadState({ status: 'loading' });
    void onReadTextFilePreview(sourcePath, { signal: abort.signal })
      .then((result) => {
        if (previewSeqRef.current !== seq) return;
        if (result.success && typeof result.data === 'string') {
          setPreviewLoadState({
            status: 'ready',
            data: result.data,
            size: result.size,
            limitMb: result.limitMb,
          });
          return;
        }
        setPreviewLoadState({
          status: 'unavailable',
          result,
        });
      })
      .catch((err) => {
        if (previewSeqRef.current !== seq) return;
        setPreviewLoadState({
          status: 'unavailable',
          message: err instanceof Error ? err.message : String(err),
          size: 0,
        });
      });
  }, [canPreview, onReadTextFilePreview, previewLoadState.status, sourcePath]);

  const previewState = useMemo<TextFilePreviewState>(() => {
    if (previewLoadState.status !== 'unavailable' || !('result' in previewLoadState)) {
      return previewLoadState;
    }
    return {
      status: 'unavailable',
      message: describeTextPreviewFailure(previewLoadState.result),
      size: previewLoadState.result.size,
      limitMb: previewLoadState.result.limitMb,
    };
  }, [i18nInstance.language, previewLoadState]);

  return { canPreview, loadPreview, previewKind, previewState };
}

type PayloadPathCopyState = 'idle' | 'copying' | 'copied' | 'failed';

function PayloadPathActions({
  children,
  layout,
  path,
}: {
  children?: ReactNode;
  layout: PayloadBodyLayout;
  path: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const { t } = useTranslation();
  const [copyState, setCopyState] = useState<PayloadPathCopyState>('idle');
  const copySeqRef = useRef(0);
  const canCopy = path.trim().length > 0;

  useEffect(() => {
    copySeqRef.current += 1;
    setCopyState('idle');
  }, [path]);

  useEffect(() => {
    if (copyState === 'idle' || copyState === 'copying') return;
    const timer = setTimeout(() => setCopyState('idle'), 1500);
    return () => clearTimeout(timer);
  }, [copyState]);

  const copyPath = useCallback(() => {
    if (!canCopy || copyState === 'copying') return;
    const seq = ++copySeqRef.current;
    setCopyState('copying');
    void writeClipboardText(path)
      .then(() => {
        if (copySeqRef.current === seq) setCopyState('copied');
      })
      .catch(() => {
        if (copySeqRef.current === seq) setCopyState('failed');
      });
  }, [canCopy, copyState, path]);

  if (!canCopy && !children) return null;

  return (
    <View style={styles.payloadActionBlock}>
      <View style={[styles.payloadActionRow, { gap: layout.actionGap }]} testID="message.payloadPathActions">
        {canCopy ? (
          <PayloadActionButton
            accessibilityLabel={t('message.renderer.copyRemoteFilePath')}
            busy={copyState === 'copying'}
            label={t('message.renderer.copyPath')}
            layout={layout}
            onPress={copyPath}
            testID="message.copyFilePathButton"
          />
        ) : null}
        {children}
      </View>
      {copyState === 'copied' || copyState === 'failed' ? (
        <Text style={styles.payloadPathCopyStatus} testID="message.copyFilePathStatus">
          {copyState === 'copied' ? t('message.renderer.copiedPath') : t('message.renderer.copyPathFailed')}
        </Text>
      ) : null}
    </View>
  );
}

function PayloadActionButton({
  accessibilityLabel,
  busy = false,
  disabled = false,
  label,
  layout,
  onPress,
  testID,
}: {
  accessibilityLabel?: string;
  /** 进行中:按钮只转圈、不显示文字(宽高由 minWidth/minHeight 保持不跳)。 */
  busy?: boolean;
  disabled?: boolean;
  label: string;
  layout: PayloadBodyLayout;
  onPress(): void;
  testID?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const interactionDisabled = disabled || busy;
  return (
    <Pressable
      accessibilityLabel={accessibilityLabel ?? label}
      accessibilityRole="button"
      accessibilityState={{ busy: busy || undefined, disabled: interactionDisabled }}
      disabled={interactionDisabled}
      onPress={interactionDisabled ? undefined : onPress}
      style={({ pressed }) => [
        styles.payloadOpenButton,
        {
          minHeight: layout.actionButtonMinHeight,
          minWidth: layout.actionButtonMinWidth,
        },
        pressed && styles.pressed,
        disabled && !busy && styles.disabled,
      ]}
      testID={testID}
    >
      {busy ? (
        <ActivityIndicator color={colors.textSecondary} size="small" />
      ) : (
        <Text style={styles.payloadOpenButtonText}>{label}</Text>
      )}
    </Pressable>
  );
}

function remoteMediaStatusText(state: RemoteMediaState, idleText = i18n.t('message.renderer.remoteMediaIdle')): string {
  if (state.status === 'loading') return i18n.t('message.renderer.remoteMediaLoading');
  if (state.status === 'ready') {
    const size = formatRemoteMediaSize(state.media.size);
    return [i18n.t('message.renderer.remoteMediaReady'), state.media.mimeType, size].filter(Boolean).join(' · ');
  }
  if (state.status === 'error') return i18n.t('message.renderer.remoteMediaFetchFailed', { message: state.message });
  return idleText;
}

function formatMediaPlayerStatus(
  status: MobileMediaPlayerStatus | null,
  kind: MobileMediaPlayerKind,
): string {
  const label = payloadMediaKindLabel(kind);
  if (!status) return i18n.t('message.renderer.mediaPending', { label });
  const progress = formatMediaPlayerProgress(status);
  switch (status.state) {
    case 'ready':
      return i18n.t('message.renderer.mediaLoaded', { label, progress });
    case 'playing':
      return i18n.t('message.renderer.mediaPlaying', { label, progress });
    case 'paused':
      return i18n.t('message.renderer.mediaPaused', { label, progress });
    case 'waiting':
      return i18n.t('message.renderer.mediaBuffering', { label, progress });
    case 'ended':
      return i18n.t('message.renderer.mediaEnded', { label, progress });
    case 'error':
      return i18n.t('message.renderer.mediaError', { label, error: status.error ? `: ${status.error}` : '' });
  }
}

function formatMediaPlayerProgress(status: MobileMediaPlayerStatus): string {
  if (typeof status.currentTime !== 'number' && typeof status.duration !== 'number') return '';
  const current = formatMediaPlayerTime(status.currentTime ?? 0);
  return typeof status.duration === 'number'
    ? ` · ${current} / ${formatMediaPlayerTime(status.duration)}`
    : ` · ${current}`;
}

function formatMediaPlayerTime(seconds: number): string {
  const safeSeconds = Math.max(0, Math.floor(seconds));
  const hh = Math.floor(safeSeconds / 3600);
  const mm = Math.floor((safeSeconds % 3600) / 60);
  const ss = safeSeconds % 60;
  if (hh > 0) return `${hh}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`;
  return `${mm}:${String(ss).padStart(2, '0')}`;
}

function formatMediaPayloadBody(
  payload: Extract<MessagePayload, { kind: 'media' }>,
  resolved: MobileResolvedRemoteMedia | null,
  state: RemoteMediaState,
  bodyText: string,
): string {
  const lines = [
    bodyText.trim() || i18n.t('message.renderer.mediaSourceUrl', { url: payload.media.url }),
  ];
  if (resolved) {
    const size = formatRemoteMediaSize(resolved.size);
    lines.push(
      i18n.t('message.renderer.mediaDownloadUrl', { url: resolved.url }),
      `MIME: ${resolved.mimeType}`,
      size ? i18n.t('message.renderer.mediaSize', { size }) : '',
      i18n.t('message.renderer.mediaExpiresAt', { time: resolved.expiresAt }),
    );
  } else if (state.status === 'error') {
    lines.push(i18n.t('message.renderer.mediaErrorLine', { message: state.message }));
  } else if (!payload.media.previewable && !bodyText.trim()) {
    lines.push(i18n.t('message.renderer.mediaDeviceLinkHint'));
  }
  return lines.filter(Boolean).join('\n');
}

function MessageControlButton({
  buttonSize,
  busy,
  copyState,
  disabled,
  id,
  iconSize,
  onPress,
}: {
  buttonSize: number;
  busy?: boolean;
  copyState: CopyMessageStatus | 'idle' | 'copying';
  disabled?: boolean;
  id: MobileMessageControlActionId;
  iconSize: number;
  onPress(): void;
}) {
  const { colors } = useTheme();
  const styles = useThemedStyles(makeStyles);
  return (
    <Pressable
      accessibilityLabel={messageControlActionLabel(id, copyState)}
      accessibilityRole="button"
      accessibilityState={{ disabled: disabled === true }}
      disabled={disabled}
      hitSlop={MESSAGE_CONTROL_HIT_SLOP}
      onPress={onPress}
      style={({ pressed }) => [
        styles.messageIconAction,
        { height: buttonSize, width: buttonSize },
        styles.messageIconActionTouchTarget,
        pressed && styles.pressed,
        disabled && styles.disabled,
      ]}
      testID={messageControlActionTestID(id)}
    >
      {messageControlActionIcon(id, copyState, iconSize, colors, busy)}
    </Pressable>
  );
}

function MessageMoreButton({
  buttonSize,
  disabled,
  iconSize: size,
  onPress,
}: {
  buttonSize: number;
  disabled?: boolean;
  iconSize: number;
  onPress(): void;
}) {
  const { t } = useTranslation();
  const { colors } = useTheme();
  const styles = useThemedStyles(makeStyles);
  return (
    <Pressable
      accessibilityLabel={t('message.renderer.moreActions')}
      accessibilityRole="button"
      accessibilityState={{ disabled: disabled === true }}
      disabled={disabled}
      hitSlop={MESSAGE_CONTROL_HIT_SLOP}
      onPress={onPress}
      style={({ pressed }) => [
        styles.messageIconAction,
        { height: buttonSize, width: buttonSize },
        styles.messageIconActionTouchTarget,
        pressed && styles.pressed,
        disabled && styles.disabled,
      ]}
      testID="message.moreButton"
    >
      <Ellipsis color={colors.textSecondary} size={size} strokeWidth={iconStroke.regular} />
    </Pressable>
  );
}

function MessageShareButton({
  buttonSize,
  iconSize: size,
  onPress,
}: {
  buttonSize: number;
  iconSize: number;
  onPress(): void;
}) {
  const { colors } = useTheme();
  const styles = useThemedStyles(makeStyles);
  const { t } = useTranslation();
  return (
    <Pressable
      accessibilityLabel={t('session.shareImage.shareMessage')}
      accessibilityRole="button"
      hitSlop={MESSAGE_CONTROL_HIT_SLOP}
      onPress={onPress}
      style={({ pressed }) => [
        styles.messageIconAction,
        { height: buttonSize, width: buttonSize },
        styles.messageIconActionTouchTarget,
        pressed && styles.pressed,
      ]}
      testID="message.shareButton"
    >
      <ShareIcon color={colors.textSecondary} size={size} strokeWidth={iconStroke.regular} />
    </Pressable>
  );
}

function isMessageControlActionId(id: MessageActionBarItemId): id is 'copy' | 'fork' {
  return id === 'copy' || id === 'fork';
}

function messageControlActionLabel(
  id: MobileMessageControlActionId,
  copyState: CopyMessageStatus | 'idle' | 'copying',
): string {
  if (id === 'copy') return copyActionLabel(copyState);
  if (id === 'delete') return i18n.t('message.renderer.controlDelete');
  if (id === 'rewind') return i18n.t('message.renderer.controlRewind');
  return i18n.t('message.renderer.controlFork');
}

function messageControlActionTestID(id: MobileMessageControlActionId): string {
  if (id === 'copy') return 'message.copyButton';
  if (id === 'delete') return 'message.deleteButton';
  if (id === 'rewind') return 'message.rewindButton';
  return 'message.forkButton';
}

function messageControlActionIcon(
  id: MobileMessageControlActionId,
  copyState: CopyMessageStatus | 'idle' | 'copying',
  iconSize: number,
  colors: ThemeColors,
  busy = false,
): ReactNode {
  if (id === 'fork' && busy) {
    return <ActivityIndicator color={colors.textSecondary} size="small" />;
  }
  if (id === 'copy') {
    return copyState === 'copying'
      ? <ActivityIndicator color={colors.textSecondary} size="small" />
      : copyState === 'copied'
        ? <Check color={colors.textSecondary} size={iconSize} strokeWidth={iconStroke.regular} />
        : <Copy color={colors.textSecondary} size={iconSize} strokeWidth={iconStroke.regular} />;
  }
  if (id === 'delete') return <Trash2 color={colors.textSecondary} size={iconSize} strokeWidth={iconStroke.regular} />;
  if (id === 'rewind') return <Undo2 color={colors.textSecondary} size={iconSize} strokeWidth={iconStroke.regular} />;
  return <Split color={colors.textSecondary} size={iconSize} strokeWidth={iconStroke.regular} />;
}

function mediaLabel(media: NormalizedToolMedia): string {
  const tail = media.url.split('/').pop() || media.url;
  return media.title || tail;
}

function findFirstUserMessageClientId(items: readonly MobileMessageRenderItem[]): string | undefined {
  for (const item of items) {
    const found = findFirstUserMessageClientIdInItem(item);
    if (found) return found;
  }
  return undefined;
}

interface WindowFrame {
  height: number;
  width: number;
  x: number;
  y: number;
}

function measureInWindow(
  target: unknown,
): Promise<WindowFrame | null> {
  return new Promise((resolve) => {
    const measurable = target as {
      measureInWindow?: (
        callback: (x: number, y: number, width: number, height: number) => void,
      ) => void;
    } | null | undefined;
    if (!measurable?.measureInWindow) {
      resolve(null);
      return;
    }
    measurable.measureInWindow((x, y, width, height) => {
      if (![x, y, width, height].every(Number.isFinite)) {
        resolve(null);
        return;
      }
      resolve({ height, width, x, y });
    });
  });
}

function findFirstUserMessageClientIdInItem(
  item: MobileMessageRenderItem | MobileWorkChildItem,
): string | undefined {
  if (item.type === 'message' && item.message.kind === 'user') return messageClientId(item);
  if (item.type === 'work_group') {
    for (const child of item.children) {
      const found = findFirstUserMessageClientIdInItem(child);
      if (found) return found;
    }
  }
  return undefined;
}

function findLastUserInputClientId(items: readonly MobileMessageRenderItem[]): string | null {
  for (let index = items.length - 1; index >= 0; index--) {
    const found = findLastUserInputClientIdInItem(items[index]);
    if (found) return found;
  }
  return null;
}

function findLastUserInputClientIdInItem(
  item: MobileMessageRenderItem | MobileWorkChildItem,
): string | null {
  if (item.type === 'message' && item.message.role === 'user') {
    const delivery = item.message.source.agentMeta?.delivery;
    return delivery === 'steer' ? null : messageClientId(item);
  }
  if (item.type === 'work_group') {
    for (let index = item.children.length - 1; index >= 0; index--) {
      const found = findLastUserInputClientIdInItem(item.children[index]);
      if (found) return found;
    }
  }
  return null;
}

function messageClientId(item: MobileMessageItem): string {
  return item.message.source.clientId || item.message.source.id || item.message.key;
}

/** Host-stamped input a companion reply answers (agentMeta.replyToClientId). */
function readReplyToClientId(message: NormalizedRemoteMessage): string | null {
  const value = message.source.agentMeta?.replyToClientId;
  return typeof value === 'string' && value ? value : null;
}

/** A message the companion's reply can point back to: a visible message the owner typed. */
function isOwnerTypedMessage(message: NormalizedRemoteMessage | undefined): message is NormalizedRemoteMessage {
  return !!message && message.kind === 'user' && !message.isSyntheticTrigger && !message.automationOrigin
    && !message.hookSource && !message.sessionOrigin && !message.systemCardType;
}

/** 语法 kind → 样式。plain 不走这里(直接当字符串塞进父 Text,少一层节点)。 */
function syntaxStyleFor(
  styles: ReturnType<typeof makeStyles>,
  kind: Exclude<CodeTokenKind, 'plain'>,
): StyleProp<TextStyle> {
  switch (kind) {
    case 'keyword': return styles.syntaxKeyword;
    case 'string': return styles.syntaxString;
    case 'comment': return styles.syntaxComment;
    case 'number': return styles.syntaxNumber;
    case 'function': return styles.syntaxFunction;
    case 'property': return styles.syntaxProperty;
  }
}

/**
 * 代码块正文 —— 按 language 做词法着色(配色对齐桌面的 GitHub hljs 主题)。
 *
 * 抽成组件只为拿 useMemo:renderBlock 每次重渲都会走到,大代码块重复分词不划算。
 * 嵌套 span 只带 color,其余样式继承外层 markdownCodeText。
 *
 * ⚠️ `SpanComponent` 必须由调用方经 `spanFor()` 给出,不能图省事直接用 RN 的
 * `Text`:块可选中且在 iOS 时外层是 UITextView,而它只接受 UITextView 家族的子
 * 节点 —— 传普通 Text 的话那些 span 会被整个丢掉(表现为代码里的属性名、关键字
 * 直接从画面上消失,不报错)。
 */
function HighlightedCodeText({
  SpanComponent,
  allowIosUITextView,
  language,
  selectable,
  styles,
  text,
}: {
  SpanComponent: typeof Text;
  allowIosUITextView: boolean;
  language: string | undefined;
  selectable: boolean;
  styles: ReturnType<typeof makeStyles>;
  text: string;
}) {
  const tokens = useMemo(() => tokenizeCode(text, language), [language, text]);
  return (
    <MarkdownSelectableText
      allowIosUITextView={allowIosUITextView}
      selectable={selectable}
      style={styles.markdownCodeText}
    >
      {tokens.map((token, index) => (
        token.kind === 'plain'
          ? token.text
          : (
            <SpanComponent key={index} style={syntaxStyleFor(styles, token.kind)}>
              {token.text}
            </SpanComponent>
          )
      ))}
    </MarkdownSelectableText>
  );
}

/**
 * markdown 标题的字号档:h1 / h2 / h3+ 三档(见 markdownHeading* 的比例说明)。
 * 两处渲染路径(text_run 合并树与独立 heading 块)共用,避免再次分叉成
 * 「level <= 2 一刀切」那种只有两档、且第二档比正文还小的形态。
 */
function headingSizeStyle(
  styles: ReturnType<typeof makeStyles>,
  level: number,
): StyleProp<TextStyle> {
  if (level <= 1) return styles.markdownHeadingLarge;
  if (level === 2) return styles.markdownHeadingMedium;
  return styles.markdownHeadingSmall;
}

const makeStyles = (colors: ThemeColors) => StyleSheet.create({
  messageFrame: { flex: 1, minHeight: 0 },
  messageList: { flex: 1 },
  messages: {
    flexGrow: 1,
    // Anchor a short conversation to the bottom (just above the composer) like a normal chat,
    // instead of pinning it to the top with dead space below. With flexGrow:1 this only affects
    // the under-one-screen case; once messages overflow the viewport the list scrolls normally.
    justifyContent: 'flex-end',
    gap: spacing.lg,
    paddingBottom: MOBILE_MESSAGE_LIST_BOTTOM_PADDING,
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.lg,
  },
  messagesWide: {
    alignSelf: 'center',
    width: '100%',
  },
  focusedItem: {
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.borderStrong,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    marginHorizontal: -spacing.xs,
    padding: spacing.xs,
  },
  emptyCard: {
    alignItems: 'center',
    justifyContent: 'center',
    minHeight: 168,
    paddingHorizontal: spacing.lg,
  },
  emptyTitle: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
  },
  syncingTitle: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
    marginTop: spacing.sm,
  },
  messageItem: {
    gap: 2,
    width: '100%',
  },
  shareSelectionContent: {
    flex: 1,
    minWidth: 0,
  },
  stickyShareOverlay: {
    height: SHARE_STICKY_CHECK_HEIGHT,
    left: 0,
    position: 'absolute',
    right: 0,
    top: 0,
    zIndex: 5,
  },
  stickyShareControl: {
    alignItems: 'center',
    width: spacing.xl * 2,
  },
  sentInlineTextChunk: {
    flexBasis: '100%',
    flexShrink: 1,
    maxWidth: '100%',
  },
  userMessageItem: {
    alignItems: 'flex-end',
  },
  agentMessageItem: {
    alignItems: 'stretch',
  },
  bubble: {
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    gap: spacing.xs,
    padding: spacing.md,
  },
  bubbleCompact: {
    gap: 6,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  bubbleRich: {
    gap: spacing.sm,
  },
  companionAnswer: { backgroundColor: colors.surface, borderWidth: 0, paddingHorizontal: 0 },
  companionQuote: { alignSelf: 'stretch', marginBottom: spacing.xs },
  // Desktop BotAvatar sm (28) + gap-2.5; the task card reuses the same inset.
  companionAvatarRow: { flexDirection: 'row', alignItems: 'flex-start', gap: COMPANION_AVATAR_GAP },
  companionAvatarSlot: { flexShrink: 0, marginTop: 2 },
  companionAvatarContent: { flex: 1, minWidth: 0 },
  companionAvatarInset: { paddingLeft: COMPANION_AVATAR_SIZE + COMPANION_AVATAR_GAP },
  companionTimeGroup: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    marginBottom: spacing.md,
    marginTop: spacing.sm,
    textAlign: 'center',
  },
  userBubble: {
    alignSelf: 'flex-end',
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    maxWidth: '86%',
    minWidth: 0,
    overflow: 'hidden',
  },
  agentBubble: {
    alignSelf: 'stretch',
    backgroundColor: colors.surface,
    borderColor: colors.surface,
    borderWidth: 0,
    maxWidth: '100%',
    paddingHorizontal: 0,
    paddingVertical: spacing.xs,
  },
  hookSourceBubble: {
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    borderWidth: StyleSheet.hairlineWidth,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  hookSourceHeader: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.xs,
    marginBottom: spacing.xs,
  },
  hookSourceTitle: {
    color: colors.textSecondary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.medium,
  },
  hookSourceChannel: {
    color: colors.textTertiary,
    flexShrink: 1,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
  },
  messageText: { color: colors.textPrimary, fontSize: typeScale.bodyLarge, lineHeight: lineHeight.bodyLarge },
  automationOriginRow: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: 4,
    maxWidth: '86%',
  },
  automationOriginText: {
    color: colors.textTertiary,
    flexShrink: 1,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
  },
  sourceLabelStack: {
    alignItems: 'flex-start',
    gap: 2,
    maxWidth: '86%',
  },
  sourceLabelStackUser: {
    alignItems: 'flex-end',
  },
  modelMismatchRow: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: 4,
    maxWidth: '86%',
  },
  failedSamplingAttemptText: {
    color: colors.textSecondary,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
  },
  modelMismatchText: {
    color: colors.textTertiary,
    flexShrink: 1,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
  },
  collapseMeasureWrap: {
    // left/right 与 `bubble` 基础样式的水平 padding(spacing.md)绑定——
    // bubbleCompact 显式覆盖为同值,bubbleRich 未覆盖(继承基础值)。若未来
    // 任何气泡变体改水平 padding,这里必须同步,否则测量宽度偏离正文实际
    // 可用宽度,临界行数(尤其自动任务的 4 行阈值)会误判收起/不收起。
    left: spacing.md,
    opacity: 0,
    position: 'absolute',
    right: spacing.md,
    top: 0,
  },
  collapseToggleText: {
    alignSelf: 'flex-start',
    color: colors.textSecondary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    // Text onPress 无 hitSlop,靠 padding 把点击区撑到 ~32pt 高。
    paddingVertical: spacing.xs,
  },
  systemCard: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    gap: spacing.sm,
    padding: spacing.md,
  },
  systemCardTitle: {
    color: colors.textPrimary,
    fontSize: typeScale.body,
    lineHeight: lineHeight.body,
    fontWeight: fontWeight.medium,
  },
  systemCardBody: {
    color: colors.textSecondary,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
  },
  systemCardRows: {
    gap: spacing.sm,
  },
  systemCardRow: {
    borderTopColor: colors.border,
    borderTopWidth: StyleSheet.hairlineWidth,
    gap: spacing.xs,
    paddingTop: spacing.sm,
  },
  systemCardLabel: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
  },
  systemCardValue: {
    color: colors.textPrimary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
  },
  autoResumeSeparator: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.md,
    paddingVertical: spacing.sm,
  },
  autoResumeDivider: {
    backgroundColor: colors.border,
    flex: 1,
    height: StyleSheet.hairlineWidth,
  },
  autoResumeSeparatorPill: {
    alignItems: 'center',
    borderColor: colors.border,
    borderRadius: radius.pill,
    borderWidth: StyleSheet.hairlineWidth,
    flexDirection: 'row',
    gap: spacing.xs,
    maxWidth: '78%',
    minHeight: 28,
    paddingHorizontal: spacing.sm,
  },
  autoResumeSeparatorText: {
    color: colors.textTertiary,
    flexShrink: 1,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
  },
  autoResumeRow: {
    alignSelf: 'stretch',
  },
  autoResumeHeader: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.xs,
    minHeight: 44,
    paddingHorizontal: spacing.xs,
  },
  autoResumeIconSlot: {
    alignItems: 'center',
    height: 18,
    justifyContent: 'center',
    width: iconSize.md,
  },
  autoResumeTitle: {
    color: colors.textSecondary,
    flexShrink: 1,
    flexGrow: 0,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
  },
  autoResumeSummary: {
    color: colors.textSecondary,
    flex: 1,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
    minWidth: 0,
  },
  autoResumeHeaderSpacer: {
    flex: 1,
    minWidth: spacing.xs,
  },
  autoResumeDetailPanel: {
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    borderRadius: radius.control,
    borderWidth: StyleSheet.hairlineWidth,
    marginHorizontal: spacing.xs,
    marginBottom: spacing.xs,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
  },
  autoResumeDetailLabel: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
  },
  autoResumeDetailText: {
    color: colors.textSecondary,
    fontFamily: monoFont,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
    marginTop: 2,
  },
  autoResumeDetailMeta: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.md,
  },
  autoResumeDetailMetaWithReason: {
    marginTop: spacing.sm,
  },
  autoResumeDetailMetaText: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
  },
  // ── agent-switch 分隔线 + 药丸(对齐桌面 AgentSwitchCard)────────────────
  agentSwitchWrap: {
    paddingVertical: spacing.sm,
  },
  agentSwitchRow: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.md,
  },
  agentSwitchDivider: {
    backgroundColor: colors.border,
    flex: 1,
    height: StyleSheet.hairlineWidth,
  },
  agentSwitchPill: {
    alignItems: 'center',
    borderColor: colors.border,
    borderRadius: radius.pill,
    borderWidth: StyleSheet.hairlineWidth,
    flexDirection: 'row',
    flexShrink: 1,
    gap: spacing.xs,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
  },
  agentSwitchPillText: {
    color: colors.textSecondary,
    fontSize: typeScale.micro,
    lineHeight: lineHeight.micro,
    fontWeight: fontWeight.medium,
  },
  // 分隔点:纯语义三级色,不再叠透明度「做淡」(§3 硬规则 1)。
  agentSwitchDot: {
    color: colors.textTertiary,
    fontSize: typeScale.micro,
    lineHeight: lineHeight.micro,
  },
  agentSwitchModel: {
    color: colors.textSecondary,
    flexShrink: 1,
    fontFamily: monoFont,
    fontSize: typeScale.micro,
    lineHeight: lineHeight.micro,
  },
  agentSwitchHandoffPanel: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    marginTop: spacing.sm,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  agentSwitchHandoffTitle: {
    color: colors.textTertiary,
    fontSize: typeScale.micro,
    lineHeight: lineHeight.micro,
    fontWeight: fontWeight.regular,
    marginBottom: spacing.xs,
  },
  agentSwitchHandoffText: {
    color: colors.textSecondary,
    fontFamily: monoFont,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
  },
  markdownBody: {},
  // 外链 / 会话深链等一切可点行内元素:**只有下划线**,不加粗、不换色、不换字体
  // (DESIGN.md §14.5;GitHub 的 `.markdown-body a` 同样只有 text-decoration)。
  //
  // 刻意**不写 color**:必须继承所在上下文的颜色。表头(markdownTableHeaderCell 用
  // textSecondary)、引用块等非正文色上下文里,写死 textPrimary 会让链接相对周围的
  // 不可点文本**除下划线之外还变色**,违反「可点态只多一条横线」(PR #1144 review 实捉)。
  markdownLink: {
    textDecorationLine: 'underline',
  },
  // 会话深链 chip(非 selectable 原生 Text 路径):嵌套 Text 只支持背景色不支持
  // 圆角,用 surfaceChip 底色近似 chip 观感;WebView 路径的 .xdt-session-chip
  // 才是完整圆角版本。
  //
  // 下划线**不再**关掉:会话 chip 是可点的,而「下划线常显 = 可点」是聊天正文的唯一
  // 交互信号(见 docs/design-rules/DESIGN.md「聊天正文的可点性信号」)。原先靠底色
  // 单独表达可点,但底色同时被行内 code 等排版语义占用,读者无法据此判断可点性。
  sessionLinkChipText: {
    backgroundColor: colors.surfaceChip,
  },
  // 对齐桌面聊天 markdown:<strong> 走浏览器默认 700,与 400 正文拉开明显对比。
  markdownStrong: { fontWeight: fontWeight.bold },
  markdownEmphasis: { fontStyle: 'italic' },
  // inline 公式:Unicode 近似文本以斜体呈现(数学正文的传统排版形态),
  // 与普通强调的区别只在语义,视觉上沿用 italic 已足够。
  markdownMathInline: { fontStyle: 'italic' },
  markdownStrike: { textDecorationLine: 'line-through' },
  markdownUnderlineStrike: { textDecorationLine: 'underline line-through' },
  // 行内 code:零底色 + 等宽字体 + 文字压暗(参照 Codex 客户端)。
  // 不给底色是平台约束:RN 嵌套在 Text 内的 inline 片段只认 backgroundColor,不认
  // borderRadius(同 sessionLinkChipText 的注释),底色在这里只能是直角方块,成段
  // 中文里一排方块比没有底色更糟。桌面走的是 GitHub 淡底 + 6px 圆角(CSS 能实现),
  // 两端形态刻意不同 —— 取值与理由见 chatInlineCodeText。
  markdownInlineCode: {
    color: colors.chatInlineCodeText,
    fontFamily: monoFont,
    fontSize: typeScale.bodySmall,
    lineHeight: lineHeight.bodySmall,
  },
  // 已验证存在的文件/目录路径 chip:**只加一条下划线,其它什么都不动**
  // (权威规则见 docs/design-rules/DESIGN.md §14.5,对齐 GitHub 的口径 ——
  // `.markdown-body code` 刻意不定义 color、纯靠继承,可点与不可点的行内 code
  // 差别只在那条横线)。
  //
  // 刻意**不**再写 color 与 fontWeight:本样式总是叠在 markdownInlineCode 之后,
  // 于是可点的行内 code 与不可点的行内 code 同色同字重,只差下划线 —— 差异越单一,
  // 「有横线 = 能点」这条规则越可信。早先这里钉 textPrimary + medium 是因为当时
  // 下划线还不是主信号,怕可点的比不可点的更淡;现在信号收敛到下划线,压暗是行内
  // code 的排版语义,继承它才是对的。
  markdownPathChip: {
    textDecorationLine: 'underline',
  },
  markdownInlineImage: {
    backgroundColor: colors.surfaceChip,
    borderRadius: radius.control,
  },
  markdownHeading: {
    color: colors.textPrimary,
    fontWeight: fontWeight.medium,
  },
  // 三档标题,行高刻意选到能与 desktop 的相对比例对齐(desktop 正文 15:h1 20/1.4、
  // h2 18/1.556、h3 16/1.5≈正文;mobile 正文 17):
  //   h1  20/28 = 1.400  ← 与 desktop h1 的 1.4 相同
  //   h2  18/28 = 1.556  ← 与 desktop h2 的 1.556 相同
  //   h3+ 17/26          ← 与正文同字号,靠 medium 区分(同 desktop 让 h3 贴近正文)
  // 20/28 与 18/28 都是 lineHeight 阶梯里既有的 listTitle 配对,未扩档。
  // 改前 h1/h2 都是 bodyLarge(17)=正文字号、h3-h6 是 caption(12)——标题比正文还小。
  markdownHeadingLarge: {
    fontSize: typeScale.title,
    lineHeight: lineHeight.listTitle,
  },
  markdownHeadingMedium: {
    fontSize: typeScale.subtitle,
    lineHeight: lineHeight.listTitle,
  },
  markdownHeadingSmall: {
    fontSize: typeScale.bodyLarge,
    lineHeight: lineHeight.bodyLarge,
  },
  // 竖线对齐本文件 styles.rail(chatCodeBorder + 2px)——界面里「块引导竖线」是
  // 一套统一的视觉语言,淡是设计意图;引用块不另搞一套(desktop 侧同样跟随
  // --agent-actions-rail)。
  markdownQuote: {
    borderLeftColor: colors.chatCodeBorder,
    borderLeftWidth: 2,
    paddingLeft: spacing.sm,
  },
  // 引用正文与正文同色:textSecondary 对 surface 仅 3.1:1(light)/ 3.4:1(dark),
  // 低于 WCAG AA 4.5:1,而 `>` 常承载本轮最该看的内容 —— 这是引用块唯一要修的
  // 问题。「这是引用」由 rail + 内缩表达,不靠压低正文对比度。
  markdownQuoteText: {
    color: colors.textPrimary,
  },
  markdownListRow: { flexDirection: 'row', gap: spacing.sm },
  // text_run 合并树里的列表 marker 前缀(不占固定列宽,颜色与原 marker 一致)。
  markdownListMarkerInline: {
    color: colors.textPrimary,
  },
  // 编号/项目符号与列表项正文同色(对齐 desktop 的 list-decimal / list-disc:
  // 那边 marker 本就继承正文色)。编号在实际使用中承担段落引导,弱化到
  // 3.1:1 会让扫读整段丢失。
  markdownListMarker: {
    color: colors.textPrimary,
    fontSize: typeScale.bodyLarge,
    lineHeight: lineHeight.bodyLarge,
    textAlign: 'right',
    width: 24,
  },
  markdownTaskMarker: {
    borderColor: colors.borderStrong,
    borderRadius: radius.micro,
    borderWidth: StyleSheet.hairlineWidth,
    fontSize: typeScale.micro,
    lineHeight: lineHeight.micro,
    marginTop: 3,
    minHeight: 16,
    overflow: 'hidden',
    textAlign: 'center',
    width: 16,
  },
  markdownListText: { flex: 1 },
  markdownCodeFrame: {
    alignSelf: 'stretch',
    backgroundColor: colors.chatCodeSurface,
    borderColor: colors.chatCodeBorder,
    borderWidth: StyleSheet.hairlineWidth,
    borderRadius: radius.container,
    maxWidth: '100%',
    minWidth: 0,
    overflow: 'hidden',
  },
  markdownCodeContent: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  markdownCodeText: {
    color: colors.textPrimary,
    flexShrink: 1,
    fontFamily: monoFont,
    fontSize: typeScale.bodySmall,
    lineHeight: lineHeight.bodySmall,
    maxWidth: '100%',
  },
  // 语法着色:只上 color,其余(字体/字号/行高)继承 markdownCodeText —— 嵌套 Text
  // 只支持有限样式,且改字号会让同一行的 token 高低不齐。
  syntaxKeyword: { color: colors.syntaxKeyword },
  syntaxString: { color: colors.syntaxString },
  syntaxComment: { color: colors.syntaxComment },
  syntaxNumber: { color: colors.syntaxNumber },
  syntaxFunction: { color: colors.syntaxFunction },
  syntaxProperty: { color: colors.syntaxProperty },
  markdownTableScroll: {
    maxWidth: '100%',
  },
  markdownTable: {
    borderColor: colors.border,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    overflow: 'hidden',
  },
  markdownTableRow: {
    flexDirection: 'row',
  },
  markdownTableHeaderRow: {
    backgroundColor: colors.surfaceElevated,
  },
  markdownTableCell: {
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderRightColor: colors.border,
    borderRightWidth: StyleSheet.hairlineWidth,
    color: colors.textPrimary,
    flexShrink: 0,
    fontSize: typeScale.bodySmall,
    lineHeight: lineHeight.bodySmall,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
  },
  markdownTableHeaderCell: {
    color: colors.textSecondary,
    fontWeight: fontWeight.medium,
  },
  detailText: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
  italicText: { fontStyle: 'italic' },
  thinkingStrong: { fontWeight: fontWeight.medium },
  thinkingCode: { fontFamily: monoFont, fontStyle: 'normal' },
  attachmentStrip: { gap: spacing.sm, marginBottom: spacing.xs, maxWidth: '100%' },
  attachmentStripLeft: { alignItems: 'flex-start' },
  attachmentStripRight: { alignItems: 'flex-end' },
  attachmentFileColumn: { gap: spacing.xs, maxWidth: '100%' },
  attachmentFileColumnRight: { alignItems: 'flex-end' },
  attachmentImageWrap: { borderRadius: radius.container, overflow: 'hidden' },
  attachmentImage: { borderRadius: radius.container },
  attachmentImagePending: { backgroundColor: colors.surfaceChip, borderRadius: radius.container },
  attachmentImageFallback: {
    alignItems: 'center',
    gap: 2,
    justifyContent: 'center',
    padding: spacing.sm,
  },
  // tool 产出媒体独立块:agent 侧左对齐,逐个竖排(图片 attachment 帧自带圆角)。
  toolMediaBlock: { alignItems: 'flex-start', maxWidth: '100%' },
  imagePreviewWrap: {
    backgroundColor: colors.surfaceChip,
    borderRadius: radius.container,
    overflow: 'hidden',
    width: 148,
  },
  imagePreview: { height: 96, width: 148 },
  imagePreviewFallback: {
    gap: 2,
    justifyContent: 'center',
    padding: spacing.sm,
  },
  mediaPlaceholder: {
    backgroundColor: colors.chatCodeSurface,
    borderColor: colors.chatCodeBorder,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    gap: 2,
    minHeight: 86,
    padding: spacing.sm,
    width: 160,
  },
  mediaKind: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular },
  mediaTitle: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
  mediaHint: { color: colors.textSecondary, fontSize: typeScale.caption, lineHeight: lineHeight.micro },
  fileChip: {
    alignItems: 'center',
    backgroundColor: colors.surfaceChip,
    borderRadius: radius.pill,
    flexDirection: 'row',
    gap: spacing.xs,
    maxWidth: '100%',
    minHeight: 32,
    paddingHorizontal: spacing.sm,
  },
  fileIconFrame: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  // Basis auto, not `flex: 1`: a content-sized chip (left-aligned strip, group wrapper) would give the name zero width.
  fileText: { flexGrow: 1, flexShrink: 1, minWidth: 0 },
  fileName: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
  diffCard: {
    backgroundColor: colors.chatCodeSurface,
    borderColor: colors.chatCodeBorder,
    borderWidth: StyleSheet.hairlineWidth,
    borderRadius: radius.container,
    gap: spacing.xs,
    padding: spacing.sm,
  },
  diffPath: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
  diffStats: { color: colors.textSecondary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
  diffRows: { gap: 2 },
  diffLine: { fontSize: typeScale.caption, lineHeight: lineHeight.micro },
  diffDelete: { color: colors.textSecondary },
  diffAdd: { color: colors.textPrimary, fontWeight: fontWeight.medium },
  diffMore: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
  messageActionBar: {
    alignItems: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 2,
    marginTop: 0,
  },
  // Keep the row occupied while a reply streams so completion controls can appear
  // without changing the message's measured height in the middle of a turn.
  messageActionSlot: { minHeight: MESSAGE_CONTROL_TOUCH_SIZE },
  userMessageActionBar: { justifyContent: 'flex-end' },
  agentMessageActionBar: { justifyContent: 'flex-start' },
  messageIconAction: {
    alignItems: 'center',
    borderRadius: radius.pill,
    height: 24,
    justifyContent: 'center',
    width: 24,
  },
  messageIconActionTouchTarget: {
    minHeight: MESSAGE_CONTROL_TOUCH_SIZE,
    minWidth: MESSAGE_CONTROL_TOUCH_SIZE,
  },
  messageActionMeta: {
    alignSelf: 'center',
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.bodyRelaxed,
  },
  foldPlain: { alignSelf: 'stretch' },
  foldCard: {
    alignSelf: 'stretch',
    backgroundColor: colors.chatCodeSurface,
    borderColor: colors.chatCodeBorder,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    overflow: 'hidden',
  },
  // 空 body 协同卡的静态表头(无 chevron、无折叠)。
  orcaStaticHeader: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: 8,
    paddingHorizontal: 12,
    paddingVertical: 10,
  },
  foldHeader: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.sm,
    minHeight: 40,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  foldHeaderPlain: {
    gap: 6,
    minHeight: 22,
    paddingHorizontal: 0,
    paddingVertical: 2,
  },
  pressed: { opacity: 0.72 },
  disabled: { opacity: 0.42 },
  scrollToBottomFab: {
    alignItems: 'center',
    backgroundColor: colors.surfaceTranslucent,
    borderColor: colors.borderTranslucent,
    borderRadius: radius.pill,
    borderWidth: StyleSheet.hairlineWidth,
    height: SCROLL_TO_BOTTOM_FAB_SIZE,
    justifyContent: 'center',
    position: 'absolute',
    width: SCROLL_TO_BOTTOM_FAB_SIZE,
    zIndex: 20,
  },
  scrollToBottomDot: {
    backgroundColor: colors.cta,
    borderRadius: radius.pill,
    height: 8,
    position: 'absolute',
    right: 3,
    top: 3,
    width: 8,
  },

  forkOriginRow: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.md,
    paddingVertical: spacing.sm,
  },
  forkOriginLine: {
    backgroundColor: colors.border,
    flex: 1,
    height: StyleSheet.hairlineWidth,
  },
  forkOriginButton: {
    alignItems: 'center',
    borderRadius: radius.pill,
    flexDirection: 'row',
    gap: spacing.xs,
    minHeight: 30,
    paddingHorizontal: spacing.sm,
  },
  forkOriginText: {
    color: colors.textSecondary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
  },
  loadEarlierButton: {
    alignItems: 'center',
    alignSelf: 'center',
    borderRadius: radius.pill,
    minHeight: 32,
    justifyContent: 'center',
    paddingHorizontal: spacing.md,
  },
  loadEarlierText: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular },
  foldText: { flex: 1, minWidth: 0 },
  foldTitle: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
  foldTitlePlain: {
    color: colors.textSecondary,
    fontSize: typeScale.bodySmall,
    fontWeight: fontWeight.regular,
    lineHeight: lineHeight.bodySmall,
  },
  foldSubtitle: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, marginTop: 2 },
  foldBody: { paddingHorizontal: spacing.md, paddingBottom: spacing.md },
  foldBodyPlain: {
    paddingBottom: 0,
    paddingHorizontal: 0,
    paddingTop: spacing.xs,
  },
  rail: {
    borderLeftColor: colors.chatCodeBorder,
    borderLeftWidth: 2,
    paddingLeft: spacing.md,
  },
  stack: { gap: spacing.md },
  stackSmall: { gap: spacing.sm },
  workActivityStack: { gap: 0 },
  // thinking 与 tool group 都由内部 28pt 行高控制;外层不再追加组间距,
  // 否则每段 thinking 前后会比连续工具行多出 8pt,视觉节奏不一致。
  workGroupStack: { gap: 0 },
  workGroupElapsed: {
    color: colors.textTertiary,
    fontFamily: monoFont,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
  },
  workThinkingRow: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: 6,
    minHeight: 28,
    paddingHorizontal: spacing.sm,
    paddingVertical: 2,
  },
  workThinkingRowExpanded: { alignItems: 'flex-start' },
  workThinkingText: { flex: 1, minWidth: 0 },
  workActivityText: {
    color: colors.textSecondary,
    fontSize: typeScale.bodySmall,
    lineHeight: lineHeight.bodySmall,
  },
  workThinkingMeasureWrap: {
    left: 0,
    opacity: 0,
    position: 'absolute',
    right: 0,
    top: 0,
  },
  toolRow: {
    gap: spacing.xs,
  },
  toolRowHeader: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: 6,
    minHeight: 28,
    paddingHorizontal: spacing.sm,
    paddingVertical: 2,
  },
  toolRowDetails: {
    gap: spacing.xs,
    marginBottom: spacing.xs,
    marginHorizontal: spacing.sm,
  },
  toolRowDetailText: {
    color: colors.textSecondary,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
  },
  imageDeliveryHint: {
    color: colors.textSecondary, fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption, fontWeight: fontWeight.regular,
  },
  imageDeliveryRetry: { minHeight: 44, justifyContent: 'center', alignSelf: 'flex-start', paddingHorizontal: spacing.sm },
  imageDeliveryRetryText: {
    color: colors.textPrimary, fontSize: typeScale.body,
    lineHeight: lineHeight.body, fontWeight: fontWeight.medium,
  },
  toolInputPreview: {
    backgroundColor: colors.chatCodeSurface,
    borderColor: colors.chatCodeBorder,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
  },
  toolInputActionRow: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.sm,
    minHeight: MESSAGE_CONTROL_TOUCH_SIZE,
    paddingHorizontal: spacing.sm,
  },
  toolInputActionText: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    fontWeight: fontWeight.regular,
    lineHeight: lineHeight.caption,
  },
  toolName: {
    color: colors.textSecondary,
    fontSize: typeScale.bodySmall,
    fontWeight: fontWeight.regular,
    lineHeight: lineHeight.bodySmall,
  },
  toolNameFlex: { flex: 1, minWidth: 0 },
  toolResult: {
    backgroundColor: colors.chatCodeSurface,
    borderColor: colors.chatCodeBorder,
    borderWidth: StyleSheet.hairlineWidth,
    borderRadius: radius.container,
    color: colors.textSecondary,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
    padding: spacing.sm,
  },
  toolResultPreview: {
    backgroundColor: colors.chatCodeSurface,
    borderColor: colors.chatCodeBorder,
    borderWidth: StyleSheet.hairlineWidth,
    borderRadius: radius.container,
    gap: spacing.xs,
  },
  toolResultHint: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
    paddingBottom: spacing.sm,
    paddingHorizontal: spacing.sm,
  },
  payloadModal: {
    backgroundColor: colors.surface,
    flex: 1,
  },
  // alignItems / minHeight 由 headerLayout 按横竖屏注入(横屏紧凑单行)。
  payloadHeader: {
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    paddingVertical: spacing.md,
  },
  payloadHeaderText: { flex: 1, minWidth: 0 },
  // 面板大标题:§3 20/25 · 600。
  payloadTitle: { color: colors.textPrimary, fontSize: typeScale.title, fontWeight: fontWeight.semibold, lineHeight: lineHeight.title },
  payloadGalleryCount: {
    color: colors.textSecondary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
    marginTop: 2,
  },
  payloadHeaderActions: {
    flexShrink: 0,
    gap: spacing.xs,
  },
  payloadHeaderPrimaryActions: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  payloadHeaderButton: {
    alignItems: 'center',
    borderColor: colors.border,
    borderRadius: radius.pill,
    borderWidth: StyleSheet.hairlineWidth,
    height: 36,
    justifyContent: 'center',
    minHeight: 36,
    width: 36,
  },
  payloadHeaderStatus: {
    color: colors.textSecondary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
  },
  payloadCloseButton: {
    alignItems: 'center',
    borderColor: colors.border,
    borderRadius: radius.pill,
    borderWidth: StyleSheet.hairlineWidth,
    height: 40,
    minHeight: 40,
    justifyContent: 'center',
    width: 40,
  },
  payloadCloseText: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
  payloadViewerBody: {
    flex: 1,
    minHeight: 0,
  },
  payloadBody: { flex: 1 },
  payloadScroll: {
    borderTopColor: colors.border,
    borderTopWidth: StyleSheet.hairlineWidth,
    // 空间不足(典型:横屏)时源码区让位给上方主体(图表/播放器),自身滚动兜底。
    flexShrink: 1,
    maxHeight: 220,
  },
  // 沉浸式 mermaid 查看器的浮动操作区(复制/关闭),悬于图表右上角。
  payloadFloatingActions: {
    flexDirection: 'row',
    gap: spacing.sm,
    position: 'absolute',
  },
  // 浮动按钮需要实底色,否则悬在图表线条上看不清。
  payloadFloatingButton: {
    backgroundColor: colors.surface,
  },
  payloadScrollContent: {
    padding: spacing.lg,
  },
  payloadText: { color: colors.textPrimary, fontSize: typeScale.bodyLarge, lineHeight: lineHeight.bodyLarge },
  payloadMonoText: { fontFamily: monoFont, fontSize: typeScale.footnote, lineHeight: lineHeight.bodySmall },
  payloadDiffHeaderBlock: {
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    gap: spacing.xs,
    padding: spacing.lg,
  },
  payloadDiffPath: {
    color: colors.textPrimary,
    fontSize: typeScale.body,
    fontWeight: fontWeight.medium,
    lineHeight: lineHeight.body,
  },
  payloadDiffStats: {
    color: colors.textSecondary,
    fontFamily: monoFont,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.bodySmall,
  },
  payloadDiffFilePreviewBlock: {
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    gap: spacing.sm,
    padding: spacing.lg,
  },
  payloadDiffFilePreviewScroll: {
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    maxHeight: 220,
  },
  payloadDiffScroll: {
    flex: 1,
  },
  payloadDiffContent: {
    gap: spacing.lg,
    padding: spacing.lg,
  },
  payloadDiffSection: {
    gap: spacing.sm,
  },
  payloadDiffCompareScroll: {
    width: '100%',
  },
  payloadDiffSectionTitle: {
    color: colors.textTertiary,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.semibold,
    textTransform: 'uppercase',
  },
  payloadDiffCompareRow: {
    flexDirection: 'row',
    gap: spacing.md,
    paddingBottom: spacing.xs,
  },
  payloadDiffPane: {
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    overflow: 'hidden',
    width: 320,
  },
  payloadDiffPaneHeader: {
    backgroundColor: colors.surfaceChip,
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  payloadDiffPaneTitle: {
    color: colors.textPrimary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.medium,
  },
  payloadDiffPaneBody: {
    paddingVertical: spacing.xs,
  },
  payloadDiffCompareLine: {
    alignItems: 'flex-start',
    flexDirection: 'row',
    minHeight: 24,
    paddingHorizontal: spacing.sm,
    paddingVertical: 2,
  },
  payloadDiffCompareLineOld: {
    backgroundColor: colors.surfaceElevated,
  },
  payloadDiffCompareLineNew: {
    backgroundColor: colors.surface,
  },
  payloadDiffLineNumber: {
    color: colors.textTertiary,
    fontFamily: monoFont,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.bodySmall,
    marginRight: spacing.sm,
    textAlign: 'right',
    width: 34,
  },
  payloadDiffLinePrefix: {
    fontFamily: monoFont,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.bodySmall,
    marginRight: spacing.sm,
    textAlign: 'center',
    width: 14,
  },
  payloadDiffLinePrefixOld: {
    color: colors.textSecondary,
  },
  payloadDiffLinePrefixNew: {
    color: colors.textPrimary,
    fontWeight: fontWeight.medium,
  },
  payloadDiffLineText: {
    flex: 1,
    fontFamily: monoFont,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.bodySmall,
  },
  payloadDiffLineTextOld: {
    color: colors.textSecondary,
    textDecorationLine: 'line-through',
  },
  payloadDiffLineTextNew: {
    color: colors.textPrimary,
    fontWeight: fontWeight.medium,
  },
  payloadDiffEmptyLine: {
    color: colors.textTertiary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.bodySmall,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.md,
  },
  payloadMediaPlayerFrame: {
    backgroundColor: colors.surfaceChip,
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    minHeight: 300,
    width: '100%',
  },
  payloadMediaPlayer: {
    flex: 1,
    minHeight: 260,
    width: '100%',
  },
  payloadMediaPlayerStatus: {
    color: colors.textSecondary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.sm,
    textAlign: 'center',
  },
  payloadMediaPlaceholder: {
    alignItems: 'center',
    backgroundColor: colors.surfaceElevated,
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    gap: spacing.sm,
    justifyContent: 'center',
    minHeight: 260,
    padding: spacing.xl,
  },
  payloadMediaKind: { color: colors.textPrimary, fontSize: typeScale.title, lineHeight: lineHeight.title, fontWeight: fontWeight.medium },
  payloadMediaHint: { color: colors.textSecondary, fontSize: typeScale.body, lineHeight: lineHeight.body, textAlign: 'center' },
  payloadActionBlock: {
    alignItems: 'center',
    gap: spacing.xs,
    width: '100%',
  },
  payloadActionRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.sm,
    justifyContent: 'center',
  },
  payloadOpenButton: {
    alignItems: 'center',
    borderColor: colors.border,
    borderRadius: radius.pill,
    borderWidth: StyleSheet.hairlineWidth,
    justifyContent: 'center',
    minHeight: 38,
    paddingHorizontal: spacing.lg,
  },
  payloadOpenButtonText: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
  payloadPathCopyStatus: {
    color: colors.textSecondary,
    fontSize: typeScale.caption,
    lineHeight: lineHeight.caption,
    textAlign: 'center',
  },
  todoRow: { alignItems: 'center', flexDirection: 'row', gap: spacing.sm, minHeight: 32 },
  todoRowPending: { opacity: 0.72 },
  todoMark: { alignItems: 'center', justifyContent: 'center', width: 22 },
  todoCopy: { flex: 1, minWidth: 0 },
  todoText: { color: colors.textPrimary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall },
  todoPending: { color: colors.textTertiary },
  todoDone: { fontWeight: fontWeight.medium },
});

export function MarkdownBody(props: Parameters<typeof MarkdownBodyBase>[0]) {
  const instanceKey = useId();
  const origin = useContext(ChatFilePathContext);
  const renderMedia = (node: RichNode) => <RichAnswerMedia node={node} body={props} />;
  const parts = useMemo(() => props.renderRichAnswers ? splitRichAnswer(props.text) : [], [props.text, props.renderRichAnswers]);
  if (!parts.some(part => part.kind === 'rich')) return <MarkdownBodyBase {...props} />;
  return <View style={{ gap: spacing.lg }}>{parts.map(part => part.kind === 'rich'
    ? <RichAnswer renderMedia={renderMedia} key={part.key} source={part.source} complete={part.complete || !props.streaming}
        stateKey={`${origin?.deviceId ?? ''}:${origin?.sessionId ?? ''}:${props.richStateKey ?? props.markdownImageCacheKey ?? instanceKey}:${part.key}`}
        renderMarkdown={(text, id) => <MarkdownBodyBase {...props} text={text} markdownImageCacheKey={`${props.markdownImageCacheKey}:${part.key}:${id}`} />} />
    : <MarkdownBodyBase {...props} key={part.key} text={part.source} streaming={!part.complete && props.streaming} />)}</View>;
}

/** Each composed column supplies its actual width; media never assumes a full message row. */
function RichAnswerMedia({ node, body }: { node: RichNode; body: Parameters<typeof MarkdownBodyBase>[0] }) {
  const origin = useContext(ChatFilePathContext);
  const resolver = useContext(MarkdownRemoteMediaContext);
  const visible = useContext(MessageHeavyContentVisibilityContext);
  const [width, setWidth] = useState(0);
  const raw = richMediaSource(node);
  if (!raw || (node.kind !== 'image' && node.kind !== 'video' && node.kind !== 'audio')) return null;
  if (node.kind === 'video' && youtubeVideo(raw)) return <VideoSitePreview src={raw} title={richString(node, 'alt', 'YouTube')} />;
  const direct = /^(?:https?|xdt-audio|xdt-video|cindy-media):\/\//.test(raw);
  const resolveUrl = node.kind === 'video' ? mobileMarkdownImageUrlForWorkdir : mobileMarkdownManagedImagePreviewUrl;
  const url = direct ? raw : resolveUrl(raw, origin?.workdir, body.markdownImageCacheKey, origin?.remoteHostId, origin?.sessionId);
  // Images outside workdir retain explicit-open. Video resolves only on explicit play.
  if (!url) return <MarkdownBodyBase {...body} text={richMarkdown(node) ?? ''} streaming={false} />;
  const label = richString(node, 'alt', node.kind);
  const media: NormalizedToolMedia = { kind: node.kind, url, title: label, previewable: isDirectPreviewableMediaUrl(url) };
  // Rich answers also render outside LegendList (cloud companions). Keep ordinary
  // state there, but remount the preview when a recycled row or streamed media
  // patch changes its identity, so resolved thumbnails/errors cannot cross images.
  const previewKey = JSON.stringify([origin?.deviceId, origin?.sessionId, body.richStateKey ?? body.markdownImageCacheKey, node.id, url]);
  const visual = richVisualStyle(node);
  const imageWidth = typeof visual.width === 'number' || typeof visual.width === 'string'
    ? width : Math.min(body.layout.imagePreviewWidth, width);
  const naturalFrameHeight = imageWidth * body.layout.imagePreviewHeight / body.layout.imagePreviewWidth;
  const imageHeight = Math.min(typeof visual.maxHeight === 'number' ? visual.maxHeight : Infinity,
    Math.max(typeof visual.minHeight === 'number' ? visual.minHeight : 0,
      typeof visual.height === 'number' ? visual.height : naturalFrameHeight));
  const layout = { ...body.layout, imagePreviewWidth: imageWidth,
    imagePreviewHeight: imageHeight,
    mediaPreviewWidth: Math.min(body.layout.mediaPreviewWidth, width) };
  return <View style={{ minWidth: 0 }} onLayout={event => setWidth(event.nativeEvent.layout.width)}>
    {width > 0 && node.kind === 'video' ? <InlineVideoPlayer key={previewKey} url={url} label={label}
      width={width} visible={visible} resolve={resolver} />
      : width > 0 ? <MediaPreview key={previewKey} layout={layout} media={media} label={label} onResolveRemoteMedia={resolver}
      usePreviewState={useState}
      onOpen={body.onOpenPayload ? () => body.onOpenPayload!(buildMediaPayload(media, label)) : undefined} /> : null}
  </View>;
}

function GeneratedImageRetry({ imageId, onRetry }: { imageId: string; onRetry?: (id: string) => Promise<void> }) {
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const [pending, setPending] = useState(false);
  const [failed, setFailed] = useState(false);
  return <View>
    <Text style={styles.imageDeliveryHint}>{t(failed ? 'chat:imageDelivery.retryFailed' : 'chat:imageDelivery.failed')}</Text>
    {onRetry && <Pressable accessibilityRole="button" disabled={pending} style={styles.imageDeliveryRetry} onPress={async () => {
      setPending(true); setFailed(false);
      try { await onRetry(imageId); } catch { setFailed(true); } finally { setPending(false); }
    }}><Text style={styles.imageDeliveryRetryText}>{t(pending ? 'chat:imageDelivery.retrying' : 'chat:imageDelivery.retry')}</Text></Pressable>}
  </View>;
}