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。

76.9 KB
Raw Blame
/**
 * 远程文件 Quick Look 预览。
 *
 * 同目录文件横滑翻页(iOS Quick Look 心智):进入时列一次父目录,把全部文件
 * (含不可预览的,显示占位页)按浏览页同款排序装进水平 pager。PDF 例外:
 * 预览期间禁用外层横滑,把缩放后的水平拖动完整留给 WKWebView,避免 pager
 * 抢手势后切换文件;PDF cell 离开渲染窗口时可能被回收,进而重置阅读位置
 * 或再次加载 URL。
 * 切换文件通过 Done 返回列表完成。
 * 文本 = readFile(acceptGzip,pako 解码)+ 行号列表;图片 = 缩略图立即显示,
 * OSS 导出原图就绪后无缝换源(不出 loading 态,规则 7);其它 = 占位 + 下载。
 * markdown 与 HTML 额外有「渲染 / 源码」双态,默认渲染。HTML 使用浮动浏览器控件,
 * 所有文件共用悬浮控件,源码切换、文件信息与路径操作收进更多菜单。
 * HTML 渲染完整目录快照,源码仍走文本通道与原有大小限制。
 *
 * absPath 单文件模式(route 参 absPath,与 relPath 互斥):聊天 chip 指向
 * workdir 外文件时进入。file-browser 的 relPath 通道(listDir / readFile /
 * thumbnail / exportFile*)对 workdir 外一律拒绝,该模式改走被控端绝对路径
 * 通道:文本 = text-file:read-preview,媒体/下载 = media:fetch
 * (fetchRemoteAbsFileToUrl);无同目录翻页、无缩略图(直接取原图)。
 */
import * as Clipboard from 'expo-clipboard';
import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
import { Image } from 'expo-image';
import { useFocusEffect, useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ArrowDownToLine, Database, File as FileIcon, Info } from 'lucide-react-native';
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Pressable,
  StyleSheet,
  View,
  useWindowDimensions,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { WebView } from 'react-native-webview';
import type { WebViewNavigation } from 'react-native-webview/lib/WebViewTypes';
import { Text } from '@/components/AppText';
import { goBackGuarded } from '@/utils/backGuard';
import { errorText, resolvedUrlKind, sanitizeDiagnosticText } from '@/debug/fileDiagnostics';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
import { useAuth } from '@/auth/AuthContext';
import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';
import { formatRemoteError } from '@/device-link/remoteStatus';
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
import type { FileBrowserReadFileResult, MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { isAbsolutePathShape, pathDisplayName } from '@/session/chatPathCandidate';
import { adaptTextFilePreviewResult, fetchRemoteAbsFileToUrl } from '@/session/remoteAbsFileFetch';
import { preparePdfPreviewSource } from '@/session/pdfPreviewSource';
import { formatByteSize, isHtmlFilePreviewCandidate } from '@/session/filePreview';
import { joinRemotePath } from '@/session/htmlLocalResources';
import { decodeGzipBase64Text, mergePathIntoComposerDraft, shareMimeForFileName } from '@/session/fileBrowserActions';
import { appendQuote, truncateQuoteText } from '@/session/chatQuoteStore';
import { getCachedListingSync, storeCachedListing, getCachedPreviewText, storeCachedPreviewText } from '@/session/fileBrowserCache';
import { exportRemoteFileToUrl } from '@/session/fileBrowserExport';
import type { RemoteMediaSshContext } from '@/session/fileBrowserGallery';
import { HtmlSnapshotReader } from '@/session/HtmlFileReader';
import { HtmlPreviewLoading } from '@/session/HtmlPreviewLoading';
import { HtmlBrowserChrome } from '@/session/HtmlBrowserChrome';
import { HtmlWebsiteBrowser, type WebsiteVisit } from '@/session/HtmlWebsiteBrowser';
import { normalizeBrowserAddress } from '@/session/browserAddress';
import { HTML_BROWSER_CONTROL_SIZE, type HtmlBrowserChromeProps } from '@/session/HtmlBrowserChrome.types';
import { usePreviewChromeFrame } from '@/session/usePreviewChromeFrame';
import type { MobileHtmlPreview } from '@/session/mobileHtmlPreview';
import { prepareMobileHtmlPreview, type PrepareMobileHtmlPreview } from '@/session/mobileHtmlPreview';
import { useHtmlSnapshot } from '@/session/useHtmlSnapshot';
import { MainWindowActionButton } from '@/components/MobilePrimitives';
import { useHtmlBrowserViewport } from '@/session/useHtmlBrowserViewport';
import { MarkdownFileReader } from '@/session/MarkdownFileReader';
import { RemoteMediaPlayerWebView } from '@/session/mediaPlayerWebView';
import { NativeVideoPlayer } from '@/session/NativeVideoPlayer';
import {
  createTransferProgressMeter,
  formatTransferProgress,
  transferPercent,
  type TransferProgress,
} from '@/session/transferProgress';
import {
  buildFileBrowserGridItems,
  normalizeRemoteOpDirEntries,
  parentRelPath,
  type FileBrowserGridItem,
  type FileBrowserRemoteOpEntry,
  type FileBrowserSortMode,
} from '@/session/fileBrowserGrid';
import { useFileThumbnail } from '@/session/fileThumbnails';
import { ImageLightbox } from '@/session/ImageLightbox';
import { buildMediaPayload } from '@/session/messagePayload';
import type { MobileMessageGalleryImage } from '@/session/messageGallery';
import type { MobileRemoteMediaPresignResult } from '@/session/remoteMedia';
import { downloadRemoteMediaShareTemp, retainRemoteFilePreview } from '@/session/remoteMediaDiskCacheExpo';
import { remoteSessionStore, useRemoteSessions } from '@/session/remoteSessionStore';
import { CindyMakeSessionGate } from '@/session/CindyMakeSessionGate';
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import type { RemoteSession } from '@/session/types';
import { fontWeight, lineHeight, monoFont, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { iconSize, iconStroke, radius, spacing, typeScale } from '@/theme/tokens';

const MAX_RENDERED_LINES = 5000;
const NOTICE_DISMISS_MS = 2500;

type TextPreviewState =
  | { status: 'loading' }
  | { status: 'ready'; lines: string[]; truncated: boolean; totalLines: number; content?: string }
  | { status: 'unavailable'; reason: string; oversize?: boolean; retryable?: boolean };

/**
 * 「渲染态」可用的两类文本:markdown 与 HTML。两者共用同一套双态机(下面
 * TextPreviewPage 的 richView),差别只在渲染载体 —— markdown 经 buildSelectableMarkdownHtml
 * 转成我们自己的 HTML,HTML 生成物则原样进 WebView。
 */
type RichTextKind = 'markdown' | 'html';

type HtmlBrowserActions = Pick<HtmlBrowserChromeProps,
  'meta' | 'busy' | 'notice' | 'onCancelNotice' | 'onClose' | 'onShare' | 'onCopyPath' | 'onAddToTask'>;

interface SiblingListing {
  key: string;
  entries: FileBrowserRemoteOpEntry[];
}

interface ExportToUrlOptions {
  /** 缺省 true:预览播放要可保留的地址;分享下载传 false。 */
  stream?: boolean;
  onProgress?: (uploaded: number, total: number) => void;
  /** 用户取消(如导出提示上的「取消」);页面卸载始终中止。 */
  isCancelled?: () => boolean;
}
type ExportToUrl = (relPath: string, mtimeMs: number, options?: ExportToUrlOptions) => Promise<string>;

/**
 * **入参必须是 `item.relPath`(真实路径),不能是 `item.name`(展示名)。**
 *
 * 这两个字段在 absPath 单文件模式下不等价(review P1,尾随反斜杠第三轮):`absPathItem`
 * 的 name 走 `pathDisplayName`,它 `split(/[\\/]/).filter(Boolean)` —— 把 `\` 一律当分隔符、
 * 再丢掉空段。于是 macOS / Linux 上合法的 `report.html\` 被削成 `report.html`,
 * 一个**不以 HTML 扩展名结尾**的文件就此冒充 HTML 进可执行 WebView。
 *
 * 上一轮修的是判定函数**内部**(`isHtmlFilePreviewCandidate` 改用不削尾的 basename),
 * 但调用方在传参之前就已经把那个字符做掉了 —— 函数再严也拿不回丢掉的信息。
 * `relPath` 两种模式下都是未归一化的真实路径(浏览器模式=被控端 `fs:list` 的原值,
 * absPath 模式=原始绝对路径),所以判定一律以它为输入。
 *
 * `pathDisplayName` 本身不改:它是**展示**函数(`/a/b/` 显示 `b` 是对的),
 * 问题从来不是它归一化,而是它的输出被当成了语义值。
 */
function richTextKindOf(pathOrName: string): RichTextKind | null {
  if (/\.(md|mdx|markdown)$/i.test(pathOrName)) return 'markdown';
  if (isHtmlFilePreviewCandidate(pathOrName)) return 'html';
  return null;
}

/** 音视频类型(复用消息里的 RemoteMediaPlayerWebView 播放器)。同上:吃 relPath 不吃 name。 */
function avKindFor(pathOrName: string): 'video' | 'audio' | null {
  if (/\.(mp4|mov|m4v|webm)$/i.test(pathOrName)) return 'video';
  if (/\.(mp3|m4a|wav|aac|ogg|flac)$/i.test(pathOrName)) return 'audio';
  return null;
}

export default function RemoteFilePreviewScreen() {
  const { sessionId, deviceId } = useLocalSearchParams<{ sessionId: string; deviceId?: string }>();
  return (
    <CindyMakeSessionGate sessionId={String(sessionId ?? '')} deviceId={readRouteString(deviceId) ?? undefined}>
      <RemoteFilePreviewContent />
    </CindyMakeSessionGate>
  );
}

function RemoteFilePreviewContent() {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  const params = useLocalSearchParams<{
    sessionId: string;
    deviceId?: string;
    deviceName?: string;
    relPath?: string;
    absPath?: string;
    sort?: string;
    line?: string;
  }>();
  const sessionId = String(params.sessionId ?? '');
  const routeDeviceId = readRouteString(params.deviceId);
  const deviceId = routeDeviceId ?? remoteSessionStore.getSessionDeviceId(sessionId) ?? '';
  const initialRelPath = readRouteString(params.relPath) ?? '';
  // absPath 单文件模式:workdir 外文件,relPath 通道不可用(详见文件头注释)。
  const singleAbsPath = initialRelPath ? null : readRouteString(params.absPath);
  const sortParam = readRouteString(params.sort);
  const sortMode: FileBrowserSortMode = sortParam === 'mtime' || sortParam === 'size' ? sortParam : 'name';
  // 内容搜索进入时的命中行(只作用于最初打开的那个文件)。
  const targetLineRaw = Number(readRouteString(params.line) ?? '');
  const targetLine = Number.isInteger(targetLineRaw) && targetLineRaw > 0 ? targetLineRaw : null;
  const router = useRouter();
  const previewWindow = useAdaptiveWindow();
  const chromeFrame = usePreviewChromeFrame();
  const [measuredPageWidth, setMeasuredPageWidth] = useState<number | null>(null);
  const pageWidth = measuredPageWidth ?? Math.max(1, previewWindow.width - previewWindow.insets.left - previewWindow.insets.right);
  const { openLink } = useDeviceLink();
  const auth = useAuth();
  const maker = useMobileMakerTransport(deviceId);
  const sessions = useRemoteSessions();
  const knownSession = useMemo(
    () => sessions.find((item) => item.id === sessionId) ?? null,
    [sessionId, sessions],
  );
  const [session, setSession] = useState<RemoteSession | null>(knownSession);
  const workdir = session?.workingDir ?? '';

  // Reuse the browser's listing as well as the body: a synthetic single page
  // would move the already visible file when the directory request completes.
  const [initialSiblings] = useState(() => initialRelPath && workdir
    ? previewSiblings(getCachedListingSync(maker.fileBrowser.cacheScope, workdir, parentRelPath(initialRelPath) ?? '') ?? [], sortMode, initialRelPath)
    : null);
  const [siblings, setSiblings] = useState<FileBrowserGridItem[] | null>(() => (
    initialSiblings ?? (singleAbsPath ? [absPathItem(singleAbsPath)] : null)
  ));
  const [siblingListing, setSiblingListing] = useState<SiblingListing | null>(null);
  const [pageIndex, setPageIndex] = useState(() => Math.max(0, initialSiblings?.findIndex(item => item.relPath === initialRelPath) ?? 0));
  // 屏级焦点(HTML 可执行 WebView 的挂载门之一,见 renderItem 的 visible)。
  // 本屏被压栈(点「发送到会话」→ router.navigate 把会话页推到根 Stack 上)时
  // 路由仍挂载、pageIndex 也不变,只有 focus 会翻。
  const screenFocused = useIsFocused();
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [busyLabel, setBusyLabel] = useState<string | null>(null);
  const [lightboxUrl, setLightboxUrl] = useState<string | null>(null);
  const noticeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // 当前页是否处在「HTML 渲染态」——外层横滑要为它让路(见 pager 的 scrollEnabled)。
  // 渲染 / 源码的切换状态在子页里,所以由子页按页 key 上报;setter 用 key 比对而不是
  // 直接存布尔,避免翻页时「旧页报 false」与「新页报 true」的先后顺序决定结果。
  const [htmlPanPageKey, setHtmlPanPageKey] = useState<string | null>(null);
  const [markdownPagerPageKey, setMarkdownPagerPageKey] = useState<string | null>(null);
  const reportHtmlPan = useCallback((key: string, wants: boolean) => {
    setHtmlPanPageKey((prev) => (wants ? key : (prev === key ? null : prev)));
  }, []);
  // Markdown WebView 的纵向滚动和宽公式横移保留在内层;正文明确横滑由文档
  // 回调后在这里驱动同一个 pager,避免 WebView 与 FlatList 争抢触摸序列。
  const reportMarkdownPager = useCallback((key: string, wants: boolean) => {
    setMarkdownPagerPageKey((prev) => (wants ? key : (prev === key ? null : prev)));
  }, []);

  const showNotice = useCallback((text: string) => {
    setNotice(text);
    if (noticeTimerRef.current) clearTimeout(noticeTimerRef.current);
    noticeTimerRef.current = setTimeout(() => setNotice(null), NOTICE_DISMISS_MS);
  }, []);

  useEffect(() => () => {
    if (noticeTimerRef.current) clearTimeout(noticeTimerRef.current);
  }, []);

  // 卸载标记:导出轮询最长 2 分钟,用户中途离开页面时必须中止循环,
  // 不能靠 busyLabel(只防并发)兜底。
  const unmountedRef = useRef(false);
  useEffect(() => {
    unmountedRef.current = false;
    return () => { unmountedRef.current = true; };
  }, []);

  // deviceUnresponsive 进依赖(review P1):深链进入且无缓存会话时,首次
  // getSession 若撞上熔断 open 会拿到 DEVICE_UNRESPONSIVE 快速失败;本页只
  // track openLink、不持有 topic,恢复 rehydrate 的 reseed 也覆盖不到——不随
  // 熔断状态翻转重跑的话,探测成功后预览页仍永久空白。翻转重跑最多多发一次
  // 轻量请求(open 期间是本地快速失败,零管道流量)。
  const unresponsiveDevices = useUnresponsiveDevices();
  const deviceUnresponsive = !!deviceId && unresponsiveDevices.has(deviceId);
  // 熔断恢复代数(review P1):open→closed 翻转沿 +1。仅重试 getSession 不够——
  // 会话已缓存时,同目录 pager 可能已退化成单文件、文本/PDF/音视频子页已落进
  // 失败态,而子页用 requestedRef/loadedRef 防重复请求,失败后绝不自行重试。
  // 代数驱动两件事:pager effect 重列目录;非 PDF 子页通过 FlatList key 整体
  // 重挂载(refs 归零、重新拉取)。PDF 保持已加载 WebView 的稳定 key,仅在
  // 上次导出失败且代数前进时由 PdfPreviewPage 原地重试,避免恢复沿重置阅读位置。
  const [recoveryEpoch, setRecoveryEpoch] = useState(0);
  const prevBreakerStateRef = useRef({ deviceId, unresponsive: deviceUnresponsive });
  useEffect(() => {
    const prev = prevBreakerStateRef.current;
    prevBreakerStateRef.current = { deviceId, unresponsive: deviceUnresponsive };
    // 换设备不是恢复沿(review):页面保持挂载但路由参数换了设备时,「上一台
    // 未响应、这一台正常」不该触发整个 pager 重挂载——新设备的加载由各 effect
    // 的 deviceId 依赖自然驱动。
    if (prev.deviceId !== deviceId) return;
    if (prev.unresponsive && !deviceUnresponsive) setRecoveryEpoch((epoch) => epoch + 1);
  }, [deviceId, deviceUnresponsive]);
  useEffect(() => {
    if (knownSession) {
      setSession(knownSession);
      return;
    }
    if (!deviceId || !sessionId) return;
    let cancelled = false;
    void withTransientRemoteRetry(async () => {
      await openLink(deviceId);
      return maker.getSession(sessionId);
    })
      .then((loaded) => {
        if (cancelled) return;
        if (!CINDY_MAKE_ENABLED && isCindyMakeSource(loaded?.source)) {
          router.replace('/');
          return;
        }
        setSession(loaded);
        // 清掉熔断 open 期间留下的错误快照,恢复后不再残留降级横幅。
        setError(null);
      })
      .catch((err) => { if (!cancelled) setError(formatRemoteError(err)); });
    return () => { cancelled = true; };
  }, [deviceId, deviceUnresponsive, knownSession, maker, openLink, recoveryEpoch, router, sessionId]);

  // absPath 单文件模式:不列目录,直接以合成 item 装单页 pager。
  useEffect(() => {
    if (!singleAbsPath) return;
    setSiblings([absPathItem(singleAbsPath)]);
    setPageIndex(0);
  }, [singleAbsPath]);

  // 同目录 pager 远端数据:只在目录来源或恢复代数变化时重列。语言 / 排序变化
  // 只消费下面缓存的原始目录项重建展示模型,不能为翻译重新请求设备。
  useEffect(() => {
    if (!deviceId || !workdir || !initialRelPath) return undefined;
    setSiblings((previous) => previous ?? [fallbackItem(initialRelPath)]);
    let cancelled = false;
    const dirRel = parentRelPath(initialRelPath) ?? '';
    const listingKey = `${deviceId}\u0000${workdir}\u0000${dirRel}`;
    void withTransientRemoteRetry(async () => {
      await openLink(deviceId);
      return maker.fileBrowser.listDir(workdir, dirRel);
    })
      .then((raw) => {
        if (cancelled) return;
        const entries = normalizeRemoteOpDirEntries(raw);
        storeCachedListing(maker.fileBrowser.cacheScope, workdir, dirRel, entries);
        setSiblingListing({ key: listingKey, entries });
      })
      // A failed background refresh must keep the visible file and neighbours.
      .catch(() => undefined);
    return () => {
      cancelled = true;
    };
  }, [deviceId, initialRelPath, maker, openLink, recoveryEpoch, workdir]);

  // 同目录 pager 展示投影:语言 / 排序变化只在本地重建 metaLabel 与顺序。
  // 重建时锚定「当前可见文件」而非固定 initialRelPath(review P1):用户已翻页后,
  // 重置回初始文件会让 FlatList 的原生滚动位置与 pageIndex(标题 / 分享 / 下载
  // 的目标)指向两个不同文件。setPageIndex 后再显式重锚一次(initialScrollIndex
  // 只在首挂载生效,items key 变化不会重置 contentOffset)。
  useEffect(() => {
    if (!deviceId || !workdir || !initialRelPath || !siblingListing) return undefined;
    const dirRel = parentRelPath(initialRelPath) ?? '';
    const listingKey = `${deviceId}\u0000${workdir}\u0000${dirRel}`;
    if (siblingListing.key !== listingKey) return undefined;
    let cancelled = false;
    const anchorRelPath = currentRelPathRef.current ?? initialRelPath;
    const anchorTo = (index: number): void => {
      if (index === pageIndexRef.current) return;
      setPageIndex(index);
      requestAnimationFrame(() => {
        if (!cancelled) {
          pagerRef.current?.scrollToOffset({ animated: false, offset: index * pageWidthRef.current });
        }
      });
    };
    // 图片已统一走浏览页的 ImageLightbox,翻页器只装非图片文件;
    // 仅当直接以图片路径进入(旧链路兜底)时保留该图片单页。
    const files = previewSiblings(siblingListing.entries, sortMode, initialRelPath, anchorRelPath);
    let index = files.findIndex((item) => item.relPath === anchorRelPath);
    if (index < 0) index = files.findIndex((item) => item.relPath === initialRelPath);
    if (files.length === 0 || index < 0) {
      setSiblings([fallbackItem(initialRelPath)]);
      anchorTo(0);
    } else {
      setSiblings(files);
      anchorTo(index);
    }
    return () => {
      cancelled = true;
    };
  }, [deviceId, i18nInstance.language, initialRelPath, siblingListing, sortMode, workdir]);

  const current = siblings?.[pageIndex] ?? null;
  const pageIndexRef = useRef(pageIndex);
  pageIndexRef.current = pageIndex;
  const pagerRef = useRef<FlatList<FileBrowserGridItem>>(null);
  const moveMarkdownPager = useCallback((key: string, direction: 'previous' | 'next') => {
    if (key !== current?.key || !siblings) return;
    const next = pageIndex + (direction === 'next' ? 1 : -1);
    if (next < 0 || next >= siblings.length) return;
    pagerRef.current?.scrollToOffset({ animated: true, offset: next * pageWidth });
  }, [current?.key, pageIndex, pageWidth, siblings]);
  // 当前可见文件路径镜像(pager 重建锚定用;不能进上面 effect 的依赖,否则
  // 每次翻页都会重列目录)。
  const currentRelPathRef = useRef<string | null>(null);
  useEffect(() => {
    currentRelPathRef.current = current?.relPath ?? null;
  }, [current]);
  // pageWidth 镜像:重锚回调里读现值,不把 pageWidth 拉进列表 effect 依赖
  // (旋转已有专门的重锚 effect)。
  const pageWidthRef = useRef(pageWidth);
  useEffect(() => {
    pageWidthRef.current = pageWidth;
  }, [pageWidth]);

  // 旋转(宽度变化)时按当前页重锚:FlatList 保留的是旧宽度下的像素 contentOffset,
  // 不重锚会停在两页中间(处理方式对齐 ImageLightbox)。
  useEffect(() => {
    pagerRef.current?.scrollToOffset({ animated: false, offset: pageIndex * pageWidth });
    // pageIndex 不进依赖:翻页由手势驱动,这里只响应宽度突变
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageWidth]);

  const absolutePathOf = useCallback((itemRelPath: string) => {
    // absPath 单文件模式的 item.relPath 本身就是被控端绝对路径,原样返回。
    if (isAbsolutePathShape(itemRelPath)) return itemRelPath;
    if (!workdir) return itemRelPath;
    // 分隔符判定走共享实现(review P2):原先用 `workdir.includes('\\')`,而 POSIX 上反斜杠是
    // 合法目录名字符 —— workdir `/tmp/a\b` 会被误判成 Windows,`pages/index.html` 被改写成
    // `pages\index.html`,于是 HTML 基目录算成 `/tmp/a\b\pages`,该页所有同目录资源取件失败。
    // 同一根因在 resolveHtmlResourcePath 里也出现过,判定各写一份正是「修一处漏一处」的成因。
    return joinRemotePath(workdir, itemRelPath);
  }, [workdir]);

  const presignGet = useCallback(async (ossKey: string) => {
    return auth.apiFetch<MobileRemoteMediaPresignResult>('/api/device-link/media/presign-get', {
      baseUrl: DEVICE_LINK_API_BASE_URL,
      method: 'POST',
      body: { key: ossKey },
    });
  }, [auth]);

  /**
   * 回收资源取件产生的 OSS 对象(与会话页 deleteRemoteMediaObject 同一端点与语义)。
   * 空 ossKey(inline 缩略图 / 缓存命中)没有在世对象,跳过。
   */
  const deleteResourceOssObject = useCallback((ossKey: string) => {
    if (!ossKey) return;
    void auth.apiFetch('/api/device-link/media', {
      baseUrl: DEVICE_LINK_API_BASE_URL,
      method: 'DELETE',
      body: { key: ossKey },
    }).catch(() => undefined);
  }, [auth]);

  /**
   * 两段式导出 → presign 下载地址(图片/PDF/音视频原件与「下载原文件」共用)。
   * 实现在 fileBrowserExport(与浏览页长按分享共用):path+mtime 缓存、
   * 轮询瞬断重试、卸载中止。
   * absPath 单文件模式改走 media:fetch 绝对路径取件(exportFile* 对 workdir
   * 外路径一律拒绝),relPath/mtime 参数此时被忽略。
   */
  const exportToUrl = useCallback(
    (relPath: string, mtimeMs: number, options?: ExportToUrlOptions): Promise<string> => {
      const stream = options?.stream ?? true;
      const isCancelled = () => unmountedRef.current || options?.isCancelled?.() === true;
      if (singleAbsPath) {
        return fetchRemoteAbsFileToUrl(
          { maker, deviceId, openLink, presignGet, stream, isCancelled, deleteOssObject: deleteResourceOssObject },
          singleAbsPath,
        );
      }
      return exportRemoteFileToUrl(
        {
          maker,
          deviceId,
          openLink,
          presignGet,
          stream,
          isCancelled,
          onProgress: options?.onProgress,
          deleteOssObject: deleteResourceOssObject,
        },
        workdir,
        relPath,
        mtimeMs,
      );
    },
    [deleteResourceOssObject, deviceId, maker, openLink, presignGet, singleAbsPath, workdir],
  );

  // SSH 远程工作区的取件上下文:三项必须同时给(被控端 parseSshMediaOrigin 会按
  // sessionId 反查会话库逐项比对);本机会话为 null,取件走被控桌面本机路径。
  const sshMediaContext = useMemo((): RemoteMediaSshContext | null => {
    const remoteHostId = session?.remoteHostId?.trim();
    if (!remoteHostId || !sessionId || !workdir) return null;
    return { sessionId, remoteHostId, workdir };
  }, [session?.remoteHostId, sessionId, workdir]);

  const prepareHtmlPreview = useCallback<PrepareMobileHtmlPreview>(
    (absPath, signal, onProgress, preferCache) => prepareMobileHtmlPreview(absPath, {
      maker, deviceId, openLink, presignGet, ssh: sshMediaContext,
      deleteOssObject: deleteResourceOssObject,
    }, signal, onProgress, preferCache),
    [deleteResourceOssObject, deviceId, maker, openLink, presignGet, sshMediaContext],
  );

  // 文本预览读文件也走瞬断重试 + openLink(与列表/搜索/导出同一路径),
  // relay 短暂重连不再把预览页打成「读取失败」。
  // absPath 单文件模式走 text-file:read-preview(被控端绝对路径文本通道),
  // 回包适配成 readFile 同构结果,文本页零分支。
  const readTextFile = useCallback(
    (relPath: string, signal?: AbortSignal): Promise<FileBrowserReadFileResult> =>
      withTransientRemoteRetry(async () => {
        if (signal?.aborted) throw new Error('PREVIEW_CANCELLED');
        await openLink(deviceId);
        if (signal?.aborted) throw new Error('PREVIEW_CANCELLED');
        const startedAt = Date.now();
        const channel = singleAbsPath ? 'text-preview' : 'read-file';
        try {
          const res = singleAbsPath
            ? adaptTextFilePreviewResult(singleAbsPath, await maker.fs.readTextFilePreview(singleAbsPath, { signal }))
            : await maker.fileBrowser.readFile(workdir, relPath, { acceptGzip: true });
          // Whole-text reads share the relay with rendered-HTML resource requests; size only.
          // gzip 回包是压缩数据的 base64,与纯文本字符数分字段记录,避免两种口径混用。
          mobileDebugLog('debug', 'files', 'preview text read', {
            channel,
            ms: Date.now() - startedAt,
            ...(res.ok
              ? res.data.contentEncoding === 'gzip'
                ? { gzip: true, base64Chars: res.data.content.length }
                : { chars: res.data.content.length }
              : { code: res.code }),
          });
          return res;
        } catch (error) {
          // 慢失败同样留痕:抛错触发重试时恰好漏掉最慢的样本。
          // 走 errorText() 脱敏:错误串可能携带路径或签名 URL,不得进入 files 日志。
          mobileDebugLog('debug', 'files', 'preview text read failed', {
            channel,
            ms: Date.now() - startedAt,
            error: errorText(error),
          });
          throw error;
        }
      }),
    [deviceId, maker, openLink, singleAbsPath, workdir],
  );

  // 进行中的「下载原文件 / 分享」:提示上点「取消」即标记本次已取消并立刻收起提示,
  // 之后的结果(含失败)一律丢弃,不再弹分享单;手机侧下载阶段随之中止。
  const exportRunRef = useRef<{ cancelled: boolean; abort: AbortController } | null>(null);
  const cancelExport = useCallback(() => {
    const run = exportRunRef.current;
    if (!run) return;
    run.cancelled = true;
    run.abort.abort();
    exportRunRef.current = null;
    setBusyLabel(null);
  }, []);
  // 离开预览页同样取消(与文件页一致,失焦即算离开):不再下载,也不在下一屏弹分享单。
  useFocusEffect(useCallback(() => cancelExport, [cancelExport]));

  const downloadAndShare = useCallback(async (item: FileBrowserGridItem) => {
    if (busyLabel) return;
    const run = { cancelled: false, abort: new AbortController() };
    exportRunRef.current = run;
    setBusyLabel(t('files.preview.exporting'));
    try {
      const url = await exportToUrl(item.relPath, item.mtimeMs, {
        stream: false,
        isCancelled: () => run.cancelled,
      });
      // The copy helper also releases a late staging result after cancellation.
      // 传原始文件名:分享单按真实扩展名识别类型(PDF/视频等非图片 mime 不在
      // extOfMime 映射里,不带名字会落成 .img 让接收方无法预览)。
      const mime = shareMimeForFileName(item.name);
      const localUri = await downloadRemoteMediaShareTemp(url, mime, item.name, run.abort.signal);
      if (run.cancelled) return;
      if (!localUri) throw new Error(t('files.preview.downloadFailed'));
      const sharing = await import('expo-sharing');
      if (run.cancelled) return;
      await sharing.shareAsync(localUri, { mimeType: mime });
    } catch (err) {
      if (!run.cancelled) showNotice(formatRemoteError(err));
    } finally {
      if (exportRunRef.current === run) {
        exportRunRef.current = null;
        setBusyLabel(null);
      }
    }
  }, [busyLabel, exportToUrl, showNotice, t]);

  const copyPath = useCallback(async (item: FileBrowserGridItem) => {
    await Clipboard.setStringAsync(absolutePathOf(item.relPath));
    showNotice(t('files.preview.copiedPath'));
  }, [absolutePathOf, showNotice, t]);

  const sendToSession = useCallback((item: FileBrowserGridItem) => {
    const merged = mergePathIntoComposerDraft(sessionId, item.relPath);
    router.navigate({
      pathname: '/sessions/[sessionId]',
      params: {
        sessionId,
        deviceId,
        draft: merged,
        focusComposerRequestKey: String(Date.now()),
      },
    });
  }, [deviceId, router, sessionId]);

  const lightboxImages = useMemo((): readonly MobileMessageGalleryImage[] => {
    if (!lightboxUrl || !current) return [];
    const payload = buildMediaPayload({ kind: 'image', url: lightboxUrl, previewable: true }, current.name);
    if (payload.kind !== 'media') return [];
    return [{
      key: `file:${current.relPath}`,
      title: current.name,
      url: lightboxUrl,
      payload,
    }];
  }, [current, lightboxUrl]);

  if (!current || !siblings) {
    const pendingPath = singleAbsPath ?? initialRelPath;
    // HTML opens straight into the floating browser chrome; the classic header would flash first.
    if (richTextKindOf(pendingPath) === 'html') {
      const retry = () => { setError(null); setRecoveryEpoch((epoch) => epoch + 1); };
      // Pending disables address editing and the menu, so these handlers stay unreachable.
      const noop = () => {};
      return (
        <SafeAreaView edges={[]} style={styles.safeArea} testID="filePreview.screen">
          <View style={styles.centerFill}>
            {error ? <>
              <Text style={styles.hintText}>{t('files.preview.readFailed')}</Text>
              <MainWindowActionButton action={{ label: t('files.preview.retry'), onPress: retry }} />
            </> : <ActivityIndicator color={colors.textTertiary} />}
          </View>
          <HtmlBrowserChrome
            title={pathDisplayName(pendingPath)}
            path={absolutePathOf(pendingPath)}
            address={absolutePathOf(pendingPath)}
            onNavigate={() => true}
            top={chromeFrame.top}
            bottom={chromeFrame.bottom}
            left={chromeFrame.left}
            right={chromeFrame.right}
            canGoBack={false}
            canGoForward={false}
            source={false}
            busy
            pending
            loading={!error}
            onClose={() => goBackGuarded(router)}
            onBack={noop}
            onForward={noop}
            onReload={retry}
            onShare={noop}
            onCopyPath={noop}
            onAddToTask={noop}
            onToggleSource={noop}
          />
        </SafeAreaView>
      );
    }
    return (
      <SafeAreaView edges={[]} style={styles.safeArea} testID="filePreview.screen">
        <View style={styles.centerFill}>
          {error ? <>
            <Text style={styles.hintText}>{t('files.preview.readFailed')}</Text>
            <MainWindowActionButton action={{ label: t('files.preview.retry'), onPress: () => {
              setError(null);
              setRecoveryEpoch((epoch) => epoch + 1);
            } }} />
          </> : <ActivityIndicator color={colors.textTertiary} />}
        </View>
        <HtmlBrowserChrome
          document
          title={pathDisplayName(pendingPath)}
          path={absolutePathOf(pendingPath)}
          top={chromeFrame.top}
          bottom={chromeFrame.bottom}
          left={chromeFrame.left}
          right={chromeFrame.right}
          busy
          pending
          onClose={() => goBackGuarded(router)}
          onShare={() => {}}
          onCopyPath={() => {}}
          onAddToTask={() => {}}
        />
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView edges={[]} style={styles.safeArea} testID="filePreview.screen">
      <FlatList
        onLayout={event => setMeasuredPageWidth(Math.max(1, event.nativeEvent.layout.width))}
        data={siblings}
        getItemLayout={(_, index) => ({ index, length: pageWidth, offset: pageWidth * index })}
        ref={pagerRef}
        horizontal
        initialScrollIndex={pageIndex}
        keyExtractor={(item) => (
          item.previewKind === 'pdf' ? item.key : `${item.key}:${recoveryEpoch}`
        )}
        onMomentumScrollEnd={(event) => {
          const next = Math.round(event.nativeEvent.contentOffset.x / pageWidth);
          if (next !== pageIndex && next >= 0 && next < siblings.length) setPageIndex(next);
        }}
        pagingEnabled
        renderItem={({ item, index }) => (
          <View style={{ width: pageWidth }}>
            <FilePreviewPage
              deviceId={deviceId}
              absolutePathOf={absolutePathOf}
              active={Math.abs(index - pageIndex) <= 1}
              // HTML 渲染态只在真正可见的当前页挂载可执行 WebView(review P1):
              // active 含相邻页(文本预取要它),但相邻页提前挂 WebView 会让用户还没
              // 滑到的文件里的脚本 / 计时器 / 网络请求先跑起来,滑走后还继续跑。
              //
              // **屏级焦点也是门的一部分**(review P1 第二轮):本屏被压栈时(从深链进
              // 预览再点「发送到会话」,router.navigate 把会话页推到根 Stack 上)路由默认
              // 仍挂载、pageIndex 也不变 —— 只看 pageIndex 的话 WebView 会在用户已经回到
              // 对话界面之后继续跑脚本。screenFocused 翻假即卸载。
              visible={screenFocused && index === pageIndex}
              onHtmlPanChange={reportHtmlPan}
              onMarkdownPagerChange={reportMarkdownPager}
              onMarkdownPageSwipe={moveMarkdownPager}
              exportToUrl={exportToUrl}
              prepareHtmlPreview={prepareHtmlPreview}
              item={item}
              maker={maker}
              onDownload={() => void downloadAndShare(item)}
              htmlBrowserActions={{
                meta: [
                  `${index + 1} / ${siblings.length}`,
                  ...(item.sizeBytes > 0 ? [formatByteSize(item.sizeBytes)] : []),
                ].join(' · '),
                busy: !!busyLabel,
                notice: busyLabel ?? notice,
                // busyLabel 只由导出 / 分享设置,进行中的提示带「取消」。
                ...(busyLabel ? { onCancelNotice: cancelExport } : {}),
                onClose: () => goBackGuarded(router),
                onShare: () => void downloadAndShare(item),
                onCopyPath: () => void copyPath(item),
                onAddToTask: () => sendToSession(item),
              }}
              // chat-text-quote:markdown 渲染态选中文字 → 引用进会话草稿
              // (携带当前文件路径,— source: 行),随即切回对话界面——与
              // 「发送到会话」(sendToSession)的图片/路径处理一致(产品决策);
              // 引用在全局 store,导航后 composer 胶囊即时可见。
              onQuoteSelection={(text) => {
                appendQuote(sessionId, {
                  text: truncateQuoteText(text),
                  sourcePath: item.relPath,
                });
                router.navigate({
                  pathname: '/sessions/[sessionId]',
                  params: {
                    sessionId,
                    deviceId,
                    focusComposerRequestKey: String(Date.now()),
                  },
                });
              }}
              readTextFile={readTextFile}
              onOpenLightbox={setLightboxUrl}
              recoveryEpoch={recoveryEpoch}
              targetLine={item.relPath === (singleAbsPath ?? initialRelPath) ? targetLine : null}
              workdir={workdir}
            />
          </View>
        )}
        // PDF 与「HTML 渲染态」都要把水平拖动完整留给内层 WebView(review P2):
        // 固定宽度布局或用户放大后需要横向平移,外层 pager 会抢走手势并切到相邻文件,
        // 超出视口的内容永远看不到。手势仲裁(区分内层平移与翻页)在 RN 上要自己写一套
        // 竞态裁决,属独立改动;这里沿用本文件对 PDF 已经采用的同一口径 —— 想翻页就切到
        // 「源码」态(源码是竖向列表,不冲突),或 Done 返回列表。
        scrollEnabled={current.previewKind !== 'pdf' && htmlPanPageKey !== current.key && markdownPagerPageKey !== current.key}
        showsHorizontalScrollIndicator={false}
        windowSize={3}
      />

      {lightboxImages.length > 0 ? (
        <ImageLightbox
          images={lightboxImages}
          initialUrl={lightboxImages[0].url}
          onClose={() => setLightboxUrl(null)}
        />
      ) : null}
    </SafeAreaView>
  );
}

/* ------------------------------ 页面组件 ------------------------------ */

function FilePreviewPage({
  deviceId,
  absolutePathOf,
  active,
  exportToUrl,
  prepareHtmlPreview,
  item,
  htmlBrowserActions,
  maker,
  onDownload,
  onHtmlPanChange,
  onMarkdownPagerChange,
  onMarkdownPageSwipe,
  onOpenLightbox,
  onQuoteSelection,
  readTextFile,
  recoveryEpoch,
  targetLine,
  visible,
  workdir,
}: {
  deviceId: string;
  absolutePathOf(relPath: string): string;
  active: boolean;
  exportToUrl: ExportToUrl;
  prepareHtmlPreview: PrepareMobileHtmlPreview;
  item: FileBrowserGridItem;
  htmlBrowserActions: HtmlBrowserActions;
  maker: Pick<MobileMakerTransport, 'fileBrowser'>;
  onDownload(): void;
  /** 上报本页是否处在 HTML 渲染态(外层 pager 据此让出横滑,仅文本页产出)。 */
  onHtmlPanChange?: (key: string, wants: boolean) => void;
  onMarkdownPagerChange?: (key: string, wants: boolean) => void;
  onMarkdownPageSwipe?: (key: string, direction: 'previous' | 'next') => void;
  onOpenLightbox(url: string): void;
  /** chat-text-quote:markdown 渲染态的选中引用回调(仅文本页消费)。 */
  onQuoteSelection?: (text: string) => void;
  readTextFile(relPath: string, signal?: AbortSignal): Promise<FileBrowserReadFileResult>;
  recoveryEpoch: number;
  targetLine: number | null;
  /** 是否真正可见的当前页(可执行渲染态的挂载门,见调用处说明)。 */
  visible: boolean;
  workdir: string;
}) {
  const { t } = useTranslation();
  const styles = useThemedStyles(makeStyles);
  const insets = useSafeAreaInsets();
  const chromeFrame = usePreviewChromeFrame();
  const contentPadding = {
    paddingTop: chromeFrame.contentTop,
    paddingBottom: insets.bottom + spacing.xs,
    paddingLeft: insets.left,
    paddingRight: insets.right,
  };
  const avKind = avKindFor(item.relPath);
  let content;
  if (item.thumb === 'image') {
    content = (
      <ImagePreviewPage
        active={active}
        exportToUrl={exportToUrl}
        item={item}
        maker={maker}
        onOpenLightbox={onOpenLightbox}
        workdir={workdir}
      />
    );
  } else if (item.previewKind === 'pdf') {
    content = <PdfPreviewPage active={active} exportToUrl={exportToUrl} item={item} onDownload={onDownload} recoveryEpoch={recoveryEpoch} workdir={workdir} />;
  } else if (avKind) {
    content = <AvPreviewPage active={active} exportToUrl={exportToUrl} item={item} kind={avKind} onDownload={onDownload} visible={visible} workdir={workdir} />;
  } else if (item.thumb === 'doc') {
    return (
      <TextPreviewPage
        key={maker.fileBrowser.cacheScope}
        cacheScope={maker.fileBrowser.cacheScope}
        deviceId={deviceId}
        absolutePathOf={absolutePathOf}
        active={active}
        prepareHtmlPreview={prepareHtmlPreview}
        item={item}
        htmlBrowserActions={htmlBrowserActions}
        onDownload={onDownload}
        onHtmlPanChange={onHtmlPanChange}
        onMarkdownPagerChange={onMarkdownPagerChange}
        onMarkdownPageSwipe={onMarkdownPageSwipe}
        onQuoteSelection={onQuoteSelection}
        readTextFile={readTextFile}
        targetLine={targetLine}
        visible={visible}
        workdir={workdir}
      />
    );
  } else {
    content = <UnsupportedPage item={item} onDownload={onDownload} reason={t('files.preview.unsupportedType')} />;
  }
  return (
    <View style={styles.textPage}>
      <View style={[styles.textPage, item.previewKind !== 'pdf' && contentPadding]}>{content}</View>
      {visible ? <HtmlBrowserChrome
        document
        {...htmlBrowserActions}
        title={item.name}
        path={absolutePathOf(item.relPath)}
        top={chromeFrame.top}
        bottom={chromeFrame.bottom}
        left={chromeFrame.left}
        right={chromeFrame.right}
      /> : null}
    </View>
  );
}

/**
 * 音视频页:导出→presign→播放(切后台/翻页失活自动暂停,回到本页不自动续播)。
 * 视频走系统原生播放器;音频、data: 地址,以及原生播放器报错的格式(如 iOS 上的 WebM)
 * 仍走消息同款 WebView 播放器——原来能在 WebView 里播的文件不能因换播放器而退化。
 * 电脑上传期间显示真实百分比与速度,旧版电脑不回报字节时只显示转圈。
 */
function AvPreviewPage({
  active,
  exportToUrl,
  item,
  kind,
  onDownload,
  visible,
  workdir,
}: {
  active: boolean;
  exportToUrl: ExportToUrl;
  item: FileBrowserGridItem;
  kind: 'video' | 'audio';
  onDownload(): void;
  /** 是否真正可见的当前页:失活(翻页/压栈)时暂停播放,见 RemoteMediaPlayerWebView。 */
  visible: boolean;
  workdir: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  const [url, setUrl] = useState<string | null>(null);
  const [failed, setFailed] = useState(false);
  const [nativeFailed, setNativeFailed] = useState(false);
  const [progress, setProgress] = useState<TransferProgress | null>(null);
  const [requestEpoch, setRequestEpoch] = useState(0);
  const requestedRef = useRef(false);
  const retry = useCallback(() => {
    requestedRef.current = false;
    setRequestEpoch((epoch) => epoch + 1);
  }, []);
  const handleNativePlaybackError = useCallback((detail: string) => {
    mobileDebugLog('warn', 'files', 'native video failed, falling back to web player', {
      error: sanitizeDiagnosticText(detail),
    });
    setNativeFailed(true);
  }, []);

  useEffect(() => {
    if (!active || requestedRef.current || !workdir) return undefined;
    requestedRef.current = true;
    let cancelled = false;
    const startedAt = Date.now();
    const measure = createTransferProgressMeter();
    mobileDebugLog('debug', 'files', 'av preview fetch start', { kind, size: item.sizeBytes });
    setFailed(false);
    setProgress(null);
    void exportToUrl(item.relPath, item.mtimeMs, {
      onProgress: (uploaded, total) => {
        if (!cancelled) setProgress(measure(uploaded, total));
      },
    })
      .then((next) => {
        mobileDebugLog('debug', 'files', 'av preview fetch done', {
          kind, ms: Date.now() - startedAt, source: resolvedUrlKind(next), left: cancelled,
        });
        if (cancelled) return;
        setNativeFailed(false);
        setUrl(next);
      })
      .catch((err) => {
        mobileDebugLog(cancelled ? 'debug' : 'warn', 'files', 'av preview fetch failed', {
          kind, ms: Date.now() - startedAt, left: cancelled, error: errorText(err),
        });
        if (cancelled) return;
        setFailed(true);
      });
    return () => {
      cancelled = true;
    };
  }, [active, exportToUrl, item.mtimeMs, item.relPath, item.sizeBytes, kind, requestEpoch, workdir]);

  if (failed) {
    return <UnsupportedPage item={item} onDownload={onDownload} reason={t('files.preview.readFailed')} onRetry={retry} />;
  }
  if (!url) {
    return (
      <View style={styles.centerFill} testID="filePreview.avLoading">
        <ActivityIndicator color={colors.textTertiary} />
        <Text style={styles.hintText}>{kind === 'video' ? t('files.preview.fetchingVideo') : t('files.preview.fetchingAudio')}</Text>
        {progress ? (
          <View style={styles.fetchProgress} testID="filePreview.avProgress">
            <View
              accessibilityRole="progressbar"
              accessibilityValue={{ min: 0, max: 100, now: transferPercent(progress) }}
              style={styles.fetchProgressTrack}
            >
              <View style={[styles.fetchProgressFill, { width: `${transferPercent(progress)}%` }]} />
            </View>
            <Text style={styles.fetchProgressText}>{formatTransferProgress(progress)}</Text>
          </View>
        ) : null}
      </View>
    );
  }
  if (kind === 'video' && !nativeFailed && !url.startsWith('data:')) {
    return (
      <NativeVideoPlayer
        onError={handleNativePlaybackError}
        testID="filePreview.avPlayer"
        url={url}
        visible={visible}
      />
    );
  }
  return (
    <View style={styles.avPage}>
      <RemoteMediaPlayerWebView
        kind={kind}
        style={styles.avPlayer}
        testID="filePreview.avPlayer"
        title={item.name}
        url={url}
        visible={visible}
      />
    </View>
  );
}

/** PDF 页:导出到 OSS → presign → WebView(iOS WKWebView 原生渲 PDF)。 */
function PdfPreviewPage({
  active,
  exportToUrl,
  item,
  onDownload,
  recoveryEpoch,
  workdir,
}: {
  active: boolean;
  exportToUrl(relPath: string, mtimeMs: number, options?: ExportToUrlOptions): Promise<string>;
  item: FileBrowserGridItem;
  onDownload(): void;
  recoveryEpoch: number;
  workdir: string;
}) {
  const insets = useSafeAreaInsets();
  const chromeFrame = usePreviewChromeFrame();
  const { viewRef, measure, viewportStyle, obscuredContentInsets } = useHtmlBrowserViewport({
    top: chromeFrame.contentTop,
    bottom: insets.bottom + spacing.xs,
    left: insets.left,
    right: insets.right,
  });
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  const [url, setUrl] = useState<string | null>(null);
  const [failure, setFailure] = useState<string | null>(null);
  const [requestEpoch, setRequestEpoch] = useState(0);
  const requestedRef = useRef(false);
  const releaseSourceRef = useRef<(() => void) | undefined>(undefined);
  useEffect(() => () => releaseSourceRef.current?.(), []);
  const latestRecoveryEpochRef = useRef(recoveryEpoch);
  const requestedAtRecoveryEpochRef = useRef(recoveryEpoch);

  useEffect(() => {
    latestRecoveryEpochRef.current = recoveryEpoch;
  }, [recoveryEpoch]);

  // 已成功加载的 PDF 不随设备恢复沿重挂载或重新取 URL;只有上次导出失败,
  // 且失败尝试发生在更早的恢复代数时,才清掉一次性请求门闩原地重试。
  useEffect(() => {
    if (!failure || requestedAtRecoveryEpochRef.current >= recoveryEpoch) return;
    requestedRef.current = false;
    setFailure(null);
    setRequestEpoch((epoch) => epoch + 1);
  }, [failure, recoveryEpoch]);

  useEffect(() => {
    if (!active || requestedRef.current || !workdir) return undefined;
    requestedRef.current = true;
    requestedAtRecoveryEpochRef.current = latestRecoveryEpochRef.current;
    let cancelled = false;
    setFailure(null);
    void exportToUrl(item.relPath, item.mtimeMs, { stream: false })
      .then(preparePdfPreviewSource)
      .then((source) => {
        if (cancelled) { source.release(); return; }
        releaseSourceRef.current?.();
        releaseSourceRef.current = source.release;
        setUrl(source.uri);
      })
      .catch((err) => {
        if (cancelled) return;
        // 保持 requestedRef=true:失败态由 UnsupportedPage 呈现,不在当前
        // 恢复代数里自动循环;下一次设备恢复沿重试,或离开后重新打开。
        setFailure(formatRemoteError(err));
      });
    return () => {
      cancelled = true;
    };
  }, [active, exportToUrl, item.mtimeMs, item.relPath, requestEpoch, workdir]);
  const pdfSource = useMemo(() => (url ? { uri: url } : null), [url]);

  if (failure) {
    return <UnsupportedPage item={item} onDownload={onDownload} reason={t('files.preview.readFailed')}
      onRetry={() => { requestedRef.current = false; setRequestEpoch((epoch) => epoch + 1); }} />;
  }
  if (!pdfSource) {
    return (
      <View style={styles.centerFill} testID="filePreview.pdfLoading">
        <ActivityIndicator color={colors.textTertiary} />
        <Text style={styles.hintText}>{t('files.preview.fetchingPdf')}</Text>
      </View>
    );
  }
  return <View ref={viewRef} onLayout={measure} collapsable={false} style={[styles.pdfView, viewportStyle]}>
    <WebView source={pdfSource} originWhitelist={['https://*', 'http://*', 'file://*']}
      automaticallyAdjustContentInsets={false}
      contentInsetAdjustmentBehavior="never"
      obscuredContentInsets={obscuredContentInsets}
      contentInset={obscuredContentInsets}
      style={styles.pdfView} testID="filePreview.pdfView" />
  </View>;
}

/**
 * 文本/代码页:readFile(acceptGzip)→ 行号列表;OVERSIZE/BINARY 退占位。
 * markdown / HTML(richTextKindOf)多一层「渲染 / 源码」切换,渲染态复用同一份已读文本。
 */
function TextPreviewPage({
  cacheScope,
  deviceId,
  absolutePathOf,
  active,
  prepareHtmlPreview,
  item,
  htmlBrowserActions,
  onDownload,
  onHtmlPanChange,
  onMarkdownPagerChange,
  onMarkdownPageSwipe,
  onQuoteSelection,
  readTextFile,
  targetLine,
  visible,
  workdir,
}: {
  cacheScope: string;
  deviceId: string;
  /** item.relPath → 被控端绝对路径(HTML 资源透传要据此定位同目录)。 */
  absolutePathOf(relPath: string): string;
  active: boolean;
  /** 下载完整目录并返回受控网页预览,签名地址不进入页面。 */
  prepareHtmlPreview: PrepareMobileHtmlPreview;
  item: FileBrowserGridItem;
  htmlBrowserActions: HtmlBrowserActions;
  onDownload(): void;
  /** 上报本页是否处在 HTML 渲染态(外层 pager 据此让出横滑,见调用处说明)。 */
  onHtmlPanChange?: (key: string, wants: boolean) => void;
  onMarkdownPagerChange?: (key: string, wants: boolean) => void;
  onMarkdownPageSwipe?: (key: string, direction: 'previous' | 'next') => void;
  /** chat-text-quote:markdown 渲染态的选中引用回调(源码态暂不支持,见 PR 说明)。 */
  onQuoteSelection?: (text: string) => void;
  /** 屏级注入:readFile 带瞬断重试 + openLink(与列表/搜索/导出同路径)。 */
  readTextFile(relPath: string, signal?: AbortSignal): Promise<FileBrowserReadFileResult>;
  targetLine: number | null;
  /** 是否真正可见的当前页:HTML 渲染态只在可见时挂 WebView(文本预取不受限)。 */
  visible: boolean;
  workdir: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  const richKind = richTextKindOf(item.relPath);
  const insets = useSafeAreaInsets();
  // Sit directly against the safe-area edges; only a small gap separates page content.
  const chromeFrame = usePreviewChromeFrame();
  const browserTop = chromeFrame.top;
  const browserBottom = chromeFrame.bottom;
  const browserContentInset = { top: chromeFrame.contentTop, bottom: browserBottom + (richKind === 'html' ? HTML_BROWSER_CONTROL_SIZE : 0) + spacing.xs };
  const browserRef = useRef<WebView>(null);
  const [website, setWebsite] = useState<WebsiteVisit | null>(null);
  const [browserNavigation, setBrowserNavigation] = useState<{
    preview: MobileHtmlPreview; state: WebViewNavigation;
  } | null>(null);
  // A cached preview renders immediately, including absolute paths without mtime.
  // The bounded text request below refreshes it in the background.
  const cacheable = !!workdir;
  const [state, setState] = useState<TextPreviewState>(() => {
    // Cache identity includes the account, device, workdir and path.
    const cached = cacheable ? getCachedPreviewText(cacheScope, workdir, item.relPath, item.mtimeMs, deviceId) : null;
    return cached
      ? {
          status: 'ready',
          lines: cached.lines,
          totalLines: cached.totalLines,
          truncated: cached.truncated,
          content: cached.content,
        }
      : { status: 'loading' };
  });
  // markdown / HTML 默认渲染态(markdown 带命中行也进渲染态——渲染层按块级
  // data-src-line 定位到覆盖目标行的块并闪高亮;切到源码态仍走精确行号跳转),
  // 可切源码;其余文本恒为源码态。
  const [richView, setRichView] = useState<'rendered' | 'source'>(richKind ? 'rendered' : 'source');
  const loadedRef = useRef(false);
  const [textReloadEpoch, setTextReloadEpoch] = useState(0);
  const codeListRef = useRef<FlatList<string>>(null);
  const scrolledToTargetRef = useRef(false);
  const wantsText = richKind !== 'html' || richView === 'source';

  useEffect(() => {
    if (!active || !wantsText || loadedRef.current || !workdir) return;
    loadedRef.current = true;
    let cancelled = false;
    const abort = new AbortController();
    const unavailable = (value: TextPreviewState) => setState((previous) =>
      previous.status === 'ready' ? previous : value);
    void readTextFile(item.relPath, abort.signal)
      .then((res: FileBrowserReadFileResult) => {
        if (cancelled) return;
        if (!res.ok) {
          // Keep the visible snapshot, but don't seed future opens from text
          // the host has confirmed is no longer previewable.
          if (cacheable && (res.code === 'OVERSIZE' || res.code === 'BINARY_FILE')) {
            storeCachedPreviewText(cacheScope, workdir, item.relPath, item.mtimeMs, null, deviceId);
          }
          // A failed refresh must not hide the text the user is already reading.
          if (res.code === 'OVERSIZE') {
            unavailable({
              status: 'unavailable',
              oversize: true,
              reason: t('files.preview.oversize', {
                size: res.stat ? formatByteSize(res.stat.size) : t('files.preview.oversizeUnknown'),
              }),
            });
          } else if (res.code === 'BINARY_FILE') {
            unavailable({ status: 'unavailable', reason: t('files.preview.binaryFile') });
          } else {
            unavailable({ status: 'unavailable', reason: t('files.preview.readFailed'), retryable: true });
          }
          return;
        }
        const content = res.data.contentEncoding === 'gzip'
          ? decodeGzipBase64Text(res.data.content)
          : res.data.content;
        const allLines = content.split('\n');
        const ready = {
          lines: allLines.slice(0, MAX_RENDERED_LINES),
          totalLines: allLines.length,
          truncated: res.data.truncated === true,
          // 原文只为渲染态(markdown / HTML)保留,普通代码文件不留大字符串。
          content: richKind ? content : undefined,
        };
        if (cacheable) storeCachedPreviewText(cacheScope, workdir, item.relPath, res.data.mtimeMs, ready, deviceId);
        setState({ status: 'ready', ...ready });
      })
      .catch((err) => {
        if (cancelled) return;
        loadedRef.current = false; // 传输层瞬断允许重进重试
        setState((previous) => previous.status === 'ready' ? previous
          : { status: 'unavailable', reason: t('files.preview.readFailed'), retryable: true });
      });
    return () => {
      cancelled = true;
      abort.abort();
      loadedRef.current = false;
    };
  }, [active, wantsText, cacheable, cacheScope, deviceId, item.relPath, richKind, readTextFile, t, workdir, textReloadEpoch]);

  const htmlSnapshot = useHtmlSnapshot(
    absolutePathOf(item.relPath),
    visible && richKind === 'html' && richView === 'rendered' && !website,
    prepareHtmlPreview,
  );
  const [htmlLoadError, setHtmlLoadError] = useState(false);
  useEffect(() => { setHtmlLoadError(false); }, [htmlSnapshot.preview]);
  const htmlError = htmlSnapshot.error || (htmlLoadError ? new Error('HTML_PREVIEW_LOAD_FAILED') : null);
  const htmlErrorCode = htmlError instanceof Error ? htmlError.message : '';
  const htmlErrorMessage = htmlErrorCode === 'HTML_PREVIEW_NATIVE_UNAVAILABLE'
    ? t('files.preview.htmlUpdateMobile')
    : htmlErrorCode === 'COMPLETE_DIRECTORY_LISTING_UNSUPPORTED'
      ? t('files.preview.htmlUpdateDesktop')
      : htmlErrorCode === 'PREVIEW_TOO_LARGE'
        ? t('files.preview.htmlSnapshotTooLarge')
        : t('files.preview.htmlSnapshotFailed');
  const htmlPanWanted = visible && richKind === 'html' && richView === 'rendered'
    && htmlSnapshot.foreground && (!!website || (!!htmlSnapshot.preview && !htmlError));
  useEffect(() => {
    onHtmlPanChange?.(item.key, htmlPanWanted);
    return () => onHtmlPanChange?.(item.key, false);
  }, [htmlPanWanted, item.key, onHtmlPanChange]);
  const markdownPagerWanted = visible && richKind === 'markdown' && richView === 'rendered'
    && state.status === 'ready';
  useEffect(() => {
    onMarkdownPagerChange?.(item.key, markdownPagerWanted);
    return () => onMarkdownPagerChange?.(item.key, false);
  }, [item.key, markdownPagerWanted, onMarkdownPagerChange]);

  if (website) return visible ? <HtmlWebsiteBrowser
    visit={website}
    insets={{ ...browserContentInset, left: insets.left, right: insets.right }}
    chrome={{ top: browserTop, bottom: browserBottom, left: chromeFrame.left, right: chromeFrame.right, onClose: htmlBrowserActions.onClose }}
    onReturn={() => { setBrowserNavigation(null); setWebsite(null); }}
  /> : <View style={styles.textPage} />;

  const retryText = () => {
    loadedRef.current = false;
    setState({ status: 'loading' });
    setTextReloadEpoch((epoch) => epoch + 1);
  };
  const ready = state.status === 'ready' ? state : null;
  const targetIndex = targetLine !== null && targetLine <= (ready?.lines.length ?? 0) ? targetLine - 1 : null;
  const lineNumWidth = String(ready?.lines.length ?? 0).length;
  const clipped = ready && (ready.truncated || ready.totalLines > ready.lines.length) && !(richKind === 'html' && richView === 'rendered');
  const canRenderRich = richKind === 'html' || (richKind !== null && typeof ready?.content === 'string');
  const showRendered = canRenderRich && richView === 'rendered';
  // State belongs to the mounted snapshot, never to a previous file/source/foreground lifetime.
  const navigation = htmlPanWanted && browserNavigation && browserNavigation.preview === htmlSnapshot.preview ? browserNavigation.state : null;
  return (
    <View style={styles.textPage}>
      <View style={styles.textPage}>
      {clipped ? (
        <View style={[styles.truncBar, { marginTop: browserContentInset.top }]} testID="filePreview.truncBanner">
          <Info color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          <Text style={styles.truncText}>
            {ready?.truncated ? t('files.preview.truncated2mb') : t('files.preview.truncatedLines', { lines: MAX_RENDERED_LINES })}
          </Text>
        </View>
      ) : null}
      {showRendered ? (
        richKind === 'html' ? (
          // **只在真正可见的当前页挂载**(review P1):HTML 里的脚本是可执行的不可信
          // 内容,相邻预取页提前挂 WebView 会让用户还没打开的文件里的脚本 / 计时器 /
          // 网络请求先跑起来。离开当前页即卸载 —— 卸载 WebView 是停掉这些东西最彻底
          // 的方式(比 injectJavaScript 去逐个 clearInterval 可靠)。离开后释放快照。
          !visible ? (
            <View style={styles.centerFill} testID="filePreview.htmlOffscreen" />
          ) : htmlError ? (
            <View style={styles.centerFill} testID="filePreview.htmlError">
              <Text style={styles.hintText}>{htmlErrorMessage}</Text>
              <MainWindowActionButton action={{ label: t('files.preview.htmlReload'), onPress: htmlSnapshot.retry }} />
            </View>
          ) : (
            // Measure the viewport while preparing; the reader mounts WebKit only once
            // the guarded snapshot is ready and keeps one loading overlay throughout.
            <HtmlSnapshotReader preview={htmlSnapshot.preview} onError={() => setHtmlLoadError(true)}
              loading={<HtmlPreviewLoading progress={htmlSnapshot.progress} />}
              webViewRef={browserRef}
              viewportInsets={{ ...browserContentInset, left: insets.left, right: insets.right }}
              onNavigationStateChange={(preview, state) => {
                htmlSnapshot.onNavigationStateChange(preview, state);
                setBrowserNavigation({ preview, state });
              }}
            />
          )
        ) : (
          <MarkdownFileReader
            markdown={ready?.content ?? ''}
            viewportInsets={{ ...browserContentInset, top: clipped ? 0 : browserContentInset.top, left: insets.left, right: insets.right }}
            onPageSwipe={onMarkdownPageSwipe ? (direction) => onMarkdownPageSwipe(item.key, direction) : undefined}
            onQuoteSelection={onQuoteSelection}
            targetLine={targetLine}
            testID="filePreview.markdownRendered"
          />
        )
      ) : state.status === 'loading' ? (
        <View style={styles.centerFill}><ActivityIndicator color={colors.textTertiary} /></View>
      ) : state.status === 'unavailable' ? (
        <UnsupportedPage item={item} onDownload={onDownload} reason={state.reason}
          onRetry={state.retryable ? retryText : undefined} />
      ) : (
      <FlatList
        contentContainerStyle={[styles.codeContent, {
          paddingTop: clipped ? spacing.md : browserContentInset.top + spacing.md,
          paddingBottom: browserContentInset.bottom + spacing.md,
          paddingLeft: insets.left + spacing.lg,
          paddingRight: insets.right + spacing.lg,
        }]}
        scrollIndicatorInsets={browserContentInset}
        data={state.lines}
        initialNumToRender={40}
        keyExtractor={(_, index) => String(index)}
        onLayout={() => {
          // 内容搜索进入:列表就绪后跳到命中行(行高不定,先 scrollToIndex,
          // 超出渲染窗时由 onScrollToIndexFailed 按估算行高兜底再补跳)。
          if (targetIndex === null || scrolledToTargetRef.current) return;
          scrolledToTargetRef.current = true;
          setTimeout(() => {
            codeListRef.current?.scrollToIndex({ animated: false, index: targetIndex, viewPosition: 0.3 });
          }, 60);
        }}
        onScrollToIndexFailed={(info) => {
          codeListRef.current?.scrollToOffset({ animated: false, offset: info.averageItemLength * info.index });
          setTimeout(() => {
            codeListRef.current?.scrollToIndex({ animated: false, index: info.index, viewPosition: 0.3 });
          }, 220);
        }}
        ref={codeListRef}
        testID={visible ? 'filePreview.sourceReady' : undefined}
        renderItem={({ item: line, index }) => (
          <View style={[styles.codeLine, index === targetIndex && styles.codeLineHit]}>
            <Text style={styles.codeLineNum}>{String(index + 1).padStart(lineNumWidth, ' ')}</Text>
            <Text selectable style={styles.codeText}>{line.length > 0 ? line : ' '}</Text>
          </View>
        )}
        style={styles.codeList}
      />
      )}
      </View>
      {richKind !== 'html' && visible ? <HtmlBrowserChrome
        document
        {...htmlBrowserActions}
        title={item.name}
        path={absolutePathOf(item.relPath)}
        top={browserTop}
        bottom={browserBottom}
        left={chromeFrame.left}
        right={chromeFrame.right}
        source={richView === 'source'}
        onToggleSource={canRenderRich ? () => setRichView(value => value === 'rendered' ? 'source' : 'rendered') : undefined}
      /> : null}
      {richKind === 'html' && visible ? (
        <HtmlBrowserChrome
          {...htmlBrowserActions}
          title={item.name}
          path={absolutePathOf(item.relPath)}
          address={absolutePathOf(item.relPath)}
          onNavigate={(input) => {
            if (input.trim() === absolutePathOf(item.relPath)) return true;
            const url = normalizeBrowserAddress(input);
            if (!url) { Alert.alert(t('files.preview.browserInvalidAddress')); return false; }
            // Start closing before disabling the snapshot hook; wait for this exact promise.
            const snapshotClosed = htmlSnapshot.preview?.close() ?? Promise.resolve();
            setRichView('rendered');
            setWebsite({ url, snapshotClosed });
            return true;
          }}
          top={browserTop}
          bottom={browserBottom}
          left={chromeFrame.left}
          right={chromeFrame.right}
          source={richView === 'source'}
          loading={richView === 'rendered' && !htmlError && (!htmlSnapshot.preview || navigation?.loading === true)}
          canGoBack={richView === 'source' || navigation?.canGoBack === true}
          canGoForward={navigation?.canGoForward === true}
          onBack={() => { if (richView === 'source') setRichView('rendered'); else if (navigation?.canGoBack) browserRef.current?.goBack(); }}
          onForward={() => { if (navigation?.canGoForward) browserRef.current?.goForward(); }}
          onReload={() => {
            // Reload means fresh remote bytes in both views, not a reload of the cached local URL.
            loadedRef.current = false;
            setState({ status: 'loading' });
            setTextReloadEpoch((value) => value + 1);
            htmlSnapshot.retry();
          }}
          onToggleSource={() => setRichView((value) => value === 'rendered' ? 'source' : 'rendered')}
        />
      ) : null}
    </View>
  );
}

/** 图片页:缩略图立即显示,原图导出就绪后无缝换源;点按进 lightbox 缩放。 */
function ImagePreviewPage({
  active,
  exportToUrl,
  item,
  maker,
  onOpenLightbox,
  workdir,
}: {
  active: boolean;
  exportToUrl(relPath: string, mtimeMs: number, options?: ExportToUrlOptions): Promise<string>;
  item: FileBrowserGridItem;
  maker: Pick<MobileMakerTransport, 'fileBrowser'>;
  onOpenLightbox(url: string): void;
  workdir: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  // absPath 单文件模式(item.relPath 为绝对路径):thumbnail op 只认 workdir
  // 内 relPath,禁用缩略图,直接等原图(media:fetch 通道)。
  const thumbUri = useFileThumbnail(
    maker,
    workdir,
    item.relPath,
    item.mtimeMs,
    active && !isAbsolutePathShape(item.relPath),
  );
  const [fullUrl, setFullUrl] = useState<string | null>(null);
  const [failure, setFailure] = useState<string | null>(null);
  const [attempt, setAttempt] = useState(0);
  const requestedRef = useRef(false);
  const releaseSourceRef = useRef<(() => void) | undefined>(undefined);
  useEffect(() => () => releaseSourceRef.current?.(), []);

  useEffect(() => {
    if (!active || requestedRef.current || !workdir) return undefined;
    requestedRef.current = true;
    let cancelled = false;
    setFailure(null);
    void exportToUrl(item.relPath, item.mtimeMs, { stream: false })
      .then((url) => retainRemoteFilePreview(url, shareMimeForFileName(item.name), item.name))
      .then((source) => {
        if (cancelled) { source.release(); return; }
        releaseSourceRef.current?.();
        releaseSourceRef.current = source.release;
        setFullUrl(source.uri);
      })
      .catch((err) => {
        if (cancelled) return;
        requestedRef.current = false; // 允许「重试」按钮/重进再次发起
        setFailure(formatRemoteError(err));
      });
    return () => {
      cancelled = true;
    };
  }, [active, attempt, exportToUrl, item.mtimeMs, item.name, item.relPath, workdir]);

  const displayUri = fullUrl ?? thumbUri;
  return (
    <Pressable
      accessibilityLabel={t('files.preview.a11yViewImage', { name: item.name })}
      disabled={!displayUri}
      onPress={() => displayUri && onOpenLightbox(fullUrl ?? displayUri)}
      style={styles.imagePage}
      testID="filePreview.imagePage"
    >
      {displayUri ? (
        <Image contentFit="contain" recyclingKey={displayUri} source={{ uri: displayUri }} style={styles.imageFull} />
      ) : failure ? (
        <View style={styles.imageStateWrap} testID="filePreview.imageError">
          <GenericGlyph name={item.name} />
          <Text style={styles.hintText}>{t('files.preview.fetchOriginalFailed', { detail: failure })}</Text>
          <MainWindowActionButton
            action={{
              accessibilityLabel: t('files.preview.a11yRetryOriginal'),
              label: t('files.preview.retry'),
              onPress: () => setAttempt((n) => n + 1),
              testID: 'filePreview.imageRetry',
            }}
          />
        </View>
      ) : (
        <View style={styles.imageStateWrap} testID="filePreview.imageLoading">
          <ActivityIndicator color={colors.textTertiary} />
          <Text style={styles.hintText}>{t('files.preview.fetchingOriginal')}</Text>
        </View>
      )}
      {displayUri && !fullUrl ? (
        <Text style={styles.imageUpgradeHint}>
          {failure ? t('files.preview.originalFailedThumb') : t('files.preview.fetchingOriginalHint')}
        </Text>
      ) : null}
    </Pressable>
  );
}

function UnsupportedPage({
  item,
  onDownload,
  onRetry,
  reason,
}: {
  item: FileBrowserGridItem;
  onDownload(): void;
  onRetry?: () => void;
  reason: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  return (
    <View style={styles.centerFill} testID="filePreview.unsupported">
      <View style={styles.bigPage}>
        <GenericGlyph name={item.name} />
      </View>
      <Text style={styles.bigName}>{item.name}</Text>
      <Text style={styles.bigMeta}>{item.metaLabel}</Text>
      <Text style={styles.hintText}>{reason}</Text>
      {onRetry ? <MainWindowActionButton action={{ label: t('files.preview.retry'), onPress: onRetry }} /> : <Pressable
        accessibilityLabel={t('files.preview.a11yExportShareFile')}
        onPress={onDownload}
        style={({ pressed }) => [styles.ctaBtn, pressed && styles.pressed]}
        testID="filePreview.unsupportedDownload"
      >
        <ArrowDownToLine color={colors.ctaText} size={iconSize.md} strokeWidth={iconStroke.regular} />
        <Text style={styles.ctaLabel}>{t('files.preview.exportShare')}</Text>
      </Pressable>}
    </View>
  );
}

function GenericGlyph({ name }: { name: string }) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const Icon = /\.(db|sqlite3?|realm)$/i.test(name) ? Database : FileIcon;
  return (
    <View style={styles.genericGlyphCard}>
      <Icon color={colors.borderStrong} size={iconSize.hero} strokeWidth={iconStroke.regular} />
    </View>
  );
}

/* ------------------------------ 工具 ------------------------------ */

function previewSiblings(entries: FileBrowserRemoteOpEntry[], sort: FileBrowserSortMode, initialRelPath: string, anchorRelPath = initialRelPath): FileBrowserGridItem[] {
  const files = buildFileBrowserGridItems(entries, sort, Date.now())
    .filter(item => item.kind === 'file')
    .filter(item => item.thumb !== 'image' || item.relPath === initialRelPath);
  return files.some(item => item.relPath === anchorRelPath || item.relPath === initialRelPath) ? files : [fallbackItem(initialRelPath)];
}

function fallbackItem(relPath: string): FileBrowserGridItem {
  const name = basename(relPath);
  return buildFileBrowserGridItems(
    [{ name, relPath, type: 'file', size: 0, mtimeMs: 0 }],
    'name',
    Date.now(),
  )[0];
}

/**
 * absPath 单文件模式的合成 item:relPath 字段直接装被控端绝对路径(仅作
 * 页面键/展示/分派用,凡消费 relPath 的取件路径都已按 isAbsolutePathShape
 * 分流),size/mtime 未知置 0(顶栏不显示 size、文本缓存跳过)。
 */
function absPathItem(absPath: string): FileBrowserGridItem {
  return buildFileBrowserGridItems(
    [{ name: pathDisplayName(absPath), relPath: absPath, type: 'file', size: 0, mtimeMs: 0 }],
    'name',
    Date.now(),
  )[0];
}

function basename(relPath: string): string {
  return relPath.split('/').filter(Boolean).pop() ?? relPath;
}

function readRouteString(value: unknown): string | null {
  if (typeof value === 'string' && value.length > 0) return value;
  if (Array.isArray(value) && typeof value[0] === 'string' && value[0].length > 0) return value[0];
  return null;
}

const makeStyles = (colors: ThemeColors) => {
  return StyleSheet.create({
    safeArea: { flex: 1, backgroundColor: colors.surfaceElevated },
    pressed: { opacity: 0.72 },
    centerFill: {
      alignItems: 'center',
      flex: 1,
      gap: spacing.md,
      justifyContent: 'center',
      paddingHorizontal: spacing.xl,
    },
    truncBar: {
      alignItems: 'center',
      backgroundColor: colors.surfaceChip,
      flexDirection: 'row',
      gap: spacing.sm - 2,
      justifyContent: 'center',
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.sm - 1,
    },
    truncText: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
    textPage: { flex: 1 },
    codeList: { flex: 1 },
    codeContent: { paddingHorizontal: spacing.lg, paddingVertical: spacing.md },
    codeLine: { flexDirection: 'row', gap: spacing.sm + 2 },
    codeLineHit: { backgroundColor: colors.surfaceChip, borderRadius: radius.micro },
    codeLineNum: {
      color: colors.textTertiary,
      fontFamily: monoFont,
      fontSize: typeScale.caption,
      lineHeight: lineHeight.caption,
    },
    codeText: {
      color: colors.textPrimary,
      flex: 1,
      fontFamily: monoFont,
      fontSize: typeScale.caption,
      lineHeight: lineHeight.caption,
    },
    imagePage: {
      alignItems: 'center',
      backgroundColor: colors.surface,
      flex: 1,
      justifyContent: 'center',
    },
    imageFull: { height: '100%', width: '100%' },
    imageStateWrap: { alignItems: 'center', gap: spacing.md, paddingHorizontal: spacing.xl },
    avPage: { flex: 1, justifyContent: 'center', padding: spacing.lg },
    fetchProgress: { alignItems: 'center', gap: spacing.sm, width: 200 },
    fetchProgressTrack: {
      backgroundColor: colors.surfaceChip,
      borderRadius: radius.pill,
      height: 4,
      overflow: 'hidden',
      width: '100%',
    },
    fetchProgressFill: { backgroundColor: colors.textSecondary, borderRadius: radius.pill, height: '100%' },
    fetchProgressText: {
      color: colors.textTertiary,
      fontSize: typeScale.caption,
      fontVariant: ['tabular-nums'],
      lineHeight: lineHeight.caption,
    },
    // The player's WebView fills its wrapper (flex: 1); a width-only wrapper collapses it to 0 pt.
    avPlayer: { flex: 1, width: '100%' },
    imageUpgradeHint: {
      bottom: spacing.md,
      color: colors.textTertiary,
      fontSize: typeScale.footnote,
      lineHeight: lineHeight.caption,
      position: 'absolute',
      textAlign: 'center',
      width: '100%',
    },
    pdfView: { flex: 1 },
    bigPage: {
      alignItems: 'center',
      justifyContent: 'center',
      marginBottom: spacing.xs,
    },
    genericGlyphCard: {
      alignItems: 'center',
      backgroundColor: colors.surfaceElevated,
      borderColor: colors.border,
      borderRadius: radius.micro,
      borderWidth: StyleSheet.hairlineWidth,
      height: 156,
      justifyContent: 'center',
      width: 122,
    },
    bigName: { color: colors.textPrimary, fontSize: typeScale.subtitle, lineHeight: lineHeight.subtitle, fontWeight: fontWeight.semibold },
    bigMeta: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
    hintText: {
      color: colors.textTertiary,
      fontSize: typeScale.footnote,
      lineHeight: lineHeight.caption,
      textAlign: 'center',
    },
    ctaBtn: {
      alignItems: 'center',
      backgroundColor: colors.cta,
      borderRadius: radius.pill,
      flexDirection: 'row',
      gap: spacing.sm,
      justifyContent: 'center',
      marginTop: spacing.sm,
      minHeight: 44,
      paddingHorizontal: spacing.xl,
    },
    ctaLabel: { color: colors.ctaText, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.medium },
  });
};