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(preview): 弱网下优先显示 HTML 缓存并展示下载进度

Dash221c559cebf0
diff --git a/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts b/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
index 569dde5e82..5fc433a134 100644
--- a/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
@@ -315,3 +315,50 @@ async function readResource(url: string, pathname: string) {
await bootstrap.body?.cancel();
return fetch(new URL(pathname, url), { headers: { cookie } });
}
+
+// Regression: weak-network stat used to block even a complete, readable cache.
+it('serves cached HTML and assets while stat is pending, retains them on failure, and fences account changes', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-offline-test-'));
+ let fail!: () => void;
+ const waiting = new Promise<never>((_resolve, reject) => { fail = () => reject(new Error('offline')); });
+ try {
+ await fs.writeFile(path.join(dir, 'index.html'), '<h1>Saved page</h1>');
+ await fs.writeFile(path.join(dir, 'style.css'), 'body { color: blue; }');
+ const stat = vi.fn(() => waiting);
+ const read = vi.fn();
+ registerHtmlPreviewIpc({ cached: async (_args, _root, rel) => path.join(dir, rel), stat, read });
+ const { url } = await mocks.handle.mock.calls[0][1]({}, args);
+ expect(stat).not.toHaveBeenCalled();
+ expect(await (await readResource(url, '/index.html')).text()).toContain('Saved page');
+ expect(await (await readResource(url, '/style.css')).text()).toBe('body { color: blue; }');
+ expect(stat).toHaveBeenCalledTimes(2);
+ expect(read).not.toHaveBeenCalled();
+ fail();
+ expect(await (await readResource(url, '/index.html')).text()).toContain('Saved page');
+ mocks.current = false;
+ expect((await fetch(url, { redirect: 'manual' })).status).toBe(410);
+ } finally { fail(); await fs.rm(dir, { recursive: true, force: true }); }
+});
+
+it('refreshes the durable copy for the next open without replacing the visible snapshot', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-refresh-test-'));
+ try {
+ const cached = path.join(dir, 'index.html');
+ await fs.writeFile(cached, '<p>previous</p>');
+ const next = '<p>updated</p>';
+ let refreshed!: () => void;
+ const update = new Promise<void>((resolve) => { refreshed = resolve; });
+ registerHtmlPreviewIpc({
+ cached: async () => cached,
+ stat: async () => ({ relPath: 'index.html', type: 'file', size: Buffer.byteLength(next), mtimeMs: 1 }),
+ read: async () => { await fs.writeFile(cached, next); refreshed(); return cached; },
+ });
+ const open = mocks.handle.mock.calls[0][1];
+ const first = await open({}, args);
+ expect(await (await readResource(first.url, '/index.html')).text()).toContain('previous');
+ await update;
+ expect(await (await readResource(first.url, '/index.html')).text()).toContain('previous');
+ const second = await open({}, args);
+ expect(await (await readResource(second.url, '/index.html')).text()).toContain('updated');
+ } finally { await fs.rm(dir, { recursive: true, force: true }); }
+});
diff --git a/apps/desktop/src/main/file-browser/html-preview-ipc.ts b/apps/desktop/src/main/file-browser/html-preview-ipc.ts
index bf59810bd6..984ae69099 100644
--- a/apps/desktop/src/main/file-browser/html-preview-ipc.ts
+++ b/apps/desktop/src/main/file-browser/html-preview-ipc.ts
@@ -25,6 +25,7 @@ import { previewTransportErrorCode, readPreviewMetadata } from './html-preview-r
const log = createLogger('html-preview');
export const HTML_PREVIEW_CHANNEL = 'maker:html-preview:open';
interface RemoteSource {
+ cached?(args: HtmlPreviewArgs, root: string, rel: string): Promise<string | null>;
stat(
args: HtmlPreviewArgs,
root: string,
@@ -89,6 +90,11 @@ export function registerHtmlPreviewIpc(remote: RemoteSource): void {
isCurrent,
// Log status only: paths, signed URLs and page contents are not diagnostics.
onResourceError: (status) => log.warn('Preview resource request failed', { status }),
+ cached: args.origin.kind === 'local' ? undefined : async (root, rel) => {
+ if (!isCurrent()) return null;
+ const cached = await remote.cached?.(args, root, rel);
+ return isCurrent() ? cached ?? null : null;
+ },
stat: async (root, rel, signal) => {
if (args.origin.kind !== 'local')
return readPreviewMetadata(
diff --git a/apps/desktop/src/main/file-browser/html-preview.ts b/apps/desktop/src/main/file-browser/html-preview.ts
index 22ebd66524..c3b0bce565 100644
--- a/apps/desktop/src/main/file-browser/html-preview.ts
+++ b/apps/desktop/src/main/file-browser/html-preview.ts
@@ -24,6 +24,8 @@ export interface PreviewSource {
signal?: AbortSignal;
isCurrent?(): boolean;
onResourceError?(status: number): void;
+ /** Local, account-scoped lookup; must never wait for remote metadata. */
+ cached?(root: string, rel: string): Promise<string | null>;
stat(root: string, rel: string, signal?: AbortSignal): Promise<Omit<DirEntry, 'name'>>;
read(root: string, entry: DirEntry, signal?: AbortSignal): Promise<string>;
/** Media goes through the existing managed store; other files are copied into staging. */
@@ -152,28 +154,40 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSo
};
try {
if (!current()) throw new Error('PREVIEW_CANCELLED');
- const initial = await source.stat(root, entry, source.signal ?? controller.signal);
+ const cachedEntry = await source.cached?.(root, entry).catch(() => null);
if (!current()) throw new Error('PREVIEW_CANCELLED');
- if (initial.type !== 'file') throw new Error('NOT_FOUND');
- const materialize = async (relPath: string, directory: string, signal: AbortSignal) => {
+ if (!cachedEntry) {
+ const initial = await source.stat(root, entry, source.signal ?? controller.signal);
+ if (!current()) throw new Error('PREVIEW_CANCELLED');
+ if (initial.type !== 'file') throw new Error('NOT_FOUND');
+ }
+ const refresh = async (relPath: string, signal: AbortSignal) => {
if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');
const metadata = await source.stat(root, relPath, signal);
+ if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');
if (metadata.type !== 'file' || metadata.relPath !== relPath || !Number.isSafeInteger(metadata.size) || metadata.size < 0)
throw new Error('NOT_FOUND');
- const file = { ...metadata, name: relPath.split('/').pop()! };
- const sourcePath = await source.read(root, file, signal);
+ const sourcePath = await source.read(root, { ...metadata, name: relPath.split('/').pop()! }, signal);
+ return { path: sourcePath, size: metadata.size };
+ };
+ const materialize = async (relPath: string, directory: string, signal: AbortSignal) => {
+ if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');
+ const cached = await source.cached?.(root, relPath).catch(() => null);
+ const cachedStat = cached ? await fs.stat(cached).catch(() => null) : null;
+ const hit = cached && cachedStat?.isFile() ? { path: cached, size: cachedStat.size } : null;
+ const file = hit ?? await refresh(relPath, signal);
if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');
- const stat = await fs.stat(sourcePath);
+ const stat = await fs.stat(file.path);
if (!stat.isFile() || stat.size !== file.size) throw new Error('PREVIEW_CHANGED');
const dest = path.join(directory, 'asset');
- const materialized = await source.materialize(sourcePath, dest, file.size);
+ const materialized = await source.materialize(file.path, dest, file.size);
if ((await fs.stat(materialized)).size !== file.size) throw new Error('PREVIEW_CHANGED');
// Guard HTML documents, including secondary pages, before publishing the snapshot.
// Copy guarded HTML into this snapshot even if materialize returned a shared cache path.
// XML documents retain their parser/MIME and use the response CSP, not an HTML prolog.
let assetPath = materialized;
let assetSize = stat.size;
- if (/\.html?$/i.test(file.relPath)) {
+ if (/\.html?$/i.test(relPath)) {
const original = await fs.readFile(materialized);
let html: string | undefined;
try {
@@ -195,6 +209,13 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSo
}
}
if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');
+ if (hit) {
+ // Refresh the durable cache after owning a copy. Never replace the open page
+ // or make a disconnected host invalidate an otherwise readable snapshot.
+ const update = refresh(relPath, controller.signal).then(() => {}, () => {});
+ pending.add(update);
+ void update.finally(() => pending.delete(update));
+ }
return { path: assetPath, size: assetSize };
};
const token = randomBytes(24).toString('hex');
@@ -290,7 +311,7 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSo
});
server.unref();
origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
- if (source.isCurrent && !source.isCurrent()) throw new Error('PREVIEW_CANCELLED');
+ if (!current()) throw new Error('PREVIEW_CANCELLED');
return { url: `${origin}/${token}/`, close };
} catch (error) {
await close();
diff --git a/apps/desktop/src/main/file-browser/index.ts b/apps/desktop/src/main/file-browser/index.ts
index 154d2ffb90..f5ac6112ce 100644
--- a/apps/desktop/src/main/file-browser/index.ts
+++ b/apps/desktop/src/main/file-browser/index.ts
@@ -401,6 +401,15 @@ export function registerFileBrowserIpc(): void {
// 日志设施由宿主注入——desktop 侧接统一 logger(规则 12),scope 与抽包前一致。
setFileBrowserCoreLoggerFactory(createLogger);
registerHtmlPreviewIpc({
+ cached: (args, root, relPath) => {
+ if (args.origin.kind === 'local') return Promise.resolve(null);
+ return findStaleCached({
+ transport: args.origin.kind,
+ endpointId: args.origin.kind === 'device' ? args.origin.deviceId : args.origin.remoteHostId,
+ workdir: root,
+ relPath,
+ });
+ },
stat: async (args, root, relPath, signal) => {
signal?.throwIfAborted();
if (args.origin.kind === 'device') {
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index df00c4b29d..49cdc13165 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -63,6 +63,7 @@ import { exportRemoteFileToUrl } from '@/session/fileBrowserExport';
import { FileTransferBusyNotice } from '@/session/FileTransferBusyNotice';
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';
@@ -314,6 +315,14 @@ function RemoteFilePreviewContent() {
setPageIndex(0);
}, [singleAbsPath]);
+ // A known HTML path can read its cached entry immediately; sibling enumeration
+ // only enriches the pager and must not gate opening the document.
+ useEffect(() => {
+ if (!deviceId || !workdir || richTextKindOf(initialRelPath) !== 'html') return;
+ setSiblings([fallbackItem(initialRelPath)]);
+ setPageIndex(0);
+ }, [deviceId, initialRelPath, workdir]);
+
// 同目录 pager 远端数据:只在目录来源或恢复代数变化时重列。语言 / 排序变化
// 只消费下面缓存的原始目录项重建展示模型,不能为翻译重新请求设备。
useEffect(() => {
@@ -487,10 +496,10 @@ function RemoteFilePreviewContent() {
}, [session?.remoteHostId, sessionId, workdir]);
const prepareHtmlPreview = useCallback<PrepareMobileHtmlPreview>(
- (absPath, signal) => prepareMobileHtmlPreview(absPath, {
+ (absPath, signal, onProgress) => prepareMobileHtmlPreview(absPath, {
maker, deviceId, openLink, presignGet, ssh: sshMediaContext,
deleteOssObject: deleteResourceOssObject,
- }, signal),
+ }, signal, onProgress),
[deleteResourceOssObject, deviceId, maker, openLink, presignGet, sshMediaContext],
);
@@ -1224,14 +1233,17 @@ function TextPreviewPage({
const [textReloadEpoch, setTextReloadEpoch] = useState(0);
const codeListRef = useRef<FlatList<string>>(null);
const scrolledToTargetRef = useRef(false);
+ const wantsText = richKind !== 'html' || richView === 'source';
useEffect(() => {
- if (!active || loadedRef.current || !workdir) return;
+ if (!active || !wantsText || loadedRef.current || !workdir) return;
loadedRef.current = true;
let cancelled = false;
+ let settled = false;
void readTextFile(item.relPath)
.then((res: FileBrowserReadFileResult) => {
if (cancelled) return;
+ settled = true;
if (!res.ok) {
if (res.code === 'OVERSIZE') {
setState({
@@ -1269,8 +1281,9 @@ function TextPreviewPage({
});
return () => {
cancelled = true;
+ if (!settled) loadedRef.current = false;
};
- }, [active, cacheable, cacheScope, item.relPath, richKind, readTextFile, t, workdir, textReloadEpoch]);
+ }, [active, wantsText, cacheable, cacheScope, item.relPath, richKind, readTextFile, t, workdir, textReloadEpoch]);
const htmlSnapshot = useHtmlSnapshot(
absolutePathOf(item.relPath),
@@ -1381,13 +1394,11 @@ function TextPreviewPage({
</View>
) : !htmlSnapshot.preview || !htmlSnapshot.foreground ? (
// 取件期间不先渲染破图再热替换 —— 那会让 WebView 重载、页面闪一下。
- <View style={styles.centerFill} testID="filePreview.htmlResourceLoading">
- <ActivityIndicator color={colors.textTertiary} />
- <Text style={styles.hintText}>{t('files.preview.fetchingHtmlResources')}</Text>
- </View>
+ <HtmlPreviewLoading progress={htmlSnapshot.progress} />
) : (
// 只有完整下载并加固过的目录快照才能进入 WebView。
<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) => setBrowserNavigation({ preview, state })}
diff --git a/apps/mobile/docs/remote-control-plan.md b/apps/mobile/docs/remote-control-plan.md
index f62e9c2fc6..96a8ca3ecb 100644
--- a/apps/mobile/docs/remote-control-plan.md
+++ b/apps/mobile/docs/remote-control-plan.md
@@ -1564,9 +1564,23 @@ V2 完成标准:
## HTML 文件预览
消息里的 `xdt-file` 链接与文件浏览共用 `/files/preview/[sessionId]`。HTML 渲染态通过
-`mobileHtmlPreview.ts` 按网页实际请求读取资源,再由 `modules/cindy-html-preview`
+`mobileHtmlPreview.ts` 先取回 HTML 主文件,其余资源按网页实际请求读取,再由 `modules/cindy-html-preview`
在手机的 `127.0.0.1` 随机端口提供只读 HTTP,交给应用内 WebView。源码查看保持原有文本
-读取和大小限制,不影响完整网页的渲染。
+读取和大小限制,只在切到源码时启动,不与渲染态重复传输同一份 HTML。
+
+- 主文件完整取回并加固后才打开 WebView,避免远程传输占用浏览器的首文档请求等待。
+ 等待沿用文件通道已有的进展超时与临时故障重试,不用浏览器的文档超时判断远程下载失败。
+ 下载及首次渲染期间显示加载提示;每个资源的接收字节通过本机回调显示文件名、百分比与
+ 采样速度,未知总量不显示百分比,上传准备阶段不编造进度。切换传输路径时重新计数,
+ 关闭、后台或切文件后忽略旧进度;只取消该预览,不重置共享连接或其他设备。
+ 这些调整只涉及 JS,兼容两套既有原生接口,不改变 runtime fingerprint。
+
+- 手机与桌面的远程 HTML 预览都先读磁盘缓存;命中时不等待联网、远端 stat 或目录检查。
+ 手机复用账号文件缓存及磁盘压力回收,内联、直连与 OSS 取回的原始文件均可缓存;
+ 身份包含账号/区域、设备、SSH 来源和目录。桌面复用 `remote-file-cache`,本机文件仍直接读取。
+ 当前页面使用独立副本并重新添加 CSP,后台更新只写缓存,失败保留可读页面,下一次打开使用新副本。
+ 旧手机原生接口先发布已有缓存及目录清单;目录清单或部分资源被回收时仍可打开缓存主文件,
+ 未缓存资源需后台目录快照刷新后再打开;新接口可按请求补取缺失资源。切换账号关闭当前预览。
- 新原生接口 `startOnDemand` / `resolveRequest` 通过事件请求单个资源;打开时不枚举目录,
不检查目录文件数和总大小。资源复用既有内联、WebRTC 直连/TURN、OSS 回退及 SSH 读取链路。
diff --git a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
index b376fb9336..e49502d344 100644
--- a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
+++ b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
@@ -6,6 +6,9 @@ import { afterEach, expect, it, vi } from 'vitest';
import { PeerFileTransport } from '@/device-link/peerFileTransport';
import { HtmlSnapshotReader } from '@/session/HtmlFileReader';
import type { MobileHtmlPreview } from '@/session/mobileHtmlPreview';
+import type { HtmlPreviewProgress, PrepareMobileHtmlPreview } from '@/session/mobileHtmlPreview';
+import { useHtmlSnapshot } from '@/session/useHtmlSnapshot';
+import { HtmlPreviewLoading } from '@/session/HtmlPreviewLoading';
const state = vi.hoisted(() => ({
props: {} as Record<string, (...args: any[]) => void>,
@@ -22,10 +25,16 @@ const state = vi.hoisted(() => ({
vi.mock('react-native', () => ({
Platform: { OS: 'ios' },
View: ({ children }: { children: unknown }) => children,
+ ActivityIndicator: () => null,
StyleSheet: { create: (value: unknown) => value },
AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
}));
vi.mock('@/theme', () => ({ useTheme: () => ({ colors: { surfaceElevated: '#FFFFFC' } }) }));
+vi.mock('@/components/AppText', () => ({ Text: ({ children }: { children: unknown }) => children }));
+vi.mock('react-i18next', async (original) => ({
+ ...await original<typeof import('react-i18next')>(),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
vi.mock('@/session/useHtmlBrowserViewport', () => ({ useHtmlBrowserViewport: (insets: unknown) => ({ viewRef: { current: null }, measure() {}, script: '/* geometry only */ true;', obscuredContentInsets: insets }) }));
vi.mock('react-native-webview', async () => {
const { forwardRef, useEffect, useImperativeHandle } = await import('react');
@@ -169,15 +178,60 @@ it('starts a new native history for a refreshed snapshot and ignores navigation
const hidden = () => [(state.props as Record<string, unknown>).style].flat(Infinity).some((style: any) => style?.opacity === 0);
it('hides each snapshot until its first document loads, then reveals it', () => {
- root = createRoot(document.createElement('div'));
+ const container = document.createElement('div');
+ root = createRoot(container);
const first: MobileHtmlPreview = { url: 'http://127.0.0.1:1234/a/', documents: ['/index.html'], close: async () => {} };
- act(() => root!.render(createElement(HtmlSnapshotReader, { preview: first, onError() {} })));
+ act(() => root!.render(createElement(HtmlSnapshotReader, { preview: first, onError() {}, loading: 'loading-page' })));
expect(hidden()).toBe(true);
+ expect(container.textContent).toBe('loading-page');
act(() => state.props.onLoadEnd());
expect(hidden()).toBe(false);
+ expect(container.textContent).toBe('');
const next: MobileHtmlPreview = { url: 'http://127.0.0.1:1234/b/', documents: ['/index.html'], close: async () => {} };
act(() => root!.render(createElement(HtmlSnapshotReader, { preview: next, onError() {} })));
expect(hidden()).toBe(true);
act(() => state.props.onLoadEnd());
expect(hidden()).toBe(false);
});
+
+// Unit: real hook + loading component, covering the formerly invisible transfer
+// and late progress/error callbacks after switching files. No native network needed.
+it('shows known bytes and speed, hides unknown percentages, and ignores retired progress', async () => {
+ const container = document.createElement('div');
+ root = createRoot(container);
+ const observers: Array<(progress: HtmlPreviewProgress) => void> = [];
+ const prepare: PrepareMobileHtmlPreview = async (_path, _signal, onProgress) => {
+ observers.push(onProgress!);
+ return { url: 'http://127.0.0.1:1234/preview', documents: [], close: async () => {} };
+ };
+ function Harness({ path, enabled = true }: { path: string; enabled?: boolean }) {
+ const snapshot = useHtmlSnapshot(path, enabled, prepare);
+ return createElement(HtmlPreviewLoading, { progress: snapshot.progress });
+ }
+ await act(async () => root!.render(createElement(Harness, { path: '/a.html' })));
+ act(() => observers[0]({ name: 'a.html', loaded: 512, total: 1024, bytesPerSecond: 1024 }));
+ expect(container.textContent).toContain('a.html50% · 1.0 KB/s');
+ act(() => observers[0]({ name: 'a.html', loaded: 0, total: 0, bytesPerSecond: null }));
+ expect(container.textContent).not.toMatch(/%|\/s/);
+ await act(async () => root!.render(createElement(Harness, { path: '/b.html' })));
+ act(() => observers[0]({ name: 'a.html', loaded: 1024, total: 1024, bytesPerSecond: 1024 }));
+ expect(container.textContent).not.toContain('a.html');
+ act(() => observers[1]({ name: 'b.html', loaded: 1, total: 4, bytesPerSecond: null }));
+ expect(container.textContent).toContain('b.html25%');
+ await act(async () => root!.render(createElement(Harness, { path: '/b.html', enabled: false })));
+ act(() => observers[1]({ name: 'b.html', loaded: 4, total: 4, bytesPerSecond: 1 }));
+ expect(container.textContent).not.toContain('b.html');
+});
+
+it('ignores late failure events from a replaced preview', () => {
+ root = createRoot(document.createElement('div'));
+ const onError = vi.fn();
+ const preview: MobileHtmlPreview = { url: 'http://127.0.0.1:1234/first', documents: [], close: async () => {} };
+ act(() => root!.render(createElement(HtmlSnapshotReader, { preview, onError })));
+ const old = state.props;
+ act(() => root!.render(createElement(HtmlSnapshotReader, { preview: { ...preview, url: 'http://127.0.0.1:4321/next' }, onError })));
+ act(() => old.onError({ nativeEvent: { code: -1001 } }));
+ expect(onError).not.toHaveBeenCalled();
+ act(() => state.props.onError({ nativeEvent: { code: -1001 } }));
+ expect(onError).toHaveBeenCalledOnce();
+});
diff --git a/apps/mobile/src/__tests__/htmlPreviewCsp.test.ts b/apps/mobile/src/__tests__/htmlPreviewCsp.test.ts
index 29370a5ac5..6b5927c4e1 100644
--- a/apps/mobile/src/__tests__/htmlPreviewCsp.test.ts
+++ b/apps/mobile/src/__tests__/htmlPreviewCsp.test.ts
@@ -281,7 +281,8 @@ describe('资源取件的安全接线(源码级守卫)', () => {
it('checks exact manifest size before and after download and bounds upload on the controlled device', () => {
expect(snapshotSource).toContain('if (media.size !== file.size)');
- expect(snapshotSource.indexOf('if (media.size !== file.size)')).toBeLessThan(snapshotSource.indexOf('createDownloadResumable(media.url'));
+ const legacySnapshot = snapshotSource.slice(snapshotSource.indexOf('export async function prepareMobileHtmlPreview'), snapshotSource.indexOf('async function prepareOnDemand'));
+ expect(legacySnapshot.indexOf('if (media.size !== file.size)')).toBeLessThan(legacySnapshot.indexOf('createDownloadResumable(media.url'));
expect(snapshotSource).toContain('destination.size !== file.size');
expect(snapshotSource).toContain('baseDir: root, maxBytes: Math.max(1, file.size)');
const gallery = readFileSync(resolve(process.cwd(), 'src/session/fileBrowserGallery.ts'), 'utf8');
diff --git a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts b/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts
index 73a9bd7e43..661a1dbf65 100644
--- a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts
+++ b/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
contents: new Map<string, Uint8Array>(),
@@ -9,14 +9,17 @@ const mocks = vi.hoisted(() => ({
stop: vi.fn(),
download: vi.fn(),
pause: vi.fn(),
+ cache: vi.fn(),
+ sequence: 0,
demand: false,
startOnDemand: vi.fn(),
resolveRequest: vi.fn(),
listeners: new Map<string, (event: { token: string; id: string; path?: string }) => void>(),
}));
vi.mock("expo-crypto", () => ({
- getRandomBytes: () => new Uint8Array(24).fill(1),
+ getRandomBytes: () => new Uint8Array(24).fill(++mocks.sequence),
}));
+vi.mock("@/session/mobileHtmlPreviewCache", () => ({ createMobileHtmlPreviewCache: mocks.cache }));
vi.mock("../../modules/cindy-html-preview/src/CindyHtmlPreviewModule", () => ({
default: {
start: mocks.start, stop: mocks.stop,
@@ -80,14 +83,16 @@ vi.mock("expo-file-system", () => {
return { Directory, File, Paths: { cache: "file:///cache", availableDiskSpace: 8 * 1024 * 1024 * 1024 } };
});
vi.mock("expo-file-system/legacy", () => ({
- createDownloadResumable: (url: string, destination: string) => ({
- downloadAsync: () => mocks.download(url, destination),
+ createDownloadResumable: (url: string, destination: string, _options: unknown, progress: unknown) => ({
+ downloadAsync: () => mocks.download(url, destination, progress),
pauseAsync: mocks.pause,
}),
}));
import { prepareMobileHtmlPreview } from "@/session/mobileHtmlPreview";
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+afterEach(() => { vi.useRealTimers(); });
const html = "<h1>中文</h1>";
const bytes = new TextEncoder().encode(html);
@@ -123,6 +128,7 @@ async function stagedDirectTransfer(_deps: unknown, path: string) {
}
beforeEach(() => {
vi.resetAllMocks();
+ mocks.sequence = 0;
mocks.demand = false;
mocks.listeners.clear();
mocks.startOnDemand.mockResolvedValue("http://127.0.0.1:43123/__cindy/token");
@@ -143,6 +149,86 @@ beforeEach(() => {
});
});
+function previewCache() {
+ const saved = new Map<string, Uint8Array>();
+ let manifest: ReturnType<typeof entry>[] | null = null;
+ const cache = {
+ current: () => true,
+ copy: vi.fn(async (relative: string, destination: { uri: string }) => {
+ const bytes = saved.get(relative);
+ if (!bytes) return null;
+ mocks.contents.set(destination.uri, bytes.slice());
+ return bytes.length;
+ }),
+ store: vi.fn(async (relative: string, source: { uri: string }) => {
+ saved.set(relative, mocks.contents.get(source.uri)!.slice());
+ }),
+ manifest: vi.fn(async () => manifest),
+ storeManifest: vi.fn(async (_entry: string, files: ReturnType<typeof entry>[]) => { manifest = files; }),
+ };
+ mocks.cache.mockReturnValue(cache);
+ return { cache, saved };
+}
+
+describe('persistent HTML preview cache', () => {
+ // Behavioral timing contract: a cache hit must resolve before an unresolved remote operation.
+ it.each([false, true])('opens cached content before network checks, including old native mode (onDemand=%s)', async (demand) => {
+ mocks.demand = demand;
+ const { deps, caps } = setup();
+ const { cache } = previewCache();
+ const first = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);
+ await first.close();
+ mocks.start.mockClear(); mocks.startOnDemand.mockClear();
+ let fail!: () => void;
+ const waiting = new Promise<never>((_resolve, reject) => { fail = () => reject(new Error('offline')); });
+ if (demand) mocks.remote.mockImplementation(() => waiting);
+ else caps.mockImplementation(() => waiting);
+ const second = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);
+ expect(demand ? mocks.startOnDemand : mocks.start).toHaveBeenCalledOnce();
+ expect(cache.copy).toHaveBeenCalled();
+ expect([...mocks.contents.values()].some((value) => new TextDecoder().decode(value).includes('<h1>中文</h1>'))).toBe(true);
+ fail();
+ await second.close();
+ });
+
+ it('keeps the open page stable and uses a background update on the next open', async () => {
+ mocks.demand = true;
+ const { deps } = setup();
+ const { cache, saved } = previewCache();
+ saved.set('index.html', bytes);
+ const updated = new TextEncoder().encode('<p>Updated page</p>');
+ mocks.remote.mockResolvedValue({ url: '', inlineBase64: btoa('<p>Updated page</p>'), size: updated.length });
+ const preview = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);
+ await vi.waitFor(() => expect(cache.store).toHaveBeenCalledOnce());
+ expect(saved.get('index.html')).toEqual(updated);
+ expect(new TextDecoder().decode(mocks.contents.get('file:///cache/html-previews/' + '01'.repeat(24) + '/0'))).toContain(html);
+ await preview.close();
+ mocks.remote.mockRejectedValue(new Error('offline'));
+ const reopened = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);
+ expect(new TextDecoder().decode(mocks.contents.get('file:///cache/html-previews/' + '02'.repeat(24) + '/0'))).toContain('Updated page');
+ await reopened.close();
+ });
+
+ it.each([false, true])('closes cached previews on account switch without waiting for a refresh (onDemand=%s)', async (demand) => {
+ mocks.demand = demand;
+ const { deps, caps } = setup();
+ const { cache, saved } = previewCache();
+ // No directory manifest: a missing companion cache must not hide the cached entry.
+ saved.set('index.html', bytes);
+ mocks.remote.mockRejectedValue(new Error('offline'));
+ caps.mockRejectedValue(new Error('offline'));
+ const preview = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);
+ expect(demand ? mocks.startOnDemand : mocks.start).toHaveBeenCalledOnce();
+ vi.spyOn(cache, 'current').mockReturnValue(false);
+ setMobileAuthOwner('switched-owner-' + demand);
+ await vi.waitFor(() => expect(mocks.stop).toHaveBeenCalledOnce());
+ await preview.close();
+ expect(mocks.contents.size).toBe(0);
+ expect(mocks.listeners.size).toBe(0);
+ setMobileAuthOwner(null);
+ });
+});
+
describe("mobile HTML preview preparation", () => {
it("serves inline HTML and an empty CSS file without an HTTP download", async () => {
const { deps, listDir } = setup();
@@ -187,6 +273,7 @@ describe("mobile HTML preview preparation", () => {
expect.any(Function),
{ baseDir: "/site", maxBytes: bytes.length },
expect.any(AbortSignal),
+ expect.any(Function),
);
expect(mocks.start).toHaveBeenCalledTimes(1);
for (const content of mocks.contents.values()) {
@@ -314,17 +401,85 @@ describe("on-demand mobile HTML previews", () => {
const request = (id: string, path: string) => mocks.listeners.get("resourceRequest")!({ token, id, path });
beforeEach(() => { mocks.demand = true; });
- it("opens without listing or downloading, then fetches only requested resources", async () => {
+ // Unit regression: a slow entry must finish before WebView can request it. Previously
+ // preparation returned immediately, leaving WebKit's request waiting on the network.
+ it("keeps a slow entry in preparation, reports bytes, then serves it without another download", async () => {
+ vi.useFakeTimers();
+ const { deps } = setup();
+ let finish!: () => void;
+ const progress = vi.fn();
+ mocks.remote.mockImplementation(async (...args) => {
+ args[6]?.(4, bytes.length);
+ await new Promise<void>((resolve) => { finish = resolve; });
+ return { url: "data:text/html;base64,", size: bytes.length, inlineBase64: Buffer.from(bytes).toString("base64") };
+ });
+ const preparing = prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal, progress);
+ await Promise.resolve();
+ expect(mocks.remote).toHaveBeenCalledOnce();
+ expect(mocks.startOnDemand).not.toHaveBeenCalled();
+ expect(progress).toHaveBeenLastCalledWith(expect.objectContaining({ name: "index.html", loaded: 4, total: bytes.length }));
+ await vi.advanceTimersByTimeAsync(90_000);
+ expect(mocks.startOnDemand).not.toHaveBeenCalled();
+ finish();
+ const preview = await preparing;
+ request("entry", "index.html");
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "entry", "0", "text/html", 200));
+ expect(mocks.remote).toHaveBeenCalledOnce();
+ await preview.close();
+ });
+
+ it.each([false, true])('reports actual download speed on old and on-demand binaries: %s', async (demand) => {
+ vi.useFakeTimers();
+ mocks.demand = demand;
+ const { deps, listDir } = setup();
+ listDir.mockResolvedValue([entry('index.html')]);
+ const progress = vi.fn();
+ mocks.download.mockImplementation(async (_url, destination, report) => {
+ vi.setSystemTime(Date.now() + 1000);
+ report({ totalBytesWritten: 4, totalBytesExpectedToWrite: -1 });
+ expect(progress).toHaveBeenLastCalledWith(expect.objectContaining({ loaded: 4, total: bytes.length, bytesPerSecond: 4 }));
+ mocks.contents.set(destination, bytes);
+ return { status: 200 };
+ });
+ const preview = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal, progress);
+ expect(progress).toHaveBeenLastCalledWith(expect.objectContaining({ loaded: bytes.length, total: bytes.length }));
+ await preview.close();
+ });
+
+ it('cancels entry preparation before opening a server and releases a late direct file', async () => {
+ const { deps } = setup();
+ const controller = new AbortController();
+ const progress = vi.fn();
+ let finish!: () => void;
+ mocks.remote.mockImplementation(async () => {
+ await new Promise<void>((resolve) => { finish = resolve; });
+ return stagedDirectTransfer(null, '/site/index.html');
+ });
+ const preparing = prepareMobileHtmlPreview('/site/index.html', deps, controller.signal, progress);
+ const rejected = expect(preparing).rejects.toThrow('PREVIEW_CANCELLED');
+ await vi.waitFor(() => expect(mocks.remote).toHaveBeenCalledOnce());
+ controller.abort();
+ progress.mockClear();
+ finish();
+ await rejected;
+ expect(mocks.startOnDemand).not.toHaveBeenCalled();
+ expect(mocks.released).toEqual(['file:///peer/index.html']);
+ expect(mocks.contents.size).toBe(0);
+ expect(mocks.listeners.size).toBe(0);
+ expect(progress).not.toHaveBeenCalled();
+ });
+
+ it("prepares only the entry without listing, then fetches requested resources", async () => {
const { deps, listDir, caps } = setup();
const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);
expect(preview.onDemand).toBe(true);
expect(listDir).not.toHaveBeenCalled();
expect(caps).not.toHaveBeenCalled();
- expect(mocks.remote).not.toHaveBeenCalled();
+ expect(mocks.remote).toHaveBeenCalledOnce();
request("a", "index.html");
await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "a", "0", "text/html", 200));
expect(mocks.remote).toHaveBeenCalledWith(deps, "/site/index.html", undefined, expect.any(Function),
- { baseDir: "/site", maxBytes: 2 * 1024 * 1024 * 1024 }, expect.any(AbortSignal));
+ { baseDir: "/site", maxBytes: 2 * 1024 * 1024 * 1024 }, expect.any(AbortSignal), expect.any(Function));
expect(new TextDecoder().decode([...mocks.contents.values()][0])).toContain("Content-Security-Policy");
expect(deps.deleteOssObject).toHaveBeenCalledOnce();
await preview.close();
@@ -363,23 +518,26 @@ describe("on-demand mobile HTML previews", () => {
await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "missing", "", "", 404));
request("escape", "../secret.html");
await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "escape", "", "", 404));
- expect(mocks.remote).toHaveBeenCalledOnce();
+ expect(mocks.remote).toHaveBeenCalledTimes(2);
request("page", "second.html");
- await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "page", "1", "text/html", 200));
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "page", "2", "text/html", 200));
await preview.close();
});
it("cancels closed requests before publishing and drains cleanup before removing its directory", async () => {
const { deps } = setup();
+ const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);
+ mocks.download.mockClear();
+ mocks.remote.mockClear();
+ deps.deleteOssObject.mockClear();
let finish!: (value: { status: number }) => void;
mocks.download.mockImplementation((_url, destination) => {
mocks.contents.set(destination, bytes);
return new Promise((resolve) => { finish = resolve; });
});
- const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);
- request("active", "index.html");
+ request("active", "second.html");
await vi.waitFor(() => expect(mocks.download).toHaveBeenCalledOnce());
- request("queued", "second.html");
+ request("queued", "third.html");
const closing = preview.close();
expect(mocks.pause).toHaveBeenCalledOnce();
expect(mocks.removed).toHaveLength(0);
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index c46a3b8587..64c0608980 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -11,6 +11,7 @@ import {
import type { RemoteInvoke } from "@/device-link/mobileMakerTransport";
import { installPeerFileDownload } from "@/device-link/peerFileRegistry";
import { isDirectPreviewableMediaUrl, resolveMobileRemoteMedia } from "@/session/remoteMedia";
+import { fetchRemoteAbsFileOnce } from '@/session/remoteAbsFileFetch';
import {
setMobileAuthOwner,
__testing as authOwnerTesting,
@@ -212,15 +213,36 @@ describe("mobile maker transport", () => {
direct,
);
expect(peer).toHaveBeenCalledOnce();
- expect(peer.mock.calls[0]).toEqual(['d', 'xdt-file://open?path=/b', undefined, expect.any(Number), { ...direct, transferRequired: true, version: 'a'.repeat(64) }]);
+ expect(peer.mock.calls[0]).toEqual(['d', 'xdt-file://open?path=/b', undefined, expect.any(Number), { ...direct, transferRequired: true, version: 'a'.repeat(64) }, undefined]);
invoke.mockResolvedValueOnce({ ...direct, transferRequired: true, version: 'a'.repeat(64) });
await maker.fetchRemoteMedia('xdt-file://open?path=/b', { stream: false, skipCache: true });
expect(peer.mock.calls[1]).toEqual(['d', 'xdt-file://open?path=/b', undefined, expect.any(Number),
- { ...direct, transferRequired: true, version: 'a'.repeat(64), skipCache: true }]);
+ { ...direct, transferRequired: true, version: 'a'.repeat(64), skipCache: true }, undefined]);
} finally {
uninstall();
}
});
+ // Unit: exercise the complete HTML fetch adapter chain. A failed partial direct
+ // download must clear its percentage while the existing OSS fallback prepares.
+ it('forwards receiver progress through HTML fetching and resets it on upload fallback', async () => {
+ const progress = vi.fn();
+ const metadata = { ossKey: '', size: 100, mimeType: 'text/html' };
+ const uninstall = installPeerFileDownload(async (_device, _url, _signal, _trace, _metadata, onProgress) => {
+ onProgress?.(42, 100);
+ return null;
+ });
+ const invoke = vi.fn().mockResolvedValueOnce({ ...metadata, transferRequired: true })
+ .mockResolvedValueOnce({ ...metadata, ossKey: 'owned/page' });
+ try {
+ const maker = createMobileMakerTransport({ deviceId: 'd', invoke });
+ const result = await fetchRemoteAbsFileOnce({ maker, deviceId: 'd', openLink: async () => {},
+ presignGet: async () => ({ getUrl: 'https://example.test/page', expiresAt: '2099-01-01T00:00:00Z' }) },
+ '/page.html', undefined, undefined, undefined, new AbortController().signal, progress);
+ expect(result.url).toBe('https://example.test/page');
+ expect(progress.mock.calls).toEqual([[42, 100], [0, 0]]);
+ expect(invoke).toHaveBeenCalledTimes(2);
+ } finally { uninstall(); }
+ });
it("cancels before caps and keeps old-host export on the existing job protocol", async () => {
const invoke = vi
.fn()
diff --git a/apps/mobile/src/__tests__/peerFileCache.test.ts b/apps/mobile/src/__tests__/peerFileCache.test.ts
index a9d2356f73..dffac0d138 100644
--- a/apps/mobile/src/__tests__/peerFileCache.test.ts
+++ b/apps/mobile/src/__tests__/peerFileCache.test.ts
@@ -1,5 +1,6 @@
import { afterEach, expect, it, vi } from "vitest";
import { createHash } from "node:crypto";
+vi.mock("@/config/env", () => ({ getActiveMobileSessionRealm: () => 'global' }));
const disk = vi.hoisted(() => ({
files: new Map<string, Uint8Array>(),
indexes: new Map<string, string>(),
@@ -41,6 +42,8 @@ vi.mock("expo-file-system", () => ({
delete() {
disk.files.delete(this.uri);
}
+ async text() { return new TextDecoder().decode(disk.files.get(this.uri)); }
+ write(text: string) { disk.files.set(this.uri, new TextEncoder().encode(text)); }
async copy(target: { uri: string }) {
disk.copying = true;
if (disk.gate) await disk.gate;
@@ -81,6 +84,11 @@ vi.mock("@/session/remoteMediaDiskCacheExpo", () => ({
},
}));
import { createPeerFileCache } from "@/device-link/peerFileCache";
+import { createMobileHtmlPreviewCache } from '@/session/mobileHtmlPreviewCache';
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { File } from 'expo-file-system';
+import { FILE_PEER_MAX_BYTES } from '@cindy/device-link';
+import { remoteFileMediaUrl } from '@/session/fileBrowserGallery';
import {
clearPeerMedia,
peerMediaUri,
@@ -88,11 +96,60 @@ import {
releasePeerMedia,
} from "@/device-link/peerFileRegistry";
afterEach(() => {
+ setMobileAuthOwner(null);
clearPeerMedia();
disk.gate = undefined;
disk.copying = false;
disk.available = 10 * 1024 ** 3;
});
+
+// Cached previews have no fresh metadata: identity and owner fencing must hold locally.
+it('restores preview bytes offline, isolates account/device/SSH, and rejects a copy crossing an account switch', async () => {
+ setMobileAuthOwner('html-owner');
+ const cache = createMobileHtmlPreviewCache('desktop-a', '/site')!;
+ const input = new File('file:///input.html');
+ input.write('<p>Cached</p>');
+ // A transfer saved before cache-first previews existed must also open offline.
+ const transfer = await createPeerFileCache(JSON.stringify(['global', 'html-owner']));
+ const meta = { ...metadata, size: input.size };
+ const media = { ossKey: '', ...meta };
+ recordPeerMedia(media, input.uri, () => {});
+ await transfer.store('desktop-a', remoteFileMediaUrl('/site/index.html', undefined, undefined,
+ { baseDir: '/site', maxBytes: FILE_PEER_MAX_BYTES }), meta, media);
+ const copy = new File('file:///restored.html');
+ expect(await cache.copy('index.html', copy)).toBe(input.size);
+ expect(await copy.text()).toBe('<p>Cached</p>');
+ expect(await cache.copy('index.html', new File('file:///too-large.html'), 1)).toBeNull();
+ expect(disk.files.has('file:///too-large.html')).toBe(false);
+ await cache.store('index.html', input, 'text/html');
+ expect(await createMobileHtmlPreviewCache('desktop-b', '/site')!.copy('index.html', copy)).toBeNull();
+ const ssh = { sessionId: 's', remoteHostId: 'ssh', workdir: '/site' };
+ expect(await createMobileHtmlPreviewCache('desktop-a', '/site', ssh)!.copy('index.html', copy)).toBeNull();
+ setMobileAuthOwner('other-html-owner');
+ expect(await createMobileHtmlPreviewCache('desktop-a', '/site')!.copy('index.html', copy)).toBeNull();
+ setMobileAuthOwner('html-owner');
+ const restored = createMobileHtmlPreviewCache('desktop-a', '/site')!;
+ let release!: () => void;
+ disk.gate = new Promise<void>((resolve) => { release = resolve; });
+ const pending = restored.copy('index.html', copy);
+ await vi.waitFor(() => expect(disk.copying).toBe(true));
+ setMobileAuthOwner('other-html-owner');
+ release();
+ expect(await pending).toBeNull();
+ expect(copy.exists).toBe(false);
+});
+
+it('restores complete legacy manifests and rejects paths that the preview cannot publish', async () => {
+ setMobileAuthOwner('manifest-owner');
+ const cache = createMobileHtmlPreviewCache('desktop', '/site')!;
+ const temporary = new File('file:///manifest.json');
+ const file = { name: 'index.html', relPath: 'index.html', type: 'file' as const, size: 20 };
+ await cache.storeManifest('index.html', [file], temporary);
+ expect(await cache.manifest('index.html')).toEqual([file]);
+ expect(temporary.exists).toBe(false);
+ await cache.storeManifest('index.html', [file, { ...file, relPath: '../secret.html' }], temporary);
+ expect(await cache.manifest('index.html')).toBeNull();
+});
const metadata = { size: 5, mimeType: "text/html", version: "a".repeat(64) };
async function seed(owner: string) {
const cache = await createPeerFileCache(owner);
diff --git a/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx b/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx
index f8437ff66c..2fd5a51e80 100644
--- a/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx
+++ b/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx
@@ -386,7 +386,10 @@ it.each(["unknown", "timeout", "route-change", "debug-enabled"])("samples paths
: normal(...args));
const controller = new AbortController();
let settled = false;
- const transfer = state.download("device", "url", controller.signal).then((result: unknown) => {
+ // Production receiver callback must report written bytes with Debug off, and a UI
+ // observer failure must not turn an acknowledged write into a failed transfer.
+ const progress = vi.fn(() => { throw new Error('observer'); });
+ const transfer = state.download("device", "url", controller.signal, undefined, undefined, progress).then((result: unknown) => {
settled = true;
return result;
});
@@ -396,8 +399,12 @@ it.each(["unknown", "timeout", "route-change", "debug-enabled"])("samples paths
await vi.advanceTimersByTimeAsync(0);
const receive = state.commands.find((c) => c.action === "receive");
expect(receive).toBeDefined();
+ expect(progress).toHaveBeenLastCalledWith(0, 100_000);
+ act(() => message({ type: 'write', id: 'bad-offset', args: [receive.args[0], 2, 'YQ=='] }));
+ expect(progress).toHaveBeenCalledOnce();
for (let offset = 0; offset < 75; offset++) {
act(() => message({ type: "write", id: `write-${offset}`, args: [receive.args[0], offset, "YQ=="] }));
+ expect(progress).toHaveBeenLastCalledWith(offset + 1, 100_000);
await vi.advanceTimersByTimeAsync(1000);
// Neither an unknown/changing route nor a long total duration ends a live transfer.
expect(settled).toBe(false);
diff --git a/apps/mobile/src/__tests__/peerFileRegistry.test.ts b/apps/mobile/src/__tests__/peerFileRegistry.test.ts
index e3b6326952..a96e050604 100644
--- a/apps/mobile/src/__tests__/peerFileRegistry.test.ts
+++ b/apps/mobile/src/__tests__/peerFileRegistry.test.ts
@@ -73,10 +73,10 @@ describe("peer file staging ownership", () => {
const peer = vi.fn(async () => null);
const remove = installPeerFileDownload(peer);
await tryMobilePeerFile("device", "url", undefined, 42);
- expect(peer).toHaveBeenCalledWith("device", "url", undefined, 42, undefined);
+ expect(peer).toHaveBeenCalledWith("device", "url", undefined, 42, undefined, undefined);
const metadata = { version: 'a'.repeat(64), size: 12, mimeType: 'text/html' };
await tryMobilePeerFile('device', 'url', undefined, 43, metadata);
- expect(peer).toHaveBeenLastCalledWith('device', 'url', undefined, 43, metadata);
+ expect(peer).toHaveBeenLastCalledWith('device', 'url', undefined, 43, metadata, undefined);
remove();
});
});
diff --git a/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts b/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
index af18ea7865..779a050ec0 100644
--- a/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
+++ b/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
@@ -4,6 +4,7 @@ import { i18n } from '@/i18n';
import {
adaptTextFilePreviewResult,
fetchRemoteAbsFileToUrl,
+ fetchRemoteAbsFileOnce,
type RemoteAbsFileFetchDeps,
} from '@/session/remoteAbsFileFetch';
import type { RemoteTextFilePreviewResult } from '@/device-link/mobileMakerTransport';
@@ -38,6 +39,17 @@ function makeDeps(overrides: Partial<{
}
describe('fetchRemoteAbsFileToUrl', () => {
+ // Unit regression: cancelling HTML preparation while opening a link must not
+ // enqueue the file read once that link eventually opens.
+ it('does not start a preview file read after cancellation during link setup', async () => {
+ const { deps, openLink, fetchRemoteMedia } = makeDeps();
+ const controller = new AbortController();
+ openLink.mockImplementation(async () => { controller.abort(); });
+ await expect(fetchRemoteAbsFileOnce(deps, '/page.html', undefined, undefined, undefined, controller.signal))
+ .rejects.toThrow('PREVIEW_CANCELLED');
+ expect(fetchRemoteMedia).not.toHaveBeenCalled();
+ expect(openLink).toHaveBeenCalledOnce();
+ });
it('separates streaming and complete-file cache entries in either order', async () => {
for (const first of [true, false]) {
const { deps, fetchRemoteMedia } = makeDeps();
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 3e850e9c37..f0cbf71714 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -1128,12 +1128,14 @@ export function createMobileMakerTransport({
? stage(
"direct",
() => tryMobilePeerFile(deviceId, url, opts?.signal, trace || undefined,
- opts?.skipCache ? { ...metadata, skipCache: true } : metadata),
+ opts?.skipCache ? { ...metadata, skipCache: true } : metadata, opts?.onProgress),
(result) => ({ hit: result !== null }),
)
: Promise.resolve(null),
- fallback: () =>
- stage("upload", fallback ?? (() => fetch(false)), describeResult),
+ fallback: () => {
+ try { opts?.onProgress?.(0, 0); } catch { /* Observer only; upload bytes are unavailable. */ }
+ return stage("upload", fallback ?? (() => fetch(false)), describeResult);
+ },
}),
(result) => ({
route: peerMediaUri(result)
diff --git a/apps/mobile/src/device-link/peerFileCache.ts b/apps/mobile/src/device-link/peerFileCache.ts
index c1bf06d50e..1aa76da138 100644
--- a/apps/mobile/src/device-link/peerFileCache.ts
+++ b/apps/mobile/src/device-link/peerFileCache.ts
@@ -40,6 +40,13 @@ async function openPeerFileCache(owner: string) {
},
);
return {
+ // HTML previews deliberately allow a last-known copy before remote stat.
+ // Keep these keys separate from the strictly versioned transfer cache.
+ lookupPreview: async (identity: string, previousTransfer?: { device: string; url: string }) =>
+ await cache.lookup(`html-preview:${identity}`) ?? (previousTransfer
+ ? cache.lookup(JSON.stringify([previousTransfer.device, previousTransfer.url])) : null),
+ storePreview: (identity: string, uri: string, mime: string, size: number) =>
+ cache.store(`html-preview:${identity}`, uri, mime, size),
prune: (size: number) => cache.prune(2 * size),
invalidate: (device: string, url: string) =>
cache.remove(JSON.stringify([device, url])),
diff --git a/apps/mobile/src/device-link/peerFileRegistry.ts b/apps/mobile/src/device-link/peerFileRegistry.ts
index d33df1fe48..69dd35f419 100644
--- a/apps/mobile/src/device-link/peerFileRegistry.ts
+++ b/apps/mobile/src/device-link/peerFileRegistry.ts
@@ -86,6 +86,7 @@ type Download = (
signal?: AbortSignal,
trace?: number,
metadata?: FileVersionMetadata,
+ onProgress?: (loaded: number, total: number) => void,
) => Promise<LocalPeerMedia | null>;
let download: Download | null = null;
export function installPeerFileDownload(value: Download) {
@@ -100,8 +101,9 @@ export async function tryMobilePeerFile(
signal?: AbortSignal,
trace?: number,
metadata?: FileVersionMetadata,
+ onProgress?: (loaded: number, total: number) => void,
) {
- return download?.(device, url, signal, trace, metadata) ?? null;
+ return download?.(device, url, signal, trace, metadata, onProgress) ?? null;
}
/** Budget includes retained files; reserve room for the consumer copy and keep 256 MiB free. */
diff --git a/apps/mobile/src/device-link/peerFileTransport.tsx b/apps/mobile/src/device-link/peerFileTransport.tsx
index c2ab474a87..4deca6be13 100644
--- a/apps/mobile/src/device-link/peerFileTransport.tsx
+++ b/apps/mobile/src/device-link/peerFileTransport.tsx
@@ -108,7 +108,7 @@ export function PeerFileTransport() {
const sinks = useRef(
new Map<
string,
- { handle: ReturnType<File["open"]>; size: number; offset: number }
+ { handle: ReturnType<File["open"]>; size: number; offset: number; onProgress?: (loaded: number, total: number) => void }
>(),
);
const epoch = useRef(0);
@@ -266,6 +266,7 @@ export function PeerFileTransport() {
url: string | null,
signal?: AbortSignal,
readTrace?: number,
+ onProgress?: (loaded: number, total: number) => void,
): Promise<LocalMedia | null> => {
const current = captureDevice(device);
// Keep a device close from turning into an upload fallback or reopening its link.
@@ -437,7 +438,8 @@ export function PeerFileTransport() {
target = new File(directory, randomUUID());
target.create();
const handle = target.open();
- sinks.current.set(id, { handle, size: file.size, offset: 0 });
+ sinks.current.set(id, { handle, size: file.size, offset: 0, onProgress });
+ try { onProgress?.(0, file.size); } catch { /* UI observers cannot interrupt a transfer. */ }
// Detect stalled writes even with Debug recording off. Route sampling is
// diagnostic only; a slow route must not interrupt a progressing download.
let sampling = false;
@@ -576,7 +578,7 @@ export function PeerFileTransport() {
};
const queueRead = createFileReadQueue();
const unregister = installPeerFileDownload(
- (device, url, signal, readTrace, metadata) => {
+ (device, url, signal, readTrace, metadata, onProgress) => {
const active = captureDevice(device);
return queueRead(
"connection",
@@ -593,12 +595,13 @@ export function PeerFileTransport() {
const cached = metadata?.skipCache ? null : await cache?.read(device, url, metadata, () => active() && !signal?.aborted).catch(() => null);
check(cached);
if (cached) {
+ try { onProgress?.(cached.size, cached.size); } catch { /* Observer only. */ }
mobileDebugLog('debug', 'files', 'file cache hit', { trace: readTrace, size: cached.size });
return cached;
}
if (metadata) await cache?.prune(metadata.size).catch(() => false);
check();
- const result = await transfer(device, url, signal, readTrace);
+ const result = await transfer(device, url, signal, readTrace, onProgress);
if (result && active() && !signal?.aborted)
await cache?.store(device, url, metadata, result).catch(() => undefined);
check(result);
@@ -862,6 +865,7 @@ export function PeerFileTransport() {
throw new Error();
sink.handle.writeBytes(bytes);
sink.offset += bytes.length;
+ try { sink.onProgress?.(sink.offset, sink.size); } catch { /* Observer only. */ }
for (const operation of pending.current.values())
operation.refresh?.();
ok = true;
diff --git a/apps/mobile/src/session/HtmlFileReader.tsx b/apps/mobile/src/session/HtmlFileReader.tsx
index 7ee2e9744f..6b5b728f1f 100644
--- a/apps/mobile/src/session/HtmlFileReader.tsx
+++ b/apps/mobile/src/session/HtmlFileReader.tsx
@@ -33,7 +33,7 @@
* 会被 RNW 交给 RN `Linking` 试着让系统处理 —— 于是 `tel:` / `mailto:` / 自定义 scheme
* 会拉起外部应用,把下面这段策略整个绕过去。放到 `['*']` 之后,回调是唯一决策点。
*/
-import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from 'react';
import { StyleSheet, View } from 'react-native';
import { WebView, type WebViewProps } from 'react-native-webview';
import type { ShouldStartLoadRequest, WebViewNavigation } from 'react-native-webview/lib/WebViewTypes';
@@ -48,9 +48,10 @@ import { browserViewportScrollScript } from '@/session/htmlBrowserViewport';
import { useTheme } from '@/theme';
/** The server serves only the downloaded manifest; every HTML has the same CSP and device guard. */
-export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInsets, onNavigationStateChange }: {
+export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInsets, onNavigationStateChange, loading }: {
preview: MobileHtmlPreview;
onError(): void;
+ loading?: ReactNode;
webViewRef?: RefObject<WebView | null>;
viewportInsets?: WebViewProps['contentInset'];
onNavigationStateChange?(preview: MobileHtmlPreview, state: WebViewNavigation): void;
@@ -74,6 +75,7 @@ export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInset
// Diagnostics only: load outcome and timing per mounted snapshot; the URL carries the snapshot token.
const mountedAt = useMemo(() => Date.now(), [preview]);
const failed = (event: string, detail: Record<string, unknown>) => {
+ if (currentPreview.current !== preview) return;
mobileDebugLog('warn', 'files', event, { ms: Date.now() - mountedAt, ...detail });
onError();
};
@@ -122,7 +124,7 @@ export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInset
// Themed backing for the strips under the floating controls; the viewport script paints
// the page canvas itself, so this never becomes the background of an unstyled page.
style={[styles.fill, { backgroundColor: colors.surfaceElevated }, paintedPreview !== preview && styles.unpainted]}
- /></View></View>;
+ />{paintedPreview !== preview && loading ? <View style={StyleSheet.absoluteFill} pointerEvents="none">{loading}</View> : null}</View></View>;
}
export function HtmlFileReader({ html, testID }: { html: string; testID?: string }) {
diff --git a/apps/mobile/src/session/HtmlPreviewLoading.tsx b/apps/mobile/src/session/HtmlPreviewLoading.tsx
new file mode 100644
index 0000000000..30e6f7235b
--- /dev/null
+++ b/apps/mobile/src/session/HtmlPreviewLoading.tsx
@@ -0,0 +1,32 @@
+import { ActivityIndicator, StyleSheet, View } from 'react-native';
+import { useTranslation } from 'react-i18next';
+import { Text } from '@/components/AppText';
+import { useTheme } from '@/theme';
+import { fontWeight, lineHeight, spacing, typeScale } from '@/theme/tokens';
+import { formatByteSize } from './filePreview';
+import type { HtmlPreviewProgress } from './mobileHtmlPreview';
+import { formatTransferProgress } from './transferProgress';
+
+/** Percentages describe the named resource, not an unknowable whole-page total. */
+export function HtmlPreviewLoading({ progress }: { progress?: HtmlPreviewProgress }) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ return <View style={styles.container} testID="filePreview.htmlResourceLoading">
+ <ActivityIndicator color={colors.textTertiary} />
+ <Text style={[styles.hint, { color: colors.textSecondary }]}>{t('files.preview.fetchingHtmlResources')}</Text>
+ {progress ? <>
+ <Text numberOfLines={1} style={[styles.meta, { color: colors.textTertiary }]}>{progress.name}</Text>
+ {progress.total > 0 ? <Text style={[styles.meta, { color: colors.textTertiary }]}>
+ {formatTransferProgress(progress)}
+ </Text> : progress.loaded > 0 ? <Text style={[styles.meta, { color: colors.textTertiary }]}>
+ {formatByteSize(progress.loaded)}
+ </Text> : null}
+ </> : null}
+ </View>;
+}
+
+const styles = StyleSheet.create({
+ container: { flex: 1, justifyContent: 'center', alignItems: 'center', gap: spacing.sm, padding: spacing.lg },
+ hint: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, textAlign: 'center' },
+ meta: { fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, maxWidth: '100%' },
+});
diff --git a/apps/mobile/src/session/mobileHtmlPreview.ts b/apps/mobile/src/session/mobileHtmlPreview.ts
index b1b646a5a3..09d9f1c96d 100644
--- a/apps/mobile/src/session/mobileHtmlPreview.ts
+++ b/apps/mobile/src/session/mobileHtmlPreview.ts
@@ -8,10 +8,13 @@ import { errorText } from '@/debug/fileDiagnostics';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
-import { assertHtmlSnapshotActive, collectHtmlSnapshot, htmlSnapshotLocation, HTML_SNAPSHOT_MAX_ENTRIES, snapshotDocumentPaths } from './htmlDirectorySnapshot';
+import { assertHtmlSnapshotActive, collectHtmlSnapshot, htmlSnapshotLocation, HTML_SNAPSHOT_MAX_ENTRIES, HTML_SNAPSHOT_MAX_BYTES, snapshotDocumentPaths } from './htmlDirectorySnapshot';
import { HTML_SNAPSHOT_CSP, withSnapshotHtmlCsp } from './htmlPreviewCsp';
import { fetchRemoteAbsFileOnce, type RemoteAbsFileFetchDeps } from './remoteAbsFileFetch';
import type { RemoteMediaSshContext } from './fileBrowserGallery';
+import { createTransferProgressMeter, type TransferProgress } from './transferProgress';
+import { createMobileHtmlPreviewCache, type MobileHtmlPreviewCache } from './mobileHtmlPreviewCache';
+import { subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';
export interface MobileHtmlPreview {
url: string;
@@ -19,7 +22,87 @@ export interface MobileHtmlPreview {
onDemand?: boolean;
close(): Promise<void>;
}
-export type PrepareMobileHtmlPreview = (absPath: string, signal: AbortSignal) => Promise<MobileHtmlPreview>;
+export interface HtmlPreviewProgress extends TransferProgress { name: string }
+type ProgressListener = (progress: HtmlPreviewProgress) => void;
+export type PrepareMobileHtmlPreview = (absPath: string, signal: AbortSignal, onProgress?: ProgressListener) => Promise<MobileHtmlPreview>;
+
+type HtmlPreviewDeps = RemoteAbsFileFetchDeps & {
+ maker: MobileMakerTransport;
+ ssh?: RemoteMediaSshContext | null;
+ deleteOssObject(key: string): void;
+};
+
+/** One meter per file; a fallback resets its byte count instead of inventing overall page progress. */
+function resourceProgress(name: string, signal: AbortSignal, listener?: ProgressListener) {
+ const measure = createTransferProgressMeter();
+ let last = -Infinity;
+ let lastTotal = -1;
+ return (loaded: number, total: number) => {
+ if (signal.aborted || !listener) return;
+ const progress = measure(loaded, total);
+ const now = Date.now();
+ if (total === lastTotal && loaded !== 0 && loaded !== total && now - last < 200) return;
+ last = now;
+ lastTotal = total;
+ try { listener({ ...progress, name }); } catch { /* Observation must not fail a download. */ }
+ };
+}
+
+/** Copy into the existing preview directory before allowing WebKit to request the document. */
+async function materializeResource(deps: HtmlPreviewDeps, root: string, relative: string,
+ dir: Directory, filename: string, signal: AbortSignal, onProgress?: ProgressListener, cache?: MobileHtmlPreviewCache) {
+ const destination = new File(dir, filename);
+ const uploaded = new Set<string>();
+ const progress = resourceProgress(relative, signal, onProgress);
+ progress(0, 0);
+ try {
+ assertHtmlSnapshotActive(signal);
+ const media = await fetchRemoteAbsFileOnce(deps, root.replace(/\/$/, '') + '/' + relative, deps.ssh,
+ (key) => uploaded.add(key), { baseDir: root, maxBytes: FILE_PEER_MAX_BYTES }, signal, progress);
+ try {
+ assertHtmlSnapshotActive(signal);
+ if (!Number.isSafeInteger(media.size) || media.size < 0 || media.size > FILE_PEER_MAX_BYTES) throw new Error('PREVIEW_TOO_LARGE');
+ if (!(Paths.availableDiskSpace >= media.size + 256 * 1024 * 1024)) throw new Error('PREVIEW_DISK_FULL');
+ if (media.inlineBase64 !== undefined) {
+ destination.create();
+ destination.write(Uint8Array.from(atob(media.inlineBase64), (char) => char.charCodeAt(0)));
+ } else if (media.url.startsWith('file://')) {
+ await new File(media.url).copy(destination);
+ } else {
+ progress(0, media.size);
+ let exceeded = false;
+ const download = createDownloadResumable(media.url, destination.uri, {}, (value) => {
+ if (value.totalBytesWritten > media.size) { exceeded = true; void download.pauseAsync().catch(() => {}); }
+ else progress(value.totalBytesWritten, media.size);
+ });
+ const abort = () => { void download.pauseAsync().catch(() => {}); };
+ signal.addEventListener('abort', abort, { once: true });
+ try {
+ assertHtmlSnapshotActive(signal);
+ const result = await download.downloadAsync();
+ assertHtmlSnapshotActive(signal);
+ if (!result || result.status !== 200 || exceeded) throw new Error('PREVIEW_CHANGED');
+ } finally { signal.removeEventListener('abort', abort); }
+ }
+ assertHtmlSnapshotActive(signal);
+ if (destination.size !== media.size) throw new Error('PREVIEW_CHANGED');
+ progress(media.size, media.size);
+ const mime = MIME[relative.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
+ const html = mime === 'text/html' ? new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes()) : undefined;
+ assertHtmlSnapshotActive(signal);
+ await cache?.store(relative, destination, mime);
+ assertHtmlSnapshotActive(signal);
+ if (html !== undefined) {
+ destination.write(withSnapshotHtmlCsp(html));
+ }
+ return { filename, mime, bytes: media.size,
+ route: media.inlineBase64 !== undefined ? 'inline' : media.url.startsWith('file://') ? 'direct' : 'upload' };
+ } finally { if (media.url.startsWith('file://')) releasePeerMedia(media.url); }
+ } catch (error) {
+ try { destination.delete(); } catch {}
+ throw error;
+ } finally { for (const key of uploaded) deps.deleteOssObject(key); }
+}
const MIME: Record<string, string> = {
html: 'text/html', htm: 'text/html', css: 'text/css', js: 'text/javascript', mjs: 'text/javascript',
@@ -44,26 +127,57 @@ function sweepInterruptedSnapshots() {
}
/** Source identity stays in the transport; no device credentials enter the snapshot. */
-export async function prepareMobileHtmlPreview(absPath: string, deps: RemoteAbsFileFetchDeps & {
- maker: MobileMakerTransport;
- ssh?: RemoteMediaSshContext | null;
- deleteOssObject(key: string): void;
-}, signal: AbortSignal): Promise<MobileHtmlPreview> {
+export async function prepareMobileHtmlPreview(absPath: string, deps: HtmlPreviewDeps,
+ signal: AbortSignal, onProgress?: ProgressListener): Promise<MobileHtmlPreview> {
if (!native) throw new Error('HTML_PREVIEW_NATIVE_UNAVAILABLE');
+ const { root, entry } = htmlSnapshotLocation(absPath);
+ if (/[\\:\0\r\n]/.test(entry) || entry.startsWith('.')) throw new Error('NOT_FOUND');
+ const cache = createMobileHtmlPreviewCache(deps.deviceId, root, deps.ssh);
+ const lifetime = new AbortController();
+ let active: MobileHtmlPreview | undefined;
+ const abort = () => {
+ lifetime.abort();
+ void active?.close().catch(() => {});
+ };
+ signal.addEventListener('abort', abort, { once: true });
+ const unsubscribe = subscribeMobileAuthOwner(() => { if (cache && !cache.current()) abort(); });
+ const dispose = () => {
+ signal.removeEventListener('abort', abort);
+ unsubscribe();
+ abort();
+ };
+ if (signal.aborted || (cache && !cache.current())) abort();
mobileDebugLog('debug', 'files', 'html preview mode', {
onDemand: !!(native.startOnDemand && native.resolveRequest),
ssh: !!deps.ssh,
});
- if (native.startOnDemand && native.resolveRequest) return prepareOnDemand(absPath, deps, signal);
- const server = native;
+ try {
+ const preview = native.startOnDemand && native.resolveRequest
+ ? await prepareOnDemand(absPath, deps, lifetime.signal, onProgress, cache)
+ : await prepareLegacy(absPath, deps, lifetime.signal, onProgress, cache);
+ active = preview;
+ if (lifetime.signal.aborted) { await preview.close(); throw new Error('PREVIEW_CANCELLED'); }
+ return { ...preview, close: async () => { dispose(); await preview.close(); } };
+ } catch (error) { dispose(); throw error; }
+}
+
+async function prepareLegacy(absPath: string, deps: HtmlPreviewDeps, signal: AbortSignal,
+ onProgress?: ProgressListener, cache?: MobileHtmlPreviewCache, preferCache = true): Promise<MobileHtmlPreview> {
+ const server = native!;
assertHtmlSnapshotActive(signal);
const { root, entry } = htmlSnapshotLocation(absPath);
- // SSH enumeration must keep the original session workdir so the desktop resolves the SSH endpoint.
const listingRoot = deps.ssh?.workdir ?? root;
- const prefix = deps.ssh ? root.slice(listingRoot.replace(/\/$/, '').length).replace(/^\//, '') : '';
if (deps.ssh && root !== listingRoot && !root.startsWith(listingRoot.replace(/\/$/, '') + '/')) throw new Error('OUTSIDE_WORKDIR');
+ if (preferCache && cache) {
+ const restored = await restoreLegacy(absPath, deps, signal, cache);
+ if (restored) return restored;
+ }
+ // SSH enumeration must keep the original session workdir so the desktop resolves the SSH endpoint.
+ const prefix = deps.ssh ? root.slice(listingRoot.replace(/\/$/, '').length).replace(/^\//, '') : '';
const caps = await withTransientRemoteRetry(async () => {
+ assertHtmlSnapshotActive(signal);
await deps.openLink(deps.deviceId);
+ assertHtmlSnapshotActive(signal);
return deps.maker.fileBrowser.caps(listingRoot);
});
if (!caps.ok || caps.completeDirectoryListing !== true) throw new Error('COMPLETE_DIRECTORY_LISTING_UNSUPPORTED');
@@ -72,6 +186,7 @@ export async function prepareMobileHtmlPreview(absPath: string, deps: RemoteAbsF
const result = await withTransientRemoteRetry(async () => {
assertHtmlSnapshotActive(signal);
await deps.openLink(deps.deviceId);
+ assertHtmlSnapshotActive(signal);
return deps.maker.fileBrowser.listDir(listingRoot, path, { includeIgnored: true, maxEntries: HTML_SNAPSHOT_MAX_ENTRIES });
});
if (!prefix || !Array.isArray(result)) return result;
@@ -86,21 +201,25 @@ export async function prepareMobileHtmlPreview(absPath: string, deps: RemoteAbsF
const token = Array.from(getRandomBytes(24), (n) => n.toString(16).padStart(2, '0')).join('');
const dir = new Directory(Paths.cache, 'html-previews', token);
dir.create({ intermediates: true });
- let closed = false;
- const close = async () => {
- if (closed) return;
- closed = true;
- try { await server.stop(token); } finally { try { dir.delete(); } catch { /* OS cache reclamation is the fallback. */ } }
+ let closing: Promise<void> | undefined;
+ const close = () => {
+ if (closing) return closing;
+ closing = (async () => {
+ try { await server.stop(token); } finally { try { dir.delete(); } catch { /* OS cache reclamation is the fallback. */ } }
+ })();
+ return closing;
};
try {
const manifest: string[][] = [];
for (const [index, file] of files.entries()) {
assertHtmlSnapshotActive(signal);
+ const progress = resourceProgress(file.relPath, signal, onProgress);
+ progress(0, file.size);
const uploaded = new Set<string>();
const destination = new File(dir, String(index));
try {
const media = await fetchRemoteAbsFileOnce(deps, root.replace(/\/$/, '') + '/' + file.relPath, deps.ssh,
- (key) => uploaded.add(key), { baseDir: root, maxBytes: Math.max(1, file.size) }, signal);
+ (key) => uploaded.add(key), { baseDir: root, maxBytes: Math.max(1, file.size) }, signal, progress);
assertHtmlSnapshotActive(signal);
if (media.size !== file.size) throw new Error('PREVIEW_CHANGED');
if (media.inlineBase64 !== undefined) {
@@ -113,8 +232,10 @@ export async function prepareMobileHtmlPreview(absPath: string, deps: RemoteAbsF
if (destination.size !== file.size) throw new Error('PREVIEW_CHANGED');
} else {
let exceeded = false;
- const download = createDownloadResumable(media.url, destination.uri, {}, (progress) => {
- if (progress.totalBytesWritten > file.size) { exceeded = true; void download.pauseAsync().catch(() => {}); }
+ progress(0, file.size);
+ const download = createDownloadResumable(media.url, destination.uri, {}, (value) => {
+ if (value.totalBytesWritten > file.size) { exceeded = true; void download.pauseAsync().catch(() => {}); }
+ else progress(value.totalBytesWritten, file.size);
});
const abort = () => { void download.pauseAsync().catch(() => {}); };
signal.addEventListener('abort', abort, { once: true });
@@ -125,10 +246,14 @@ export async function prepareMobileHtmlPreview(absPath: string, deps: RemoteAbsF
if (!result || result.status !== 200 || exceeded || destination.size !== file.size) throw new Error('PREVIEW_CHANGED');
} finally { signal.removeEventListener('abort', abort); }
}
+ progress(file.size, file.size);
const mime = MIME[file.relPath.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
- if (mime === 'text/html') {
+ const text = mime === 'text/html' ? new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes()) : undefined;
+ assertHtmlSnapshotActive(signal);
+ await cache?.store(file.relPath, destination, mime);
+ assertHtmlSnapshotActive(signal);
+ if (text !== undefined) {
// Reject invalid UTF-8 instead of publishing a corrupted page. No source text is truncated.
- const text = new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes());
destination.write(withSnapshotHtmlCsp(text));
}
manifest.push([file.relPath, String(index), mime]);
@@ -137,16 +262,63 @@ export async function prepareMobileHtmlPreview(absPath: string, deps: RemoteAbsF
assertHtmlSnapshotActive(signal);
const url = await server.start(decodeURIComponent(dir.uri.replace(/^file:\/\//, '')), entry, token, HTML_SNAPSHOT_CSP, manifest);
assertHtmlSnapshotActive(signal);
+ await cache?.storeManifest(entry, files, new File(dir, 'manifest.json'));
+ assertHtmlSnapshotActive(signal);
return { url, documents: snapshotDocumentPaths(files), close };
} catch (error) { await close(); throw error; }
}
+/** Old native binaries can publish only the files restored before starting their server. */
+async function restoreLegacy(absPath: string, deps: HtmlPreviewDeps, signal: AbortSignal,
+ cache: NonNullable<MobileHtmlPreviewCache>): Promise<MobileHtmlPreview | null> {
+ const { entry } = htmlSnapshotLocation(absPath);
+ const files = await cache.manifest(entry) ?? [{ name: entry, relPath: entry, type: 'file' as const, size: 0 }];
+ assertHtmlSnapshotActive(signal);
+ sweepInterruptedSnapshots();
+ const token = Array.from(getRandomBytes(24), (n) => n.toString(16).padStart(2, '0')).join('');
+ const dir = new Directory(Paths.cache, 'html-previews', token);
+ dir.create({ intermediates: true });
+ const refresh = new AbortController();
+ let closing: Promise<void> | undefined;
+ const close = () => {
+ if (closing) return closing;
+ refresh.abort();
+ closing = (async () => {
+ try { await native!.stop(token); } finally { try { dir.delete(); } catch {} }
+ })();
+ return closing;
+ };
+ try {
+ const manifest: string[][] = [];
+ const restored = [];
+ let remaining = HTML_SNAPSHOT_MAX_BYTES;
+ for (const [index, file] of files.entries()) {
+ const destination = new File(dir, String(index));
+ const size = await cache.copy(file.relPath, destination, remaining);
+ assertHtmlSnapshotActive(signal);
+ if (size === null) {
+ if (file.relPath === entry) { await close(); return null; }
+ continue;
+ }
+ const mime = MIME[file.relPath.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
+ if (mime === 'text/html') destination.write(withSnapshotHtmlCsp(new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes())));
+ manifest.push([file.relPath, String(index), mime]);
+ restored.push({ ...file, size });
+ remaining -= size;
+ }
+ assertHtmlSnapshotActive(signal);
+ const url = await native!.start(decodeURIComponent(dir.uri.replace(/^file:\/\//, '')), entry, token, HTML_SNAPSHOT_CSP, manifest);
+ assertHtmlSnapshotActive(signal);
+ // Refresh a separate snapshot, leaving the visible copy and its scroll position intact.
+ void prepareLegacy(absPath, deps, refresh.signal, undefined, cache, false)
+ .then((updated) => updated.close()).catch(() => {});
+ return { url, documents: snapshotDocumentPaths(restored), close };
+ } catch (error) { await close(); throw error; }
+}
+
/** New native binaries fetch each requested resource; older binaries retain their existing snapshot API. */
-async function prepareOnDemand(absPath: string, deps: RemoteAbsFileFetchDeps & {
- maker: MobileMakerTransport;
- ssh?: RemoteMediaSshContext | null;
- deleteOssObject(key: string): void;
-}, signal: AbortSignal): Promise<MobileHtmlPreview> {
+async function prepareOnDemand(absPath: string, deps: HtmlPreviewDeps,
+ signal: AbortSignal, onProgress?: ProgressListener, cache?: MobileHtmlPreviewCache): Promise<MobileHtmlPreview> {
const server = native!;
assertHtmlSnapshotActive(signal);
const { root, entry } = htmlSnapshotLocation(absPath);
@@ -160,9 +332,28 @@ async function prepareOnDemand(absPath: string, deps: RemoteAbsFileFetchDeps & {
let sequence = 0;
let requestCount = 0;
const requests = new Map<string, AbortController>();
- const pending = new Set<Promise<void>>();
+ const pending = new Set<Promise<unknown>>();
const materialized = new Map<string, { filename: string; mime: string }>();
const queue = createFileReadQueue();
+ const loadResource = async (relative: string, filename: string, requestSignal: AbortSignal) => {
+ const destination = new File(dir, filename);
+ const size = await cache?.copy(relative, destination);
+ assertHtmlSnapshotActive(requestSignal);
+ if (size != null) {
+ const mime = MIME[relative.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
+ if (mime === 'text/html') destination.write(withSnapshotHtmlCsp(new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes())));
+ assertHtmlSnapshotActive(requestSignal);
+ const updatedName = `${filename}-refresh`;
+ const update = materializeResource(deps, root, relative, dir, updatedName, signal, undefined, cache)
+ .then(() => {}, () => {}).finally(() => {
+ try { new File(dir, updatedName).delete(); } catch {}
+ pending.delete(update);
+ });
+ pending.add(update);
+ return { filename, mime, bytes: size, route: 'cache' };
+ }
+ return materializeResource(deps, root, relative, dir, filename, requestSignal, onProgress, cache);
+ };
const requestListener = server.addListener('resourceRequest', (event) => {
if (event.token !== token || closed || requests.has(event.id)) return;
const controller = new AbortController();
@@ -176,7 +367,6 @@ async function prepareOnDemand(absPath: string, deps: RemoteAbsFileFetchDeps & {
let route = 'unknown';
let bytes = 0;
const startedAt = Date.now();
- const uploaded = new Set<string>();
try {
assertHtmlSnapshotActive(controller.signal);
const relative = event.path;
@@ -190,40 +380,10 @@ async function prepareOnDemand(absPath: string, deps: RemoteAbsFileFetchDeps & {
}
const filename = String(sequence++);
destination = new File(dir, filename);
- const media = await fetchRemoteAbsFileOnce(deps, root.replace(/\/$/, '') + '/' + relative, deps.ssh,
- (key) => uploaded.add(key), { baseDir: root, maxBytes: FILE_PEER_MAX_BYTES }, controller.signal);
- assertHtmlSnapshotActive(controller.signal);
- bytes = media.size;
- route = media.inlineBase64 !== undefined ? 'inline' : media.url.startsWith('file://') ? 'direct' : 'upload';
- if (!(Paths.availableDiskSpace >= media.size + 256 * 1024 * 1024)) {
- if (media.url.startsWith('file://')) releasePeerMedia(media.url);
- throw new Error('PREVIEW_DISK_FULL');
- }
- if (media.inlineBase64 !== undefined) {
- destination.create();
- destination.write(Uint8Array.from(atob(media.inlineBase64), (char) => char.charCodeAt(0)));
- } else if (media.url.startsWith('file://')) {
- try { await new File(media.url).copy(destination); } finally { releasePeerMedia(media.url); }
- } else {
- let exceeded = false;
- const download = createDownloadResumable(media.url, destination.uri, {}, (progress) => {
- if (progress.totalBytesWritten > media.size) { exceeded = true; void download.pauseAsync().catch(() => {}); }
- });
- const abort = () => { void download.pauseAsync().catch(() => {}); };
- controller.signal.addEventListener('abort', abort, { once: true });
- try {
- assertHtmlSnapshotActive(controller.signal);
- const result = await download.downloadAsync();
- if (!result || result.status !== 200 || exceeded) throw new Error('PREVIEW_CHANGED');
- } finally { controller.signal.removeEventListener('abort', abort); }
- }
- assertHtmlSnapshotActive(controller.signal);
- if (destination.size !== media.size) throw new Error('PREVIEW_CHANGED');
- const mime = MIME[relative.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
- if (mime === 'text/html') {
- const html = new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes());
- destination.write(withSnapshotHtmlCsp(html));
- }
+ const resource = await loadResource(relative, filename, controller.signal);
+ const { mime } = resource;
+ bytes = resource.bytes;
+ route = resource.route;
assertHtmlSnapshotActive(controller.signal);
accepted = await server.resolveRequest!(token, event.id, filename, mime, 200);
if (accepted) materialized.set(relative, { filename, mime });
@@ -245,8 +405,7 @@ async function prepareOnDemand(absPath: string, deps: RemoteAbsFileFetchDeps & {
await server.resolveRequest!(token, event.id, '', '', status);
}
} finally {
- for (const key of uploaded) deps.deleteOssObject(key);
- // Accepted files belong to the native response and are deleted when its socket closes.
+ // Accepted files remain available for subsequent requests until the preview closes.
if (!accepted && destination) { try { destination.delete(); } catch {} }
}
}, controller.signal);
@@ -256,22 +415,32 @@ async function prepareOnDemand(absPath: string, deps: RemoteAbsFileFetchDeps & {
const closedListener = server.addListener('resourceClosed', (event) => {
if (event.token === token) requests.get(event.id)?.abort();
});
- const close = async () => {
- if (closed) return;
+ let closing: Promise<void> | undefined;
+ const close = () => {
+ if (closing) return closing;
closed = true;
signal.removeEventListener('abort', abort);
requestListener.remove();
closedListener.remove();
for (const request of requests.values()) request.abort();
- try { await server.stop(token); } finally {
- // Downloads may settle after an abort. Let their owner finish cleanup before removing the directory.
- await Promise.allSettled([...pending]);
- try { dir.delete(); } catch {}
- }
+ closing = (async () => {
+ try { await server.stop(token); } finally {
+ // Downloads may settle after an abort. Drain the entry and all resources before cleanup.
+ await Promise.allSettled([...pending]);
+ try { dir.delete(); } catch {}
+ }
+ })();
+ return closing;
};
const abort = () => { void close().catch(() => {}); };
signal.addEventListener('abort', abort, { once: true });
try {
+ assertHtmlSnapshotActive(signal);
+ // Keep weak-network waiting outside WebKit's document-request timeout. Only the
+ // entry is fetched eagerly; sibling resources retain the existing on-demand queue.
+ const preparation = loadResource(entry, String(sequence++), signal);
+ pending.add(preparation);
+ try { materialized.set(entry, await preparation); } finally { pending.delete(preparation); }
assertHtmlSnapshotActive(signal);
const url = await server.startOnDemand!(decodeURIComponent(dir.uri.replace(/^file:\/\//, '')), entry, token, HTML_SNAPSHOT_CSP);
if (closed || signal.aborted) {
diff --git a/apps/mobile/src/session/mobileHtmlPreviewCache.ts b/apps/mobile/src/session/mobileHtmlPreviewCache.ts
new file mode 100644
index 0000000000..87d8fd0a37
--- /dev/null
+++ b/apps/mobile/src/session/mobileHtmlPreviewCache.ts
@@ -0,0 +1,70 @@
+import { File } from 'expo-file-system';
+import { FILE_PEER_MAX_BYTES } from '@cindy/device-link';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { getActiveMobileSessionRealm } from '@/config/env';
+import { createPeerFileCache } from '@/device-link/peerFileCache';
+import { effectiveRemoteMediaSshContext, remoteFileMediaUrl, type RemoteMediaSshContext } from './fileBrowserGallery';
+import { HTML_SNAPSHOT_MAX_ENTRIES, HTML_SNAPSHOT_MAX_BYTES, type HtmlSnapshotEntry } from './htmlDirectorySnapshot';
+
+/** Reuse the account's existing disk cache and pressure-based eviction. No network here. */
+export function createMobileHtmlPreviewCache(deviceId: string, root: string, ssh?: RemoteMediaSshContext | null) {
+ const owner = getMobileAuthOwner();
+ if (!owner.accountId) return undefined;
+ const cache = createPeerFileCache(JSON.stringify([getActiveMobileSessionRealm(), owner.accountId]));
+ const current = () => isMobileAuthOwnerCurrent(owner);
+ const key = (relative: string, manifest = false) => JSON.stringify([
+ deviceId, effectiveRemoteMediaSshContext(ssh), root, manifest ? 'manifest' : 'resource', relative,
+ ]);
+ return {
+ current,
+ async copy(relative: string, destination: File, maxBytes = FILE_PEER_MAX_BYTES): Promise<number | null> {
+ try {
+ if (!current()) return null;
+ const hit = await (await cache).lookupPreview(key(relative), {
+ device: deviceId,
+ url: remoteFileMediaUrl(root.replace(/\/$/, '') + '/' + relative, undefined, ssh,
+ { baseDir: root, maxBytes: FILE_PEER_MAX_BYTES }),
+ });
+ if (!hit || hit.size > maxBytes || !current()) return null;
+ await new File(hit.uri).copy(destination);
+ if (current() && destination.size === hit.size) return hit.size;
+ } catch { /* Missing/evicted files are ordinary cache misses. */ }
+ try { destination.delete(); } catch {}
+ return null;
+ },
+ async store(relative: string, source: File, mime: string) {
+ try {
+ const disk = await cache;
+ if (current()) await disk.storePreview(key(relative), source.uri, mime, source.size);
+ } catch { /* Persistence must not fail a readable preview. */ }
+ },
+ async manifest(entry: string): Promise<HtmlSnapshotEntry[] | null> {
+ try {
+ const hit = await (await cache).lookupPreview(key(entry, true));
+ if (!hit || !current() || hit.size > 1024 * 1024) return null;
+ const files: unknown = JSON.parse(await new File(hit.uri).text());
+ if (!current() || !Array.isArray(files) || files.length > HTML_SNAPSHOT_MAX_ENTRIES) return null;
+ let total = 0;
+ const seen = new Set<string>();
+ for (const file of files) {
+ if (!file || file.type !== 'file' || typeof file.relPath !== 'string'
+ || /[\\:\0\r\n]/.test(file.relPath) || file.relPath.split('/').length > 32
+ || file.relPath.split('/').some((p: string) => !p || p.startsWith('.'))
+ || seen.has(file.relPath) || !Number.isSafeInteger(file.size) || file.size < 0) return null;
+ seen.add(file.relPath);
+ total += file.size;
+ }
+ return total <= HTML_SNAPSHOT_MAX_BYTES && seen.has(entry) ? files : null;
+ } catch { return null; }
+ },
+ async storeManifest(entry: string, files: HtmlSnapshotEntry[], temporary: File) {
+ try {
+ temporary.write(JSON.stringify(files));
+ const disk = await cache;
+ if (current()) await disk.storePreview(key(entry, true), temporary.uri, 'application/json', temporary.size);
+ } catch { /* Old clients may rebuild the directory if its manifest was evicted. */ }
+ finally { try { temporary.delete(); } catch {} }
+ },
+ };
+}
+export type MobileHtmlPreviewCache = ReturnType<typeof createMobileHtmlPreviewCache>;
diff --git a/apps/mobile/src/session/remoteAbsFileFetch.ts b/apps/mobile/src/session/remoteAbsFileFetch.ts
index 865f9f2149..7ebdc800c5 100644
--- a/apps/mobile/src/session/remoteAbsFileFetch.ts
+++ b/apps/mobile/src/session/remoteAbsFileFetch.ts
@@ -167,14 +167,18 @@ export async function fetchRemoteAbsFileOnce(
*/
constraints?: RemoteMediaFetchConstraints | null,
signal?: AbortSignal,
+ onProgress?: (loaded: number, total: number) => void,
): Promise<MobileResolvedRemoteMedia> {
return withTransientRemoteRetry(async () => {
+ const assertActive = () => { if (signal?.aborted) throw new Error('PREVIEW_CANCELLED'); };
+ assertActive();
await deps.openLink(deps.deviceId);
+ assertActive();
// kind 只影响结果的 previewable 标志(此处不消费),按 image 占位。
return resolveMobileRemoteMedia(
{ kind: 'image', url: remoteFileMediaUrl(absPath, undefined, ssh, constraints) },
{ fetchRemoteMedia: deps.maker.fetchRemoteMedia, presignGet: deps.presignGet },
- { onOssKey, signal, stream: false },
+ { onOssKey, signal, stream: false, ...(onProgress ? { onProgress } : {}) },
);
});
}
diff --git a/apps/mobile/src/session/remoteMedia.ts b/apps/mobile/src/session/remoteMedia.ts
index 85414bada1..c868d68840 100644
--- a/apps/mobile/src/session/remoteMedia.ts
+++ b/apps/mobile/src/session/remoteMedia.ts
@@ -48,6 +48,8 @@ export interface MobileResolvedRemoteMedia {
}
export interface MobileRemoteMediaFetchOptions {
+ /** Local receiver bytes; never sent to the remote computer. */
+ onProgress?: (loaded: number, total: number) => void;
/** Local read intent only; false for consumers that copy complete bytes. */
stream?: boolean;
skipCache?: boolean;
@@ -66,6 +68,7 @@ export interface MobileRemoteMediaResolverDeps {
}
export interface MobileRemoteMediaResolveOptions {
+ onProgress?: (loaded: number, total: number) => void;
stream?: boolean;
signal?: AbortSignal;
/** 强制被控端绕过上传去重缓存(上次的 ossKey 已悬空时的自愈路径)。 */
@@ -180,6 +183,7 @@ export async function resolveMobileRemoteMedia(
throw new Error(i18n.t("composer.attachments.notFetchableMedia"));
}
const fetchOpts = {
+ ...(opts?.onProgress ? { onProgress: opts.onProgress } : {}),
...(opts?.stream !== undefined ? { stream: opts.stream } : {}),
...(opts?.onOssKey ? { onDiscardOssKey: opts.onOssKey } : {}),
...(opts?.signal ? { signal: opts.signal } : {}),
diff --git a/apps/mobile/src/session/useHtmlSnapshot.ts b/apps/mobile/src/session/useHtmlSnapshot.ts
index 597d412f0a..67bfbddcbb 100644
--- a/apps/mobile/src/session/useHtmlSnapshot.ts
+++ b/apps/mobile/src/session/useHtmlSnapshot.ts
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { AppState } from 'react-native';
-import type { MobileHtmlPreview, PrepareMobileHtmlPreview } from './mobileHtmlPreview';
+import type { HtmlPreviewProgress, MobileHtmlPreview, PrepareMobileHtmlPreview } from './mobileHtmlPreview';
import { errorText } from '@/debug/fileDiagnostics';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
@@ -10,6 +10,7 @@ export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: Prep
const [epoch, setEpoch] = useState(0);
const [result, setResult] = useState<{
preview?: MobileHtmlPreview; error?: unknown; path?: string; prepare?: PrepareMobileHtmlPreview; epoch?: number;
+ progress?: HtmlPreviewProgress;
}>({});
useEffect(() => {
const subscription = AppState.addEventListener('change', (state) => {
@@ -24,13 +25,15 @@ export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: Prep
const controller = new AbortController();
const startedAt = Date.now();
let preview: MobileHtmlPreview | undefined;
- void prepare(absPath, controller.signal).then((value) => {
+ void prepare(absPath, controller.signal, (progress) => {
+ if (!controller.signal.aborted) setResult((previous) => ({ ...previous, progress, path: absPath, prepare, epoch }));
+ }).then((value) => {
preview = value;
mobileDebugLog('debug', 'files', 'html preview prepared', {
ms: Date.now() - startedAt, onDemand: value.onDemand === true, aborted: controller.signal.aborted,
});
if (controller.signal.aborted) void value.close().catch(() => {});
- else setResult({ preview: value, path: absPath, prepare, epoch });
+ else setResult((previous) => ({ ...previous, preview: value, path: absPath, prepare, epoch }));
}).catch((error: unknown) => {
mobileDebugLog(controller.signal.aborted ? 'debug' : 'warn', 'files', 'html preview prepare failed', {
ms: Date.now() - startedAt, aborted: controller.signal.aborted, error: errorText(error),
@@ -46,6 +49,7 @@ export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: Prep
return {
preview: current ? result.preview : undefined,
error: current ? result.error : undefined,
+ progress: current ? result.progress : undefined,
foreground, retry: () => setEpoch((value) => value + 1),
};
}