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。

fix(mobile): 缓存文件预览复用目录信息并保持阅读位置

Dash5d3ff20b2267
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 24e384265f..3281e26cd0 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -58,7 +58,7 @@ import { formatByteSize, isHtmlFilePreviewCandidate } from '@/session/filePrevie
import { joinRemotePath } from '@/session/htmlLocalResources';
import { decodeGzipBase64Text, mergePathIntoComposerDraft, shareMimeForFileName } from '@/session/fileBrowserActions';
import { appendQuote, truncateQuoteText } from '@/session/chatQuoteStore';
-import { getCachedPreviewText, storeCachedPreviewText } from '@/session/fileBrowserCache';
+import { getCachedListingSync, storeCachedListing, getCachedPreviewText, storeCachedPreviewText } from '@/session/fileBrowserCache';
import { exportRemoteFileToUrl } from '@/session/fileBrowserExport';
import { FileTransferBusyNotice } from '@/session/FileTransferBusyNotice';
import type { RemoteMediaSshContext } from '@/session/fileBrowserGallery';
@@ -214,14 +214,16 @@ function RemoteFilePreviewContent() {
const [session, setSession] = useState<RemoteSession | null>(knownSession);
const workdir = session?.workingDir ?? '';
- // The requested file is already known. Mount it (and its cached body) before
- // listing neighbours; a slow directory read must not hold every reopen blank.
+ // 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>(() => (
- initialRelPath && workdir ? [fallbackItem(initialRelPath)]
- : singleAbsPath ? [absPathItem(singleAbsPath)] : null
+ initialSiblings ?? (singleAbsPath ? [absPathItem(singleAbsPath)] : null)
));
const [siblingListing, setSiblingListing] = useState<SiblingListing | null>(null);
- const [pageIndex, setPageIndex] = useState(0);
+ const [pageIndex, setPageIndex] = useState(() => Math.max(0, initialSiblings?.findIndex(item => item.relPath === initialRelPath) ?? 0));
// 屏级焦点(HTML 可执行 WebView 的挂载门之一,见 renderItem 的 visible)。
// 本屏被压栈(点「发送到会话」→ router.navigate 把会话页推到根 Stack 上)时
// 路由仍挂载、pageIndex 也不变,只有 focus 会翻。
@@ -334,17 +336,12 @@ function RemoteFilePreviewContent() {
})
.then((raw) => {
if (cancelled) return;
- setSiblingListing({ key: listingKey, entries: normalizeRemoteOpDirEntries(raw) });
+ const entries = normalizeRemoteOpDirEntries(raw);
+ storeCachedListing(maker.fileBrowser.cacheScope, workdir, dirRel, entries);
+ setSiblingListing({ key: listingKey, entries });
})
- .catch(() => {
- if (cancelled) return;
- setSiblingListing(null);
- setSiblings([fallbackItem(initialRelPath)]);
- setPageIndex(0);
- requestAnimationFrame(() => {
- if (!cancelled) pagerRef.current?.scrollToOffset({ animated: false, offset: 0 });
- });
- });
+ // A failed background refresh must keep the visible file and neighbours.
+ .catch(() => undefined);
return () => {
cancelled = true;
};
@@ -363,6 +360,7 @@ function RemoteFilePreviewContent() {
let cancelled = false;
const anchorRelPath = currentRelPathRef.current ?? initialRelPath;
const anchorTo = (index: number): void => {
+ if (index === pageIndexRef.current) return;
setPageIndex(index);
requestAnimationFrame(() => {
if (!cancelled) {
@@ -372,9 +370,7 @@ function RemoteFilePreviewContent() {
};
// 图片已统一走浏览页的 ImageLightbox,翻页器只装非图片文件;
// 仅当直接以图片路径进入(旧链路兜底)时保留该图片单页。
- const files = buildFileBrowserGridItems(siblingListing.entries, sortMode, Date.now())
- .filter((item) => item.kind === 'file')
- .filter((item) => item.thumb !== 'image' || item.relPath === initialRelPath);
+ 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) {
@@ -390,6 +386,8 @@ function RemoteFilePreviewContent() {
}, [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;
@@ -1678,6 +1676,13 @@ function ToolbarButton({
/* ------------------------------ 工具 ------------------------------ */
+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(
diff --git a/apps/mobile/src/__tests__/filePreviewCacheRendering.test.tsx b/apps/mobile/src/__tests__/filePreviewCacheRendering.test.tsx
new file mode 100644
index 0000000000..fac6c7b909
--- /dev/null
+++ b/apps/mobile/src/__tests__/filePreviewCacheRendering.test.tsx
@@ -0,0 +1,135 @@
+// @vitest-environment jsdom
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import Screen from '../../app/files/preview/[sessionId]';
+import { storeCachedListing } from '@/session/fileBrowserCache';
+
+// Integration: the real screen must start at the cached file's index and keep
+// its position when the background directory request settles (reported on iOS).
+const state = vi.hoisted(() => ({
+ scope: '',
+ listDir: vi.fn(),
+ scroll: vi.fn(),
+ pager: null as any,
+ params: { sessionId: 'task', deviceId: 'device', relPath: 'README.md' },
+}));
+vi.mock('react-native', async () => {
+ const { createElement, forwardRef, useImperativeHandle } = await import('react');
+ const View = ({ children }: { children?: ReactNode }) => createElement('div', null, children);
+ return {
+ View, Text: View, Pressable: View, ActivityIndicator: () => null, Alert: {},
+ StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
+ useWindowDimensions: () => ({ width: 390, height: 844 }),
+ FlatList: forwardRef((props: any, ref) => {
+ state.pager = props;
+ useImperativeHandle(ref, () => ({ scrollToOffset: state.scroll }), []);
+ return null;
+ }),
+ };
+});
+vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text }));
+vi.mock('react-native-safe-area-context', async () => ({
+ SafeAreaView: (await import('react-native')).View,
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
+}));
+vi.mock('expo-router', () => {
+ const router = {};
+ return { useLocalSearchParams: () => state.params, useRouter: () => router, useIsFocused: () => true, useFocusEffect: () => {} };
+});
+vi.mock('@/platform/chrome/SystemNavigationBack', () => ({ SystemNavigationBack: () => null, useSystemNavigationBack: () => false }));
+vi.mock('@/platform/AdaptiveWindowContext', () => ({ useAdaptiveWindow: () => ({ width: 390, insets: { left: 0, right: 0 } }) }));
+vi.mock('@/auth/AuthContext', () => { const auth = {}; return { useAuth: () => auth }; });
+vi.mock('@/device-link/DeviceLinkContext', () => { const link = { openLink: async () => {} }; return { useDeviceLink: () => link }; });
+vi.mock('@/device-link/unresponsiveDevicesStore', () => { const devices = new Set(); return { useUnresponsiveDevices: () => devices }; });
+vi.mock('@/device-link/remoteRetry', () => ({ withTransientRemoteRetry: (read: () => unknown) => read() }));
+vi.mock('@/device-link/useMobileMakerTransport', () => {
+ const maker = { fileBrowser: { get cacheScope() { return state.scope; }, listDir: state.listDir } };
+ return { useMobileMakerTransport: () => maker };
+});
+vi.mock('@/session/remoteSessionStore', () => {
+ const sessions = [{ id: 'task', workingDir: '/repo' }];
+ return { useRemoteSessions: () => sessions, remoteSessionStore: {} };
+});
+vi.mock('@/session/CindyMakeSessionGate', () => ({ CindyMakeSessionGate: ({ children }: { children: ReactNode }) => children }));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ return { ...tokens, monoFont: 'monospace', useTheme: () => ({ colors: tokens.darkColors }), useThemedStyles: (make: any) => make(tokens.darkColors) };
+});
+vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: async () => null, setItem: async () => {}, multiRemove: async () => {} } }));
+vi.mock('lucide-react-native', () => Object.fromEntries(['ArrowDownToLine', 'Copy', 'Database', 'File', 'Info', 'MessageSquarePlus', 'Share'].map(key => [key, () => null])));
+vi.mock('expo-clipboard', () => ({}));
+vi.mock('expo-image', () => ({ Image: () => null }));
+vi.mock('react-native-webview', () => ({ WebView: () => null }));
+vi.mock('@/debug/mobileDebugLog', () => ({ mobileDebugLog: () => {} }));
+vi.mock('@/session/remoteAbsFileFetch', () => ({}));
+vi.mock('@/session/pdfPreviewSource', () => ({}));
+vi.mock('@/session/fileBrowserExport', () => ({}));
+vi.mock('@/session/FileTransferBusyNotice', () => ({ FileTransferBusyNotice: () => null }));
+vi.mock('@/session/HtmlFileReader', () => ({}));
+vi.mock('@/session/HtmlPreviewLoading', () => ({}));
+vi.mock('@/session/HtmlBrowserChrome', () => ({}));
+vi.mock('@/session/HtmlWebsiteBrowser', () => ({}));
+vi.mock('@/session/mobileHtmlPreview', () => ({}));
+vi.mock('@/session/useHtmlSnapshot', () => ({}));
+vi.mock('@/components/MobilePrimitives', () => ({}));
+vi.mock('@/session/FileBrowserSegmentedControl', () => ({}));
+vi.mock('@/session/MarkdownFileReader', () => ({}));
+vi.mock('@/session/mediaPlayerWebView', () => ({}));
+vi.mock('@/session/NativeVideoPlayer', () => ({}));
+vi.mock('@/session/fileThumbnails', () => ({}));
+vi.mock('@/session/ImageLightbox', () => ({}));
+vi.mock('@/session/remoteMediaDiskCacheExpo', () => ({}));
+
+const entries = ['a.txt', 'b.txt', 'README.md', 's.txt', 't.txt', 'z.txt'].map(name => ({
+ name, relPath: name, type: 'file' as const, size: 12200, mtimeMs: 1,
+}));
+let root: Root;
+let host: HTMLDivElement;
+let resolveListing: (value: unknown) => void;
+let rejectListing: (error: Error) => void;
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ vi.stubGlobal('requestAnimationFrame', (callback: () => void) => { callback(); return 0; });
+ state.scope += 'next';
+ state.scroll.mockClear();
+ state.listDir.mockImplementation(() => new Promise((resolve, reject) => { resolveListing = resolve; rejectListing = reject; }));
+ host = document.createElement('div');
+ root = createRoot(host);
+});
+afterEach(() => { act(() => root.unmount()); vi.unstubAllGlobals(); });
+async function open(cached = true) {
+ if (cached) storeCachedListing(state.scope, '/repo', '', entries);
+ await act(async () => { root.render(<Screen />); });
+}
+describe('cached file preview presentation', () => {
+ it('shows the cached index, count and size on the first render and does not reposition on unchanged refresh', async () => {
+ await open();
+ expect(host.textContent).toContain('3 / 6 · 11.9 KB');
+ expect(state.pager.initialScrollIndex).toBe(2);
+ const selectedKey = state.pager.keyExtractor(state.pager.data[2]);
+ state.scroll.mockClear();
+ await act(async () => { resolveListing({ entries }); });
+ expect(host.textContent).toContain('3 / 6 · 11.9 KB');
+ expect(state.pager.keyExtractor(state.pager.data[2])).toBe(selectedKey);
+ expect(state.scroll).not.toHaveBeenCalled();
+ });
+ it('retains the selected neighbour and cached metadata when directory refresh fails', async () => {
+ await open();
+ act(() => state.pager.onMomentumScrollEnd({ nativeEvent: { contentOffset: { x: 390 * 3 } } }));
+ state.scroll.mockClear();
+ await act(async () => { rejectListing(new Error('offline')); });
+ expect(host.textContent).toContain('s.txt4 / 6 · 11.9 KB');
+ expect(state.scroll).not.toHaveBeenCalled();
+ });
+ it('still opens without a listing and seeds subsequent opens from the successful background read', async () => {
+ await open(false);
+ expect(host.textContent).toContain('1 / 1');
+ await act(async () => { resolveListing({ entries }); });
+ expect(host.textContent).toContain('3 / 6 · 11.9 KB');
+ act(() => root.unmount());
+ root = createRoot(host);
+ await open(false);
+ expect(host.textContent).toContain('3 / 6 · 11.9 KB');
+ });
+});