sailfork / t3code-github / apps/ mobile/ src/ features/ threads/ ThreadFeed.tsx

import { Button } from "../../components/ui/Button";
import * as Dialog from "../../components/ui/Dialog";
import { useOpenPullRequest } from "../../native/useOpenPullRequest";
import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width";
import { ThreadMarkdownVideo, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
import {
  enrichedContextLinkCustomization,
  enrichedThreadLinkCustomization,
  withChipIcon,
} from "../../native/useEnrichedLinkVariants";
import {
  enrichedSkillDisplayName,
  enrichedSkillInstructionsPath,
  enrichedSkillReference,
} from "../../lib/enrichedLinkPresentation";
import { ThreadContextDivider } from "./thread-context-divider";
import {
  ThreadHandoffDivider,
  ThreadHandoffRow,
  ThreadModelSwitchDivider,
} from "./thread-handoff-row";
import { GuestBubbleTint, GuestMessageName } from "./guestMessageStyle";
import { ThreadGuestPendingMessage, useThreadGuestShare } from "./ThreadGuestShareBar";
import { LinkRequestCard } from "./LinkRequestCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import {
  WorktreeWorkingHeader,
  WorktreeSetupCard,
  type WorktreeSetupCardProps,
} from "./worktree-setup-card";
import * as Haptics from "expo-haptics";
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
import {
  IDLE_COMPACTING_LABELS,
  resolveUserMessageFileCards,
  resolveUserMessagePresentation,
} from "@t3tools/client-runtime/user-message";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
import {
  AuthFilesystemReadScope,
  idleCompactionOf,
  type OrchestrationMessageContext,
  ThreadId,
  type ChatAttachment,
  type ChatFileAttachment,
  type ChatImageAttachment,
  type EnvironmentId,
  type MessageId,
  type OrchestrationV2ProjectedTurnItem,
  type RunId,
  type ScheduledTaskId,
  type ScopedThreadRef,
} from "@t3tools/contracts";
import type { ToolCallVisibility } from "@t3tools/contracts/settings";
import { renderAssistantCitationsAsText } from "@t3tools/shared/assistantCitations";
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
import { hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks";
import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks";
import {
  parseComposerContextHref,
  collectComposerContextReferences,
  replaceComposerContextReferences,
  formatComposerContextReference,
} from "@t3tools/shared/composerContextReferences";
import { ComposerContextSheet } from "../../components/ComposerContextSheet";
import { writeComposerContextClipboard } from "../../lib/composerContextClipboard";
import {
  codexArtifactTemplatePresentationLabel,
  type CodexArtifactTemplate,
} from "@t3tools/shared/codexArtifactTemplates";
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
import {
  executeAtomQuery,
  settlePromise,
  squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import {
  classifyMarkdownImageSource,
  markdownImageSourceFragment,
} from "@t3tools/client-runtime/markdown-images";
import { resolveViewedImageAsset } from "@t3tools/client-runtime/work-log/presentation";
import {
  renderCodexInlineDirectivesAsMarkdown,
  splitCodexArtifactTemplateMarkdown,
} from "@t3tools/shared/codexMarkdownDirectives";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { imageMimeType } from "@t3tools/shared/image";
import { videoMimeType } from "@t3tools/shared/video";
import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
import { useFocusEffect, useNavigation } from "@react-navigation/native";
import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
import { useDeviceType } from "../../native/native-layout-metrics";
import { isDuoDevice } from "../../lib/device-type";
import {
  memo,
  useCallback,
  useEffect,
  useEffectEvent,
  useImperativeHandle,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  useSyncExternalStore,
  useId,
  type ComponentPropsWithRef,
  type ComponentRef,
  type ReactNode,
  type Ref,
  type RefObject,
} from "react";
import {
  Image,
  Platform,
  type LayoutChangeEvent,
  type NativeScrollEvent,
  type NativeSyntheticEvent,
  Pressable,
  StyleSheet,
  type ColorValue,
  useWindowDimensions,
  View,
} from "react-native";
import { Image as ExpoImage } from "expo-image";
import { useResolveClassNames } from "uniwind";
import { useReduceMotionEnabled } from "../../lib/appState";
import { useFilePreviewGallery, FilePreviewGallery } from "../../components/FilePreviewGallery";
import { assetImageSource } from "../../lib/assetImageSource";
import { composerImageGallery } from "../../lib/composerImageGallery";
import { isFileBackedComposerAttachment } from "../../lib/composerImages";
import { useLocalAttachmentPreview } from "../../lib/localAttachmentPreview";
import { messageImageGallery } from "./messageImageGallery";
import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
import { inlineFilePreviewKind, isPdfFile } from "../../lib/filePreview";
import { ThreadInlineFilePreview } from "./ThreadInlineFilePreview";
import { flattenThemeColor } from "../../lib/mobileTheme";
import { PresentationSource } from "../../components/ui/NativePresentation";
import { NativeScrollViewMarker } from "../../native/NativeScrollViewMarker";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, { FadeIn, FadeInDown, type SharedValue } from "react-native-reanimated";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { FONT_FAMILIES } from "../../lib/fontFamilies";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
import { splitMarkdownDetails } from "../../lib/markdownDetails";
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
import {
  SelectableMarkdownText,
  type MarkdownFileContextMenu,
  type MarkdownImageRenderer,
  type MarkdownImageSourceResolver,
  type MarkdownLinkCustomization,
  type NativeMarkdownTextStyle,
  type SelectableMarkdownSkill,
} from "../../native/SelectableMarkdownText";

import { AppText as Text } from "../../components/ui/AppText";
import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
import { attachmentVideoPreviewSource } from "../../lib/videoPreviewSource";
import { CopyTextButton } from "./CopyTextButton";
import { getReviewSectionIdForCheckpoint } from "../review/reviewModel";
import { setReviewSelectedSectionId } from "../review/reviewState";
import { Menu } from "../../components/ui/Menu";
import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
import { useBarInset } from "../../components/ui/useBarInset";
import { copyPromptLink } from "../prompt-links/prompt-link-actions";
import { parseReviewCommentMessageSegments } from "../review/reviewCommentSelection";
import {
  ReviewCommentCard,
  useReviewCommentColors,
  type ReviewCommentColors,
} from "../review/ReviewCommentCard";
import { cn } from "../../lib/cn";
import {
  deriveCenteredContentHorizontalPadding,
  deriveThreadFeedInitialContentInset,
  deriveThreadWorkLogSizing,
  type LayoutVariant,
} from "../../lib/layout";
import { uuidv4 } from "../../lib/uuid";
import { resolveNativeMarkdownTypography } from "../../lib/appearancePreferences";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
import {
  normalizeNativeMarkdownUrl,
  resolveMarkdownLinkPresentation,
} from "../../lib/markdownLinks";
import {
  createThreadFeedCache,
  threadFeedCompactionLabels,
  failedFeedRunIds,
  deriveThreadFeedPresentation,
  threadFeedRunIsUnsettled,
  isContextCompactionActivityGroup,
  isContextHandoffActivityGroup,
  isLinkRequestActivityGroup,
  isSecretRequestActivityGroup,
  type ThreadFeedEntry,
  type ThreadFeedLatestRun,
  messageFoldRunId,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import {
  resolveThreadFeedLiveFollow,
  resolveThreadFeedReflowAnchor,
  resolveThreadFeedReflowOffset,
  resolveThreadFeedReflowScroll,
  type ThreadFeedLiveFollowEvent,
  type ThreadFeedReflowAnchor,
  type ThreadWorkGroupScrollPosition,
} from "./thread-feed-live-follow";
import {
  collapsedWorkLogHeight,
  ThreadDisclosureChevron,
  THREAD_DISCLOSURE_TRANSITION_MS,
  ThreadWorkGroupToggle,
  ThreadThinkingRow,
  ThreadWorkLog,
  WORK_GROUP_TOGGLE_HEIGHT,
} from "./thread-work-log";
import {
  appendGuestPendingMessages,
  appendPendingThreadMessages,
  createThreadFeedGrouping,
  isCompactionCommandFeedEntry,
  type GroupedThreadFeedRow,
  type ThreadFeedRow,
} from "./pending-thread-feed";
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size";
import { htmlRenderFrameHeight } from "@t3tools/shared/htmlRender";
import { htmlRenderRowHeight, ThreadHtmlRender } from "./HtmlRenderWebView";
import { ThreadMcpApp } from "./McpAppWebView";
import { assetEnvironment, useAssetUrl, useRefreshAssetUrl } from "../../state/assets";
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import { readEnvironmentScope, usePreparedConnection } from "../../state/session";
import { projectEnvironment } from "../../state/projects";
import {
  needsWorkspaceBasenameLookup,
  pickWorkspaceBasenameMatch,
  WORKSPACE_BASENAME_LOOKUP_LIMIT,
} from "@t3tools/client-runtime/workspace-basename-lookup";
import {
  resolveThreadLink,
  useLiveThreadLinkLabels,
  useQuietThreadShell,
  useThreadChipIcons,
} from "../../state/entities";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { composerDocumentAttachmentRecord } from "../../lib/composerContext";
import * as Option from "effect/Option";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { ThreadWorkflowOpening, useWorkflowOpening } from "./thread-workflow-opening";
import { useAtomCommand } from "../../state/use-atom-command";
import { useV2ItemSupport } from "../../state/v2-item-support";
import {
  fileRoutePathSegments,
  resolveFileLinkPath,
  resolveWorkspaceFilePath,
  resolveWorkspaceRelativeFilePath,
} from "../files/filePath";
import { waitForThreadShell } from "./threadForkNavigation";
import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
import { fileChipClipboardPath, fileChipMenu, resolveFileChipTarget } from "./fileChipMenu";
import { useFileChipShare } from "./useFileChipShare";
import { useOpenLinkedThread } from "./useOpenLinkedThread";
import {
  MarkdownImageAvailableWidthContext,
  ThreadMarkdownImage,
  ThreadMarkdownImageUnavailable,
  ThreadMarkdownImageView,
} from "./ThreadMarkdownImage";
import { openSettings } from "../settings/settings-navigation";
import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";

const WIDE_MARKDOWN_BLOCK_OPTIONS = {
  // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width.
  includeBlockquotes: Platform.OS === "ios",
  includeOrderedLists: Platform.OS === "android",
} as const;

const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
  hour: "numeric",
  minute: "2-digit",
});
function formatMessageTime(input: string): string {
  const timestamp = Date.parse(input);
  if (Number.isNaN(timestamp)) {
    return "";
  }
  return MESSAGE_TIME_FORMATTER.format(timestamp);
}

const TURN_FOLD_HEIGHT = 42;
const FEED_PADDING_TOP = 12;
// Rows re-measure within a commit or two of a width change. LegendList also defers imperative
// scrolls for 100ms after it compensates a size change, and a deferred restore could land
// under a drag that starts meanwhile.
const FEED_REFLOW_SETTLE_MS = 200;
// A fold resizes the feed in steps about 200ms apart. Holding the place taken at the first step
// across all of them keeps a passing moment off the end from re-anchoring the rest to a row.
const FEED_REFLOW_HOLD_MS = 600;
const USER_BUBBLE_HORIZONTAL_PADDING = 3.5 * 3.5;
const ASSISTANT_ROW_HORIZONTAL_PADDING = 3.5;

// Virtualization remounts old rows; only newly created content should replay an entrance.
const FRESH_ENTRY_WINDOW_MS = 3_000;
function isFreshTimestamp(input: string): boolean {
  const timestamp = Date.parse(input);
  return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS;
}

export interface ThreadFeedHistoryControls {
  readonly hasMoreHistory: boolean;
  readonly loading: boolean;
  readonly error: string | null;
  readonly onLoadEarlier: () => void;
  /** Loads earlier history down to the entry, in one request. */
  readonly onLoadThrough: (entryId: string) => void;
}

export interface ThreadFeedHandle {
  /** A send re-arms following the end, whatever the reader had scrolled to. */
  readonly resetEndFollow: () => void;
}

export interface ThreadFeedProps {
  readonly toolCallVisibility?: ToolCallVisibility;
  readonly worktreeSetup?: WorktreeSetupCardProps | null;
  readonly setupWorkingStartedAt?: string | null;
  readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
  readonly dispatchingMessageId: MessageId | null;
  readonly onEditPendingMessage: ((message: QueuedThreadMessage) => void) | null;
  readonly environmentId: EnvironmentId;
  readonly threadId: ThreadId;
  /** Null while the thread's creation is queued: reading detail then caches a not-found as deleted. */
  readonly detailRef: ScopedThreadRef | null;
  readonly threadTitle: string;
  readonly workspaceRoot?: string | null;
  readonly feed: ReadonlyArray<ThreadFeedEntry>;
  readonly pendingHandoff?: HandoffEndpoints | null;
  readonly contentPresentation: ThreadContentPresentation;
  readonly latestRun: ThreadFeedLatestRun | null;
  readonly activeWorkStartedAt: string | null;
  readonly runlessWorkActive?: boolean;
  readonly listRef: RefObject<LegendListRef | null>;
  readonly freeze: SharedValue<boolean>;
  readonly anchorMessageId: MessageId | null;
  /** A message to scroll to once it is in the feed; see `onJumpedToMessage`. */
  readonly jumpToMessageId?: MessageId | null;
  readonly onJumpedToMessage?: () => void;
  readonly contentInsetEndAdjustment: SharedValue<number>;
  readonly keyboardOffset: number;
  readonly sendingWithKeyboard?: boolean;
  readonly fitShortFeedToViewport?: boolean;
  readonly contentTopInset?: number;
  readonly contentBottomInset?: number;
  readonly historyControls?: ThreadFeedHistoryControls;
  readonly contentMaxWidth?: number;
  readonly contentSideInsets?: { readonly left: number; readonly right: number };
  readonly layoutVariant?: LayoutVariant;
  readonly usesAutomaticContentInsets?: boolean;
  readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
  readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
  readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
  readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
}

const USER_MESSAGE_COPY_MENU_ACTIONS = [
  { id: "copy-prompt-link", title: "Copy prompt link", image: "link" },
];

function UserMessageCopyButton(props: {
  readonly text: string;
  readonly onCopy: (() => Promise<void>) | undefined;
  readonly tintColor: ColorValue;
}) {
  const button = (
    <CopyTextButton
      accessibilityLabel="Copy message"
      text={props.text}
      onCopy={props.onCopy}
      tintColor={props.tintColor}
      buttonSize={28}
      iconSize={13}
    />
  );
  const linkText = replaceComposerContextReferences(props.text, (reference) => reference.label);
  if (linkText.length > PROMPT_LINK_MAX_PROMPT_LENGTH) return button;
  return (
    <Menu
      actions={USER_MESSAGE_COPY_MENU_ACTIONS}
      onPressAction={({ nativeEvent }) => {
        if (nativeEvent.event === "copy-prompt-link") void copyPromptLink(linkText);
      }}
      shouldOpenOnLongPress
    >
      {button}
    </Menu>
  );
}

function AssistantForkButton(props: {
  readonly environmentId: EnvironmentId;
  readonly iconColor: ColorValue;
  readonly buttonSize: number;
  readonly iconSize: number;
  readonly projectedItem: OrchestrationV2ProjectedTurnItem;
  readonly sourceTitle: string;
}) {
  const support = useV2ItemSupport({
    environmentId: props.environmentId,
    sourceThreadId: props.projectedItem.sourceThreadId,
    sourceItemId: props.projectedItem.sourceItemId,
  });
  const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
  const selectDetail = useSelectWorkspaceDetail();
  const [busy, setBusy] = useState(false);
  const canFork = canForkProjectedAssistantItem({
    projectedItem: props.projectedItem,
    capabilities: support.providerSession?.capabilities,
  });
  const runId = props.projectedItem.item.runId;

  if (!canFork || runId === null) return null;

  return (
    <Pressable
      accessibilityRole="button"
      accessibilityLabel="Fork from this response"
      disabled={busy}
      onPress={() => {
        const targetThreadId = ThreadId.make(uuidv4());
        setBusy(true);
        void Haptics.selectionAsync();
        void forkFromRun({
          environmentId: props.environmentId,
          input: {
            sourceThreadId: props.projectedItem.sourceThreadId,
            targetThreadId,
            runId,
            title: `${props.sourceTitle} fork`,
            creationSource: "mobile",
          },
        })
          .then(async (result) => {
            if (result._tag !== "Success") return;
            const targetThreadReady = await waitForThreadShell(
              scopeThreadRef(props.environmentId, targetThreadId),
            );
            if (!targetThreadReady) {
              Dialog.alert(
                "Fork created",
                "Its thread data did not reach this client. Reconnect and try opening it from the thread list.",
              );
              return;
            }
            selectDetail({
              name: "Thread",
              params: { environmentId: props.environmentId, threadId: targetThreadId },
            });
          })
          .finally(() => setBusy(false));
      }}
      className="h-7 w-7 items-center justify-center disabled:opacity-40"
      style={
        Platform.OS === "android"
          ? { width: props.buttonSize, height: props.buttonSize }
          : undefined
      }
    >
      {busy ? (
        <AppActivityIndicator size="small" />
      ) : (
        <SymbolView
          name="arrow.triangle.branch"
          size={props.iconSize}
          tintColor={props.iconColor}
          type="monochrome"
        />
      )}
    </Pressable>
  );
}

function MessageImage(props: {
  readonly source: ComponentPropsWithRef<typeof ExpoImage>["source"];
  readonly className: string;
  readonly maxWidth?: number;
  readonly height?: number;
  readonly onLoad?: () => void;
  readonly onError?: () => void;
}) {
  const imageStyle = useResolveClassNames(props.className);
  const [size, setSize] = useState<{ width: number; height: number } | null>(null);
  const displaySize =
    props.maxWidth !== undefined && size !== null
      ? resolveMarkdownImageDisplaySize({
          sourceWidth: size.width,
          sourceHeight: size.height,
          availableWidth: props.maxWidth,
        })
      : null;
  return (
    <ExpoImage
      source={props.source}
      cachePolicy="memory-disk"
      style={[
        imageStyle,
        props.maxWidth !== undefined
          ? (displaySize ?? {
              width: Math.min(props.maxWidth, MARKDOWN_IMAGE_MAX_WIDTH),
              aspectRatio: 1.3,
            })
          : props.height !== undefined
            ? { height: props.height }
            : undefined,
      ]}
      contentFit={props.maxWidth === undefined ? "cover" : "contain"}
      onLoad={(event) => {
        if (props.maxWidth !== undefined) setSize(event.source);
        props.onLoad?.();
      }}
      onError={props.onError}
    />
  );
}

function MessageAttachmentImage(props: {
  readonly environmentId: EnvironmentId;
  readonly attachmentId: string;
  readonly name: string;
  readonly mimeType: string;
  readonly className: string;
  readonly maxWidth?: number;
  readonly height?: number;
  readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
  const withGallery = useFilePreviewGallery();
  const sourceIdentifier = useId();
  const resource = {
    _tag: "attachment" as const,
    attachmentId: props.attachmentId,
    fileName: props.name,
    mimeType: props.mimeType,
  };
  const uri = useAssetUrl(props.environmentId, resource);
  const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource);
  const retriedImage = useRef(false);

  if (uri === null) {
    return (
      <View
        className={`${props.className} items-center justify-center`}
        style={
          props.maxWidth !== undefined
            ? { width: Math.min(props.maxWidth, MARKDOWN_IMAGE_MAX_WIDTH), aspectRatio: 1.3 }
            : props.height !== undefined
              ? { height: props.height }
              : undefined
        }
      >
        <AppActivityIndicator />
      </View>
    );
  }

  return (
    <PresentationSource identifier={sourceIdentifier}>
      <Pressable
        accessibilityRole="imagebutton"
        accessibilityLabel={`Open ${props.name}`}
        onPress={() =>
          props.onPressPreview(
            withGallery({
              kind: "image",
              environmentId: props.environmentId,
              resource,
              name: props.name,
              sourceIdentifier,
              actionsSource: {
                name: props.name,
                mimeType: props.mimeType,
                environmentId: props.environmentId,
                resource,
              },
            }),
          )
        }
      >
        <MessageImage
          source={assetImageSource(props.environmentId, resource, uri)}
          className={props.className}
          maxWidth={props.maxWidth}
          height={props.height}
          onLoad={() => {
            retriedImage.current = false;
          }}
          onError={() => {
            if (retriedImage.current) return;
            retriedImage.current = true;
            void refreshAssetUrl();
          }}
        />
      </Pressable>
    </PresentationSource>
  );
}

function isImageAttachment(attachment: ChatAttachment): attachment is ChatImageAttachment {
  return attachment.type === "image" || imageMimeType(attachment) !== null;
}

function isFileAttachment(attachment: ChatAttachment): attachment is ChatFileAttachment {
  return attachment.type === "file";
}

function isMediaAttachment(attachment: ChatAttachment): boolean {
  return (
    isImageAttachment(attachment) ||
    (isFileAttachment(attachment) && videoMimeType(attachment) !== null)
  );
}

function MessageAttachmentFile(props: {
  readonly environmentId: EnvironmentId;
  readonly attachment: ChatFileAttachment;
  readonly onPressPreview: (source: FilePreviewSource) => void;
  readonly onPlaybackStart: () => void;
  readonly standaloneMedia?: boolean;
  readonly standaloneFile?: boolean;
  readonly available?: boolean;
}) {
  const sourceIdentifier = useId();
  const navigation = useNavigation();
  const { selectedThread } = useThreadSelection();
  const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
    refresh: true,
    reportFailure: false,
  });
  const preparedConnection = usePreparedConnection(props.environmentId);
  const { attachment } = props;
  const videoType = videoMimeType(attachment);
  const isPdf = isPdfFile(attachment);
  const fileTypeLabel = isPdf
    ? "PDF"
    : (attachment.name.match(/\.([a-z0-9]{1,8})$/i)?.[1]?.toUpperCase() ?? "File");
  const sizeLabel = formatAttachmentSize(attachment.sizeBytes);
  const httpBaseUrl = Option.isSome(preparedConnection)
    ? preparedConnection.value.httpBaseUrl
    : null;
  const openingRef = useRef<AbortController | null>(null);
  const [opening, setOpening] = useState(false);

  useFocusEffect(
    useCallback(() => {
      setOpening(false);
      return () => {
        openingRef.current?.abort();
        openingRef.current = null;
      };
      // oxlint-disable-next-line react/memo-dependencies -- Changing the attachment or connection cancels the previous file open even while this screen stays focused.
    }, [props.environmentId, attachment.id, httpBaseUrl]),
  );

  const shareFile = (sourceIdentifier?: string) => {
    if (props.available === false || httpBaseUrl === null || openingRef.current) return;
    const controller = new AbortController();
    openingRef.current = controller;
    setOpening(true);
    const finish = (message: string | null) => {
      if (message !== null && !controller.signal.aborted) {
        Dialog.alert("Could not open attachment", message);
      }
      if (openingRef.current === controller) {
        openingRef.current = null;
        setOpening(false);
      }
    };
    void (async () => {
      const result = await createAssetUrl({
        environmentId: props.environmentId,
        input: {
          resource: {
            _tag: "attachment",
            attachmentId: attachment.id,
            fileName: attachment.name,
            mimeType: attachment.mimeType,
          },
        },
      });
      if (controller.signal.aborted) return finish(null);
      if (result._tag === "Failure") {
        const error = squashAtomCommandFailure(result);
        return finish(error instanceof Error ? error.message : "The attachment is unavailable.");
      }
      const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
      if (url === null) return finish("The attachment could not be opened.");
      const shared = await settlePromise(() =>
        downloadAndShareAttachment({
          url,
          attachment,
          signal: controller.signal,
          sourceIdentifier,
        }),
      );
      if (shared._tag === "Failure") {
        const error = squashAtomCommandFailure(shared);
        return finish(error instanceof Error ? error.message : "The attachment is unavailable.");
      }
      finish(null);
    })();
  };

  const openAttachment = () =>
    isPdf
      ? props.onPressPreview({
          kind: "pdf",
          name: attachment.name,
          environmentId: props.environmentId,
          resource: {
            _tag: "attachment",
            attachmentId: attachment.id,
            fileName: attachment.name,
            mimeType: "application/pdf",
          },
          sourceIdentifier,
        })
      : navigation.navigate("ThreadAttachment", {
          environmentId: String(props.environmentId),
          ...(selectedThread ? { threadId: String(selectedThread.id) } : {}),
          attachmentId: attachment.id,
          name: attachment.name,
          mimeType: attachment.mimeType,
          sizeBytes: String(attachment.sizeBytes),
        });
  const inlineKind = inlineFilePreviewKind(attachment);
  if (inlineKind) {
    return (
      <PresentationSource identifier={sourceIdentifier}>
        <ThreadInlineFilePreview
          key={attachment.id}
          source={{
            kind: "document",
            name: attachment.name,
            mimeType: attachment.mimeType,
            environmentId: props.environmentId,
            resource: {
              _tag: "attachment",
              attachmentId: attachment.id,
              fileName: attachment.name,
              mimeType: attachment.mimeType,
              disposition: "inline",
            },
          }}
          sizeBytes={attachment.sizeBytes}
          onOpen={openAttachment}
          onPlaybackStart={props.onPlaybackStart}
          onLongPress={() => shareFile(sourceIdentifier)}
        />
      </PresentationSource>
    );
  }

  if (videoType !== null) {
    return (
      <View
        className={props.standaloneMedia ? undefined : "my-1"}
        style={{ width: props.standaloneMedia ? 320 : 224, maxWidth: "100%" }}
      >
        <ThreadMarkdownVideo
          source={attachmentVideoPreviewSource(props.environmentId, attachment, sourceIdentifier)}
          onPlaybackStart={props.onPlaybackStart}
          borderRadius={props.standaloneMedia ? 20 : undefined}
        />
      </View>
    );
  }

  const disabled = props.available === false || opening || httpBaseUrl === null;
  return (
    <PresentationSource
      identifier={sourceIdentifier}
      className="my-1"
      style={{ width: 280, maxWidth: "100%" }}
    >
      <View className="min-w-0 flex-row items-center overflow-hidden rounded-xl border border-border bg-card">
        <Pressable
          accessibilityRole="button"
          accessibilityLabel={`Open ${attachment.name}`}
          accessibilityValue={{ text: `${fileTypeLabel}, ${sizeLabel}` }}
          accessibilityState={{ disabled, busy: opening }}
          disabled={disabled}
          className="min-w-0 flex-1 flex-row items-center gap-3 p-3 active:bg-subtle"
          onLongPress={() => shareFile(sourceIdentifier)}
          onPress={openAttachment}
        >
          <View className="h-12 w-10 shrink-0 items-center justify-center rounded-lg bg-subtle">
            {opening ? (
              <AppActivityIndicator size="small" />
            ) : (
              <PierreEntryIcon path={attachment.name} kind="file" size={26} />
            )}
          </View>
          <View className="min-w-0 flex-1 gap-1">
            <Text className="font-t3-medium text-sm text-foreground" numberOfLines={2}>
              {attachment.name}
            </Text>
            <Text className="text-xs text-foreground-muted" numberOfLines={1}>
              {fileTypeLabel} · {sizeLabel}
            </Text>
          </View>
          <SymbolView
            name="chevron.right"
            size={12}
            tintColorClassName="accent-foreground-muted"
            type="monochrome"
          />
        </Pressable>
        {props.standaloneFile ? (
          <Pressable
            accessibilityRole="button"
            accessibilityLabel={`Download ${attachment.name}`}
            accessibilityState={{ disabled, busy: opening }}
            disabled={disabled}
            className="mr-1 min-h-11 w-11 items-center justify-center rounded-lg active:bg-subtle disabled:opacity-40"
            onPress={() => shareFile(sourceIdentifier)}
          >
            <SymbolView name="arrow.down" size={16} tintColorClassName="accent-foreground-muted" />
          </Pressable>
        ) : null}
      </View>
    </PresentationSource>
  );
}

function UserMessageMedia(props: {
  readonly attachments: ReadonlyArray<ChatAttachment>;
  readonly pendingAttachments: QueuedThreadMessage["attachments"];
  readonly environmentId: EnvironmentId;
  readonly maxWidth: number;
  readonly onPressPreview: (source: FilePreviewSource) => void;
  readonly onPlaybackStart: () => void;
}) {
  const attachments = [...props.pendingAttachments, ...props.attachments];
  const collage = attachments.length > 1 && attachments.every(isImageAttachment);
  const imageProps = (index: number) => ({
    className: "w-full bg-user-bubble-foreground/15",
    maxWidth: collage ? undefined : props.maxWidth,
    height: !collage
      ? undefined
      : attachments.length === 2 || (attachments.length === 3 && index === 0)
        ? 192
        : attachments.length === 3
          ? (192 - StyleSheet.hairlineWidth) / 2
          : 96,
  });
  const media = [
    ...props.pendingAttachments.map((attachment, index) => {
      const image = isImageAttachment(attachment);
      return {
        id: attachment.id,
        image,
        content:
          image && attachment.uploadedAttachmentId ? (
            <MessageAttachmentImage
              environmentId={props.environmentId}
              attachmentId={attachment.uploadedAttachmentId}
              name={attachment.name}
              mimeType={attachment.mimeType}
              {...imageProps(index)}
              onPressPreview={props.onPressPreview}
            />
          ) : !image && attachment.uploadedAttachmentId ? (
            <ThreadMarkdownVideo
              source={attachmentVideoPreviewSource(props.environmentId, {
                ...attachment,
                type: "file",
                id: attachment.uploadedAttachmentId,
              })}
              onPlaybackStart={props.onPlaybackStart}
              borderRadius={20}
            />
          ) : (
            <PendingMessageMedia
              attachment={attachment}
              {...imageProps(index)}
              onPressPreview={props.onPressPreview}
              onPlaybackStart={props.onPlaybackStart}
            />
          ),
      };
    }),
    ...props.attachments.map((attachment, index) => ({
      id: attachment.id,
      image: isImageAttachment(attachment),
      content: isImageAttachment(attachment) ? (
        <MessageAttachmentImage
          environmentId={props.environmentId}
          attachmentId={attachment.id}
          name={attachment.name}
          mimeType={attachment.mimeType}
          {...imageProps(props.pendingAttachments.length + index)}
          onPressPreview={props.onPressPreview}
        />
      ) : isFileAttachment(attachment) ? (
        <MessageAttachmentFile
          environmentId={props.environmentId}
          attachment={attachment}
          onPressPreview={props.onPressPreview}
          onPlaybackStart={props.onPlaybackStart}
          standaloneMedia
        />
      ) : null,
    })),
  ];
  return collage ? (
    <View
      className="overflow-hidden rounded-[20px] bg-border"
      style={{ width: 320, maxWidth: "100%", alignSelf: "flex-end", gap: StyleSheet.hairlineWidth }}
    >
      {media.length === 3 ? (
        <View className="flex-row" style={{ gap: StyleSheet.hairlineWidth }}>
          <View className="min-w-0" style={{ flex: 3 }}>
            {media[0]!.content}
          </View>
          <View className="min-w-0" style={{ flex: 2, gap: StyleSheet.hairlineWidth }}>
            {media[1]!.content}
            {media[2]!.content}
          </View>
        </View>
      ) : (
        media
          .filter((_, index) => index % 2 === 0)
          .map((item, index) => (
            <View key={item.id} className="flex-row" style={{ gap: StyleSheet.hairlineWidth }}>
              <View className="min-w-0 flex-1">{item.content}</View>
              {media[index * 2 + 1] ? (
                <View className="min-w-0 flex-1">{media[index * 2 + 1]!.content}</View>
              ) : null}
            </View>
          ))
      )}
      <View pointerEvents="none" className="absolute inset-0 rounded-[20px] border border-border" />
    </View>
  ) : (
    <View className="items-end gap-2">
      {media.map((item) => (
        <View
          key={item.id}
          className="overflow-hidden rounded-[20px]"
          style={{ width: item.image ? undefined : 320, maxWidth: "100%" }}
        >
          {item.content}
          <View
            pointerEvents="none"
            className="absolute inset-0 rounded-[20px] border border-border"
          />
        </View>
      ))}
    </View>
  );
}

function PendingMessageMedia(props: {
  readonly attachment: QueuedThreadMessage["attachments"][number];
  readonly className: string;
  readonly maxWidth?: number;
  readonly height?: number;
  readonly onPressPreview: (source: FilePreviewSource) => void;
  readonly onPlaybackStart: () => void;
}) {
  const withGallery = useFilePreviewGallery();
  const { attachment } = props;
  const fileBacked = isFileBackedComposerAttachment(attachment);
  const preview = useLocalAttachmentPreview(fileBacked ? attachment : null);
  if (isImageAttachment(attachment)) {
    const uri = fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri);
    return (
      <Pressable
        accessibilityRole="imagebutton"
        accessibilityLabel={`Open ${attachment.name}`}
        onPress={() => {
          const source = composerImageGallery([attachment])[0];
          if (source) props.onPressPreview(withGallery(source));
        }}
      >
        <MessageImage
          source={uri === null ? undefined : { uri }}
          className={props.className}
          maxWidth={props.maxWidth}
          height={props.height}
        />
      </Pressable>
    );
  }
  if (preview.uri === null) {
    return (
      <View className="aspect-video items-center justify-center bg-black">
        {preview.error ? (
          <Text className="p-3 text-center text-xs text-white/70">{preview.error.message}</Text>
        ) : (
          <AppActivityIndicator />
        )}
      </View>
    );
  }
  return (
    <ThreadMarkdownVideo
      source={{
        type: "media",
        name: attachment.name,
        mimeType: attachment.mimeType,
        uri: preview.uri,
      }}
      onPlaybackStart={props.onPlaybackStart}
      borderRadius={20}
    />
  );
}

/** A message's files as its bubble shows them; a guest's waiting message uses it too. */
function MessageAttachmentList(props: {
  readonly attachments: ReadonlyArray<ChatAttachment>;
  readonly environmentId: EnvironmentId;
  readonly onPressPreview: (source: FilePreviewSource) => void;
  readonly onPlaybackStart: () => void;
}) {
  return props.attachments.map((attachment) =>
    isImageAttachment(attachment) ? (
      <MessageAttachmentImage
        key={attachment.id}
        environmentId={props.environmentId}
        attachmentId={attachment.id}
        name={attachment.name}
        mimeType={attachment.mimeType}
        className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-subtle-strong"
        onPressPreview={props.onPressPreview}
      />
    ) : isFileAttachment(attachment) ? (
      <MessageAttachmentFile
        key={attachment.id}
        environmentId={props.environmentId}
        attachment={attachment}
        onPressPreview={props.onPressPreview}
        onPlaybackStart={props.onPlaybackStart}
      />
    ) : (
      <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
    ),
  );
}

function MessageAttachmentUnknown(props: { readonly name: string }) {
  return (
    <View className="flex-row items-center gap-2 py-1">
      <PierreEntryIcon path={props.name} kind="file" size={16} />
      <Text className="min-w-0 flex-1 text-sm text-foreground" numberOfLines={1}>
        {props.name}
      </Text>
    </View>
  );
}

// LegendList only computes hook visibility when the list has a viewability config.
const THREAD_MEDIA_VIEWABILITY_CONFIG = { itemVisiblePercentThreshold: 0 };

// The composer and overlays beside the feed keep UIKit from finding it on its own, so
// register it with the screen controller. Header minimization observes this scroll view.
function ThreadFeedScrollView(props: ComponentPropsWithRef<typeof Animated.ScrollView>) {
  return (
    <NativeScrollViewMarker style={{ flex: 1 }}>
      <Animated.ScrollView {...props} />
    </NativeScrollViewMarker>
  );
}

function ThreadMediaVisibility(props: { readonly children: ReactNode }) {
  const [visible, setVisible] = useState(false);
  useViewabilityAmount<ThreadFeedEntry>(
    useCallback((token) => setVisible(token.sizeVisible > 0), []),
  );
  return <ThreadMediaVisibleContext value={visible}>{props.children}</ThreadMediaVisibleContext>;
}

interface MarkdownLinkHandlers {
  readonly onLinkPress: (href: string) => void;
  readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined;
  readonly onFileContextMenuAction: (href: string, actionId: string) => void;
  readonly onImagePress?: (href: string) => void;
  readonly resolveImageSource?: MarkdownImageSourceResolver;
  readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;
  readonly linkCustomization?: (href: string) => MarkdownLinkCustomization | undefined;
}

interface MarkdownStyleSets {
  readonly user: MarkdownStyleSet;
  readonly assistant: MarkdownStyleSet;
}

interface MarkdownStyleSet {
  readonly nativeTextStyle: NativeMarkdownTextStyle;
}

const ARTIFACT_TEMPLATE_SYMBOL_BY_KIND: Record<
  CodexArtifactTemplate["artifactKind"],
  AppSymbolName
> = {
  document: "doc.text",
  presentation: "chart.bar.xaxis",
  spreadsheet: "chart.bar.xaxis",
  site: "safari",
  "google-docs": "doc.text",
  "google-slides": "chart.bar.xaxis",
  "google-sheets": "chart.bar.xaxis",
  image: "camera",
  email: "text.bubble",
  slack: "text.bubble",
};

function ArtifactTemplateCard(props: {
  readonly template: CodexArtifactTemplate;
  readonly onUse?: ((template: CodexArtifactTemplate) => void) | undefined;
}) {
  return (
    <View className="my-2 min-w-0 flex-row items-center gap-3 rounded-2xl border border-border bg-card px-3 py-3">
      <View className="relative h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-border bg-subtle">
        <SymbolView
          name={ARTIFACT_TEMPLATE_SYMBOL_BY_KIND[props.template.artifactKind]}
          size={20}
          tintColorClassName="accent-foreground-muted"
          type="monochrome"
        />
        <View className="absolute -right-1 -bottom-1 h-4 w-4 items-center justify-center rounded-full bg-fuchsia-500">
          <SymbolView
            name={{ ios: "sparkles", android: "auto_awesome" }}
            size={9}
            tintColor="white"
            type="monochrome"
          />
        </View>
      </View>
      <View className="min-w-0 flex-1">
        <Text className="font-t3-bold text-sm text-foreground" numberOfLines={1}>
          {props.template.displayName}
        </Text>
        <Text className="text-xs text-foreground-muted">
          {codexArtifactTemplatePresentationLabel(props.template.artifactKind)}
        </Text>
      </View>
      {props.onUse ? (
        <Button
          label="Use template"
          tone="secondary"
          accessibilityLabel={`Use ${props.template.displayName} template`}
          onPress={() => props.onUse?.(props.template)}
        />
      ) : null}
    </View>
  );
}

const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
  readonly markdown: string;
  readonly environmentId: EnvironmentId;
  readonly markdownStyles: MarkdownStyleSet;
  readonly linkHandlers: MarkdownLinkHandlers;
  readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
  readonly renderImage: MarkdownImageRenderer;
  readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
}) {
  const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);
  const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown);
  const linkHandlers: MarkdownLinkHandlers = {
    ...props.linkHandlers,
    linkCustomization: (href) =>
      withChipIcon(props.linkHandlers.linkCustomization?.(href), threadIcons.get(href)),
  };

  return (
    <AssistantMarkdownBlocks
      markdown={liveMarkdown}
      markdownStyles={props.markdownStyles}
      linkHandlers={linkHandlers}
      onUseArtifactTemplate={props.onUseArtifactTemplate}
      renderImage={props.renderImage}
      skills={props.skills}
    />
  );
});

// Folds split first, so an artifact card inside a fold stays inside it.
function AssistantMarkdownBlocks(props: {
  readonly markdown: string;
  readonly markdownStyles: MarkdownStyleSet;
  readonly linkHandlers: MarkdownLinkHandlers;
  readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
  readonly renderImage: MarkdownImageRenderer;
  readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
}) {
  const blocks = useMemo(
    () =>
      splitMarkdownDetails(props.markdown).map((block) =>
        block.kind === "details"
          ? block
          : { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) },
      ),
    [props.markdown],
  );
  return blocks.map((block) => {
    if (block.kind === "details") {
      return (
        <MarkdownDetailsFold
          key={`details:${block.sourceOffset}`}
          summary={block.summary}
          initiallyOpen={block.open}
        >
          <AssistantMarkdownBlocks {...props} markdown={block.body} />
        </MarkdownDetailsFold>
      );
    }
    return block.segments.map((segment) => {
      const offset = block.sourceOffset + segment.sourceOffset;
      if (segment.kind === "artifact-template") {
        return (
          <ArtifactTemplateCard
            key={`artifact-template:${offset}`}
            template={segment.template}
            onUse={props.onUseArtifactTemplate}
          />
        );
      }
      if (segment.markdown.trim().length === 0) return null;
      return (
        <SelectableMarkdownText
          key={`markdown:${offset}`}
          markdown={renderCodexInlineDirectivesAsMarkdown(segment.markdown)}
          skills={props.skills}
          textStyle={props.markdownStyles.nativeTextStyle}
          {...props.linkHandlers}
          renderImage={props.renderImage}
        />
      );
    });
  });
}

function MarkdownDetailsFold(props: {
  readonly summary: string;
  readonly initiallyOpen: boolean;
  readonly children: ReactNode;
}) {
  const [expanded, setExpanded] = useState(props.initiallyOpen);
  const iconSubtleColor = useUniwindTheme()["--color-icon-subtle"];
  return (
    <View className="my-2 border-y border-border">
      <Pressable
        accessibilityRole="button"
        accessibilityLabel={props.summary}
        accessibilityState={{ expanded }}
        hitSlop={4}
        className="min-h-10 flex-row items-center gap-2 py-2"
        onPress={() => {
          void Haptics.selectionAsync();
          setExpanded((value) => !value);
        }}
      >
        <ThreadDisclosureChevron
          expanded={expanded}
          collapsedDirection="right"
          size={12}
          tintColor={iconSubtleColor}
        />
        <Text className="min-w-0 shrink font-t3-medium text-sm text-foreground">
          {props.summary}
        </Text>
      </Pressable>
      {expanded ? <View className="pb-3 pl-5">{props.children}</View> : null}
    </View>
  );
}

function useMarkdownStyles(): MarkdownStyleSets {
  const { appearance } = useAppearancePreferences();
  const nativeMarkdownTypography = resolveNativeMarkdownTypography(appearance.baseFontSize);
  const theme = useUniwindTheme();
  const markdownBodyColor = theme["--color-md-body"];
  const markdownStrongColor = theme["--color-md-strong"];
  const markdownLinkColor = theme["--color-md-link"];
  const markdownBlockquoteBorder = theme["--color-md-blockquote-border"];
  const markdownCodeBg = theme["--color-md-code-bg"];
  const markdownCodeText = theme["--color-md-code-text"];
  const markdownInlineCodeText = theme["--color-foreground-secondary"];
  const markdownHrColor = theme["--color-md-hr"];
  // Native chip drawing parses opaque hex only, and this role is translucent.
  const contextChipBorderColor = flattenThemeColor(
    theme["--color-border"],
    theme["--color-user-bubble"],
  );
  const markdownUserBodyColor = theme["--color-user-bubble-foreground"];
  const markdownUserCodeBg = theme["--color-md-user-code-bg"];
  const markdownUserCodeText = theme["--color-md-user-code-text"];
  const markdownUserInlineCodeText = theme["--color-user-bubble-foreground-muted"];
  const markdownUserFenceBg = theme["--color-md-user-fence-bg"];
  const regularFontFamily = FONT_FAMILIES.regular;
  const boldFontFamily = FONT_FAMILIES.bold;

  return {
    user: {
      nativeTextStyle: {
        color: markdownUserBodyColor,
        strongColor: markdownUserBodyColor,
        mutedColor: markdownUserBodyColor,
        linkColor: markdownUserBodyColor,
        inlineCodeColor: markdownUserInlineCodeText,
        codeColor: markdownUserCodeText,
        codeBackgroundColor: markdownUserCodeBg,
        codeBlockBackgroundColor: markdownUserFenceBg,
        fileTextColor: markdownUserBodyColor,
        quoteMarkerColor: markdownUserBodyColor,
        dividerColor: markdownUserBodyColor,
        contextChipBorderColor,
        fontSize: nativeMarkdownTypography.fontSize,
        lineHeight: nativeMarkdownTypography.lineHeight,
        headingFontSizes: nativeMarkdownTypography.headingFontSizes,
        fontFamily: regularFontFamily,
        headingFontFamily: boldFontFamily,
        boldFontFamily,
      },
    },
    assistant: {
      nativeTextStyle: {
        color: markdownBodyColor,
        strongColor: markdownStrongColor,
        mutedColor: markdownBodyColor,
        linkColor: markdownLinkColor,
        inlineCodeColor: markdownInlineCodeText,
        codeColor: markdownCodeText,
        codeBackgroundColor: markdownCodeBg,
        codeBlockBackgroundColor: markdownCodeBg,
        fileTextColor: markdownCodeText,
        quoteMarkerColor: markdownBlockquoteBorder,
        dividerColor: markdownHrColor,
        contextChipBorderColor,
        fontSize: nativeMarkdownTypography.fontSize,
        lineHeight: nativeMarkdownTypography.lineHeight,
        headingFontSizes: nativeMarkdownTypography.headingFontSizes,
        fontFamily: regularFontFamily,
        headingFontFamily: boldFontFamily,
        boldFontFamily,
      },
    },
  };
}

/** Messages from other agents fold to one line so the user's own messages stay easy to find. */
function AgentMessageFoldHeader(props: {
  readonly environmentId: EnvironmentId;
  readonly senderThreadId?: ThreadId;
  readonly summary: string;
  readonly expanded: boolean;
  readonly onToggle: () => void;
  readonly iconSubtleColor: ColorValue;
}) {
  const senderShell = useQuietThreadShell(
    props.senderThreadId ? scopeThreadRef(props.environmentId, props.senderThreadId) : null,
  );
  const label = senderShell?.title.trim() || "Agent";
  return (
    <Pressable
      accessibilityRole="button"
      accessibilityLabel={`${label}: ${props.summary}`}
      accessibilityHint={`Double tap to ${props.expanded ? "hide" : "show"} the message.`}
      accessibilityState={{ expanded: props.expanded }}
      hitSlop={4}
      className="min-h-10 flex-row items-center gap-1.5 px-3.5 py-2"
      onPress={() => {
        void Haptics.selectionAsync();
        props.onToggle();
      }}
    >
      <SymbolView
        name="bubble.left.and.bubble.right"
        size={14}
        weight="medium"
        tintColorClassName="accent-user-bubble-foreground-muted"
        type="monochrome"
      />
      <Text
        numberOfLines={1}
        className="max-w-[50%] shrink-0 font-t3-medium text-sm text-user-bubble-foreground-muted"
      >
        {label}
      </Text>
      <Text numberOfLines={1} className="min-w-0 shrink text-sm text-user-bubble-foreground">
        {props.summary}
      </Text>
      <ThreadDisclosureChevron
        expanded={props.expanded}
        collapsedDirection="down"
        size={11}
        tintColor={props.iconSubtleColor}
      />
    </Pressable>
  );
}

function OpenSenderThreadButton(props: {
  readonly environmentId: EnvironmentId;
  readonly senderThreadId: ThreadId;
}) {
  const openLinkedThread = useOpenLinkedThread();
  return (
    <Pressable
      accessibilityRole="link"
      hitSlop={6}
      onPress={() =>
        openLinkedThread({
          environmentId: String(props.environmentId),
          threadId: String(props.senderThreadId),
        })
      }
    >
      <Text className="font-t3-medium text-xs text-foreground-secondary">Open thread</Text>
    </Pressable>
  );
}

/** Automation prompts are long, repeated runbooks; a folded bubble keeps them out of the way. */
function ThreadAutomationMessageRow(props: {
  readonly environmentId: EnvironmentId;
  readonly text: string;
  readonly context?: OrchestrationMessageContext;
  readonly scheduledTaskId: ScheduledTaskId | undefined;
  readonly timestampLabel: string;
  readonly expanded: boolean;
  readonly onToggle: () => void;
  readonly bubbleColor: ColorValue;
  readonly bubbleMaxWidth: number | "85%";
  readonly contentMaxWidth: number;
  readonly iconSubtleColor: ColorValue;
  readonly markdownStyles: MarkdownStyleSet;
  readonly reviewCommentColors: ReviewCommentColors;
  readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
  readonly linkHandlers: MarkdownLinkHandlers;
  readonly renderImage: MarkdownImageRenderer;
}) {
  const navigation = useNavigation();
  const tasks = useEnvironmentQuery(
    props.scheduledTaskId
      ? serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} })
      : null,
  );
  const taskTitle = tasks.data?.tasks.find((task) => task.id === props.scheduledTaskId)?.title;
  const summary = taskTitle ?? props.text.trim().split(/\r?\n/, 1)[0] ?? "";

  return (
    <View className="mb-5 items-end">
      <View
        className="min-w-0 rounded-[20px]"
        style={{
          backgroundColor: props.bubbleColor,
          maxWidth: props.bubbleMaxWidth,
          ...(props.expanded ? { width: props.bubbleMaxWidth } : null),
        }}
      >
        <Pressable
          accessibilityRole="button"
          accessibilityLabel={`Automation: ${summary}`}
          accessibilityHint={`Double tap to ${props.expanded ? "hide" : "show"} the prompt.`}
          accessibilityState={{ expanded: props.expanded }}
          hitSlop={4}
          className="min-h-10 flex-row items-center gap-1.5 px-3.5 py-2"
          onPress={() => {
            void Haptics.selectionAsync();
            props.onToggle();
          }}
        >
          <SymbolView
            name="calendar.badge.clock"
            size={14}
            weight="medium"
            tintColorClassName="accent-user-bubble-foreground-muted"
            type="monochrome"
          />
          <Text className="font-t3-medium text-sm text-user-bubble-foreground-muted">
            Automation
          </Text>
          <Text numberOfLines={1} className="min-w-0 shrink text-sm text-user-bubble-foreground">
            {summary}
          </Text>
          <ThreadDisclosureChevron
            expanded={props.expanded}
            collapsedDirection="down"
            size={11}
            tintColor={props.iconSubtleColor}
          />
        </Pressable>
        {props.expanded ? (
          <View className="px-3.5 pb-2.5">
            <MarkdownImageAvailableWidthContext value={props.contentMaxWidth}>
              <UserMessageContent
                text={renderAssistantCitationsAsText(props.text)}
                environmentId={props.environmentId}
                context={props.context}
                markdownStyles={props.markdownStyles}
                reviewCommentColors={props.reviewCommentColors}
                skills={props.skills}
                linkHandlers={props.linkHandlers}
                renderImage={props.renderImage}
              />
            </MarkdownImageAvailableWidthContext>
          </View>
        ) : null}
      </View>
      {props.expanded ? (
        <View className="mt-1 flex-row items-center justify-end gap-2 pr-0.5">
          {props.scheduledTaskId ? (
            <Pressable
              accessibilityRole="link"
              hitSlop={6}
              onPress={() => openSettings(navigation, "SettingsScheduledTasks")}
            >
              <Text className="font-t3-medium text-xs text-foreground-secondary">
                Open automation
              </Text>
            </Pressable>
          ) : null}
          <Text className="font-t3-medium text-xs tabular-nums text-foreground-secondary">
            {props.timestampLabel}
          </Text>
          <UserMessageCopyButton
            text={props.text}
            onCopy={undefined}
            tintColor={props.iconSubtleColor}
          />
        </View>
      ) : null}
    </View>
  );
}

/** Leads with why T3 Code compacted, when it did so without being asked. */
function compactionLabel(label: string, title: string | undefined) {
  return title !== undefined && label.startsWith("Context compacted")
    ? title + label.slice("Context compacted".length)
    : label;
}

function RunFoldButton({
  entry,
  environmentId,
  threadId,
  onToggle,
  rowSizing,
  iconColor,
}: {
  entry: Extract<ThreadFeedEntry, { type: "run-fold" }>;
  environmentId: EnvironmentId;
  threadId: ThreadId;
  onToggle: (runId: RunId) => void;
  rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
  iconColor: ColorValue;
}) {
  const loadWork = useAtomCommand(threadEnvironment.loadEarlierHistory, { reportFailure: false });
  const anchorsKey = entry.deferredWorkItemIds?.join("\n") ?? "";
  const [failed, setFailed] = useState(false);
  const load = () => {
    if (!anchorsKey) return;
    void Promise.all(
      anchorsKey
        .split("\n")
        .map((workAnchorId) => loadWork({ environmentId, input: { threadId, workAnchorId } })),
    ).then((results) =>
      setFailed(
        results.some((result) => result._tag === "Failure" || result.value._tag === "error"),
      ),
    );
  };
  const loadOnExpand = useEffectEvent(load);
  // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restored expanded folds load their deferred server history on mount.
  useEffect(() => {
    if (entry.expanded && anchorsKey && environmentId && threadId) loadOnExpand();
  }, [entry.expanded, anchorsKey, environmentId, threadId]);
  const error = anchorsKey && failed ? "Couldn't load work. Tap to retry." : null;
  const loading = entry.expanded && anchorsKey !== "" && !failed;
  const toggle = () => {
    setFailed(false);
    if (error && entry.expanded) load();
    else onToggle(entry.runId);
  };

  return (
    <View className="min-w-0 flex-1">
      <Pressable
        accessibilityRole="button"
        accessibilityState={{ expanded: entry.expanded, busy: loading }}
        onPress={toggle}
        hitSlop={4}
        className="min-h-11 min-w-0 flex-1 flex-row items-center gap-2"
        style={{ minHeight: Math.max(TURN_FOLD_HEIGHT - 3.5, rowSizing.estimatedRowHeight) }}
      >
        <Text
          key={rowSizing.textSizeKey}
          numberOfLines={1}
          className="shrink font-t3-medium text-sm tabular-nums text-foreground-muted"
        >
          {entry.label}
          {error ? ` · ${error}` : ""}
        </Text>
        <ThreadDisclosureChevron
          expanded={entry.expanded}
          collapsedDirection="right"
          size={15}
          tintColor={iconColor}
        />
      </Pressable>
      {loading ? (
        <View
          accessible={false}
          importantForAccessibility="no-hide-descendants"
          className="gap-2 px-1 pb-2"
        >
          {(["40%", "60%", "33%"] as const).map((width) => (
            <View key={width} className="flex-row items-center gap-2">
              <View className="size-3 rounded bg-subtle-strong" />
              <View className="h-2.5 rounded-full bg-subtle-strong" style={{ width }} />
            </View>
          ))}
        </View>
      ) : null}
    </View>
  );
}

function renderFeedEntry(
  info: { item: ThreadFeedRow; index: number },
  props: Pick<
    ThreadFeedProps,
    | "environmentId"
    | "onUseArtifactTemplate"
    | "skills"
    | "dispatchingMessageId"
    | "onEditPendingMessage"
    | "threadId"
    | "workspaceRoot"
  > & {
    readonly copiedRowId: string | null;
    readonly expandedWorkRows: Record<string, boolean>;
    readonly workRowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
    readonly workGroupScrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
    readonly terminalAssistantMessageIds: ReadonlySet<string>;
    readonly unsettledTurnId: RunId | null;
    readonly compactionLabelsByEntryId: ReadonlyMap<string, { title: string; compacting: string }>;
    readonly failedRunIds: ReadonlySet<RunId>;
    readonly onCopyWorkRow: (rowId: string, value: string) => void;
    readonly onToggleWorkGroup: (groupId: string, anchorKey?: string) => void;
    readonly onToggleWorkRow: (rowId: string, anchorKey?: string, groupId?: string) => void;
    readonly onToggleTurnFold: (runId: RunId) => void;
    readonly onOpenTurnDiff: (checkpoint: ThreadCheckpointSummary) => void;
    readonly onPressPreview: (source: FilePreviewSource) => void;
    readonly onPlaybackStart: () => void;
    readonly markdownLinkHandlers: MarkdownLinkHandlers;
    readonly renderMarkdownImage: MarkdownImageRenderer;
    readonly renderViewedImage: MarkdownImageRenderer;
    readonly renderReasoning: (text: string) => ReactNode;
    readonly iconSubtleColor: string | import("react-native").ColorValue;
    readonly replyActionSize: { readonly button: number; readonly icon: number };
    readonly screenColor: string;
    readonly userBubbleColor: string | import("react-native").ColorValue;
    readonly markdownStyles: MarkdownStyleSets;
    readonly reviewCommentColors: ReviewCommentColors;
    readonly reviewCommentBubbleWidth: number;
    readonly themeAppearance: "light" | "dark";
    readonly duoColumns: boolean;
    readonly userBubbleMaxWidth: number;
    readonly markdownContentWidth: number;
    readonly contentWidth: number;
    readonly threadTitle: string;
    readonly workflowOpening: WorkflowOpening | null;
    readonly userMessageGrouping: GroupedThreadFeedRow["userMessageGrouping"];
  },
) {
  const entry = info.item;
  const { markdownStyles, iconSubtleColor, userBubbleColor } = props;

  if (entry.type === "guest-pending") {
    return (
      <ThreadGuestPendingMessage
        threadRef={scopeThreadRef(props.environmentId, props.threadId)}
        guestName={entry.guestName}
        message={entry.message}
        bubbleMaxWidth={props.duoColumns ? "85%" : props.userBubbleMaxWidth}
        renderAttachments={(attachments) => (
          <MessageAttachmentList
            attachments={attachments}
            environmentId={props.environmentId}
            onPressPreview={props.onPressPreview}
            onPlaybackStart={props.onPlaybackStart}
          />
        )}
      />
    );
  }

  if (entry.type === "run-fold") {
    return (
      <View className="mb-1 flex-row items-center border-b border-border-subtle px-2">
        <RunFoldButton
          key={entry.id}
          entry={entry}
          environmentId={props.environmentId}
          threadId={props.threadId}
          onToggle={props.onToggleTurnFold}
          rowSizing={props.workRowSizing}
          iconColor={iconSubtleColor}
        />
        {entry.checkpointSummary ? (
          <TurnDiffStat
            checkpoint={entry.checkpointSummary}
            onOpenTurnDiff={props.onOpenTurnDiff}
          />
        ) : null}
      </View>
    );
  }

  if (entry.type === "thinking") {
    return (
      <ThreadThinkingRow
        rowSizing={props.workRowSizing}
        iconSubtleColor={iconSubtleColor}
        label={entry.label}
      />
    );
  }

  if (entry.type === "html-render") {
    return (
      <ThreadHtmlRender
        environmentId={props.environmentId}
        threadId={props.threadId}
        render={entry.render}
        frameWidth={props.contentWidth}
        iconColor={iconSubtleColor}
      />
    );
  }

  if (entry.type === "mcp-app") {
    return (
      <ThreadMcpApp
        key={entry.app.attachmentId}
        environmentId={props.environmentId}
        threadId={entry.sourceThreadId}
        conversationThreadId={props.threadId}
        itemId={entry.itemId}
        revision={entry.revision}
        app={entry.app}
        width={props.contentWidth}
      />
    );
  }

  if (entry.type === "work-toggle") {
    return (
      <ThreadWorkGroupToggle
        environmentId={props.environmentId}
        rowSizing={props.workRowSizing}
        expanded={entry.expanded}
        hiddenCount={entry.hiddenCount}
        iconSubtleColor={iconSubtleColor}
        summary={entry.summary}
        summaryKind={entry.summaryKind}
        themeAppearance={props.themeAppearance}
        toolSurface={entry.toolSurface}
        toolIcon={entry.toolIcon}
        summaryToolIcon={entry.summaryToolIcon}
        hasFailure={entry.hasFailure}
        shimmer={entry.shimmer}
        thought={entry.thought}
        trailing={
          entry.checkpointSummary ? (
            <TurnDiffStat