Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(html-preview): 减少重复打开闪动并在后台校验后更新页面
Dashabb6249062a2
diff --git a/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts b/apps/desktop/src/main/file-browser/__tests__/html-preview.test.tsindex 5efeb7ca38..242f4a38e6 100644--- a/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import { get } from 'node:http';+import { runInNewContext } from 'node:vm';import { statEntry } from '@cindy/file-browser-core';import { HTML_SNAPSHOT_CSP, withSnapshotHtmlCsp } from '@cindy/maker-shared/file-preview';import {@@ -45,6 +46,73 @@ async function fixture() {};}describe('directory HTML preview', () => {+ // Unit/loopback integration: a cached HTML response must arrive before remote+ // validation; only different bytes from that check permit the page to reload.+ // The existing fixture has no stale-cache/update handshake coverage.+ it.each(['changed', 'unchanged', 'offline'] as const)('checks cached HTML once without blocking its first response (%s)', async (outcome) => {+ const { dir, source, args } = await fixture();+ const oldHtml = '\uFEFF<!doctype html><h1>old</h1>';+ const nextHtml = outcome === 'changed' ? '<h1>new</h1>' : oldHtml;+ const cached = path.join(dir, 'cached.html');+ const cachedScript = path.join(dir, 'cached.js');+ await fs.writeFile(cached, oldHtml);+ await fs.writeFile(cachedScript, 'old script');+ await fs.writeFile(args.absPath, nextHtml);+ let finish!: () => void;+ const check = new Promise<void>(resolve => { finish = resolve; });+ const read = vi.fn(async (root: string, file: { relPath: string }) => {+ await check;+ if (outcome === 'offline') throw new Error('offline');+ return path.join(root, file.relPath);+ });+ const preview = await createHtmlPreview(args, {+ ...source, read,+ cached: async (_root, rel) => rel === 'index.html' ? cached : cachedScript,+ });+ cleanups.push(preview.close);+ const entry = await fetch(preview.url, { redirect: 'manual' });+ const cookie = entry.headers.get('set-cookie')!.split(';')[0];+ const headers = { Cookie: cookie };+ const origin = new URL(preview.url).origin;+ const first = await (await fetch(origin + '/index.html', { headers })).text();+ expect(first).toContain(oldHtml.slice(1));+ // fetch.text strips the leading BOM; no second BOM may be inserted in the body.+ expect(first).not.toContain('\uFEFF');+ const updatePath = /fetch\("([^"\n]+\/updated)"/.exec(first)?.[1];+ expect(updatePath).toBeTruthy();+ expect((await fetch(origin + updatePath)).status).toBe(403);+ const script = /<script>(\(\(\)=>\{const page=[\s\S]*?)<\/script>/.exec(first)![1];+ const reload = vi.fn();+ let onLoad!: () => Promise<void>;+ let observed!: Promise<unknown>;+ const checkFetch = vi.fn((url: string) => {+ observed = fetch(origin + url, { headers }).then(async response => {+ const changed = await response.json();+ expect(changed).toBe(outcome === 'changed');+ return { ok: true, json: () => Promise.resolve(changed) };+ });+ return observed;+ });+ const addEventListener = vi.fn((_event: string, callback: typeof onLoad) => { onLoad = callback; });+ runInNewContext(script, { location: { pathname: '/index.html', reload }, addEventListener, fetch: checkFetch });+ expect(checkFetch).not.toHaveBeenCalled();+ expect(addEventListener).toHaveBeenCalledWith('load', expect.any(Function), { once: true });+ onLoad();+ finish();+ await observed;+ // Drain the response.json/reload promise chain without a wall-clock delay.+ await new Promise<void>(resolve => setImmediate(resolve));+ expect(checkFetch).toHaveBeenCalledOnce();+ expect(reload).toHaveBeenCalledTimes(outcome === 'changed' ? 1 : 0);+ const reopened = await (await fetch(origin + '/index.html', { headers })).text();+ if (outcome === 'changed') {+ expect(reopened).toBe(withSnapshotHtmlCsp(nextHtml));+ expect(await (await fetch(origin + '/dist/app.js', { headers })).text()).toBe('export const test = true;');+ } else expect(reopened).toBe(first);+ expect(read.mock.calls.filter(([, file]) => file.relPath === 'index.html')).toHaveLength(1);+ expect(await (await fetch(origin + updatePath, { headers })).json()).toBe(false);+ });+it('bounds copies and refuses links instead of reading their targets', async () => {const { dir } = await fixture();const source = path.join(dir, 'index.html');diff --git a/apps/desktop/src/main/file-browser/html-preview.ts b/apps/desktop/src/main/file-browser/html-preview.tsindex c3b0bce565..b9557d43e7 100644--- a/apps/desktop/src/main/file-browser/html-preview.ts+++ b/apps/desktop/src/main/file-browser/html-preview.ts@@ -139,6 +139,10 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSoconst pending = new Set<Promise<void>>();const queue = createFileReadQueue();const materialized = new Map<string, { path: string; size: number }>();+ const token = randomBytes(24).toString('hex');+ const updatePath = `/${token}/updated`;+ let entryUpdate: Promise<{ path: string; size: number } | null> | undefined;+ let updateApplied = false;const current = () => !closed && !source.signal?.aborted && source.isCurrent?.() !== false;const close = async () => {closed = true;@@ -170,25 +174,27 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSoconst 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) => {+ const materialize = async (relPath: string, directory: string, signal: AbortSignal,+ fresh?: { path: string; size: number }): Promise<{ path: string; size: number }> => {if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');- const cached = await source.cached?.(root, relPath).catch(() => null);+ const cached = fresh || updateApplied ? null : 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);+ const file = fresh ?? hit ?? await refresh(relPath, signal);if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');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(file.path, dest, file.size);- if ((await fs.stat(materialized)).size !== file.size) throw new Error('PREVIEW_CHANGED');+ const copied = await source.materialize(file.path, dest, file.size);+ if ((await fs.stat(copied)).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 assetPath = copied;let assetSize = stat.size;+ let cachedHtml: Buffer | undefined;if (/\.html?$/i.test(relPath)) {- const original = await fs.readFile(materialized);+ const original = await fs.readFile(copied);let html: string | undefined;try {html = new TextDecoder('utf-8', { fatal: true }).decode(original);@@ -202,7 +208,13 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSo!html.includes('\0') &&[...(charsets ?? [])].every((match) => /^utf-?8$/i.test(match[1]))) {- const guarded = withSnapshotHtmlCsp(html);+ const checkEntry = !!hit && relPath === entry;+ if (checkEntry) cachedHtml = original;+ // One same-origin request observes this opening's existing background check.+ // Fresh pages do not carry the script, so reload never starts a polling loop.+ const reload = checkEntry ? `<script>(()=>{const page=location.pathname;addEventListener('load',()=>{fetch(${JSON.stringify(updatePath)},{cache:'no-store'}).then(r=>r.ok?r.json():false).then(changed=>{if(changed&&location.pathname===page)location.reload();}).catch(()=>{});},{once:true});})();</script>` : '';+ const guarded = withSnapshotHtmlCsp(html.charCodeAt(0) === 0xfeff+ ? `\uFEFF${reload}${html.slice(1)}` : reload + html);await fs.writeFile(dest, guarded, { encoding: 'utf8', mode: 0o600 });assetPath = dest;assetSize = Buffer.byteLength(guarded);@@ -210,15 +222,22 @@ 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(() => {}, () => {});+ const fetched = refresh(relPath, controller.signal);+ if (cachedHtml) {+ const previous = cachedHtml;+ entryUpdate = fetched.then(async (next) => {+ if (!current() || previous.equals(await fs.readFile(next.path))) return null;+ const directory = await fs.mkdtemp(path.join(staging, 'updated-'));+ return materialize(relPath, directory, controller.signal, next);+ }).catch(() => null);+ }+ // An offline refresh must never invalidate the readable copy.+ const update = (entryUpdate && relPath === entry ? entryUpdate : fetched).then(() => {}, () => {});pending.add(update);void update.finally(() => pending.delete(update));}return { path: assetPath, size: assetSize };};- const token = randomBytes(24).toString('hex');const cookieName = `cindy_preview_${token}`;let origin = '';server = createServer((req, res) => {@@ -261,6 +280,24 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSoreturn deny(403);}}+ if (url.pathname === updatePath) {+ if (req.method !== 'GET') return deny(405);+ void Promise.resolve(entryUpdate).then((replacement) => {+ if (res.destroyed) return;+ if (!current()) return deny(410);+ const changed = !!replacement && !updateApplied;+ if (changed) {+ // Already displayed resources remain usable; the reloaded document gets+ // fresh companions instead of inheriting the previous snapshot's files.+ updateApplied = true;+ materialized.clear();+ materialized.set(entry, replacement!);+ }+ res.setHeader('Content-Type', 'application/json');+ res.end(JSON.stringify(changed));+ });+ return;+ }let pathname: string;try {pathname = decodeURIComponent(url.pathname);@@ -275,12 +312,13 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSores.once('close', () => requestController.abort());const signal = AbortSignal.any([controller.signal, requestController.signal]);const work = queue('preview', async () => {+ const startedAfterUpdate = updateApplied;let asset = materialized.get(relPath);if (!asset) {const directory = await fs.mkdtemp(path.join(staging, 'request-'));try {asset = await materialize(relPath, directory, signal);- materialized.set(relPath, asset);+ if (startedAfterUpdate === updateApplied) materialized.set(relPath, asset);} catch (error) {await fs.rm(directory, { recursive: true, force: true });throw error;diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsxindex d01f62d867..11dbbfbfb4 100644--- a/apps/mobile/app/files/preview/[sessionId].tsx+++ b/apps/mobile/app/files/preview/[sessionId].tsx@@ -490,10 +490,10 @@ function RemoteFilePreviewContent() {}, [session?.remoteHostId, sessionId, workdir]);const prepareHtmlPreview = useCallback<PrepareMobileHtmlPreview>(- (absPath, signal, onProgress) => prepareMobileHtmlPreview(absPath, {+ (absPath, signal, onProgress, preferCache) => prepareMobileHtmlPreview(absPath, {maker, deviceId, openLink, presignGet, ssh: sshMediaContext,deleteOssObject: deleteResourceOssObject,- }, signal, onProgress),+ }, signal, onProgress, preferCache),[deleteResourceOssObject, deviceId, maker, openLink, presignGet, sshMediaContext],);@@ -1338,11 +1338,9 @@ function TextPreviewPage({<Text style={styles.hintText}>{htmlErrorMessage}</Text><MainWindowActionButton action={{ label: t('files.preview.htmlReload'), onPress: htmlSnapshot.retry }} /></View>- ) : !htmlSnapshot.preview || !htmlSnapshot.foreground ? (- // 取件期间不先渲染破图再热替换 —— 那会让 WebView 重载、页面闪一下。- <HtmlPreviewLoading progress={htmlSnapshot.progress} />) : (- // 只有完整下载并加固过的目录快照才能进入 WebView。+ // Measure the viewport while preparing; the reader mounts WebKit only once+ // the guarded snapshot is ready and keeps one loading overlay throughout.<HtmlSnapshotReader preview={htmlSnapshot.preview} onError={() => setHtmlLoadError(true)}loading={<HtmlPreviewLoading progress={htmlSnapshot.progress} />}webViewRef={browserRef}diff --git a/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts b/apps/mobile/src/__tests__/filePreviewPagerWiring.test.tsindex a4efc8ad0d..ae659bcba6 100644--- a/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts+++ b/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts@@ -237,12 +237,15 @@ describe('HTML 生成物的渲染态接线', () => {expect(source).toContain('testID="filePreview.htmlError"');expect(source).toContain("t('files.preview.htmlSnapshotTooLarge')");expect(source).toContain('onPress: htmlSnapshot.retry');- expect(source).toContain('!htmlSnapshot.preview || !htmlSnapshot.foreground');+ // The viewport now mounts during preparation; executable content remains gated+ // inside the reader until a current, guarded snapshot exists.+ expect(readSource('src/session/HtmlFileReader.tsx')).toContain('{preview ? <WebView');+ expect(readSource('src/session/useHtmlSnapshot.ts')).toContain('const current = enabled && foreground');});it('downloads stop on source mode, invisibility, background, and source identity changes', () => {const hook = readSource('src/session/useHtmlSnapshot.ts');- expect(hook).toContain('if (!enabled || !foreground) return');+ expect(hook).toContain('if (!enabled || !foreground) {');expect(hook).toContain('controller.abort()');expect(hook).toContain('preview?.close()');expect(hook).toContain('[absPath, enabled, foreground, prepare, epoch]');diff --git a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsxindex e49502d344..56dd9ced94 100644--- a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx+++ b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx@@ -21,13 +21,17 @@ const state = vi.hoisted(() => ({goBack: vi.fn(),goForward: vi.fn(),inject: vi.fn(),+ appStateListeners: new Set<(value: string) => void>(),}));vi.mock('react-native', () => ({Platform: { OS: 'ios' },View: ({ children }: { children: unknown }) => children,ActivityIndicator: () => null,StyleSheet: { create: (value: unknown) => value },- AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },+ AppState: { currentState: 'active', addEventListener: (_event: string, listener: (value: string) => void) => {+ state.appStateListeners.add(listener);+ return { remove() { state.appStateListeners.delete(listener); } };+ } },}));vi.mock('@/theme', () => ({ useTheme: () => ({ colors: { surfaceElevated: '#FFFFFC' } }) }));vi.mock('@/components/AppText', () => ({ Text: ({ children }: { children: unknown }) => children }));@@ -66,6 +70,7 @@ afterEach(() => {state.unregisterInvoke.mockClear(); state.unregisterUpload.mockClear(); state.unregisterReset.mockClear();state.goBack.mockClear(); state.goForward.mockClear();state.inject.mockClear();+ vi.useRealTimers();});it('installs geometry on each document and ignores scroll/load events from a disposed reader', () => {@@ -177,6 +182,55 @@ 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);+// Unit regression: cached preparation and WebView loading used to mount two separate+// loading views. Keep one delayed indicator across both phases, with no flash on a fast open.+it('keeps one loading lifetime from preparation through the first document paint', () => {+ vi.useFakeTimers();+ const container = document.createElement('div');+ root = createRoot(container);+ const preview: MobileHtmlPreview = { url: 'http://127.0.0.1:1234/a/', documents: ['/index.html'], close: async () => {} };+ const props = { onError() {}, loading: createElement(HtmlPreviewLoading) };+ act(() => root!.render(createElement(HtmlSnapshotReader, props)));+ expect(state.mounts).toBe(0);+ expect(container.textContent).toBe('');+ act(() => vi.advanceTimersByTime(150));+ act(() => root!.render(createElement(HtmlSnapshotReader, { ...props, preview })));+ expect(state.mounts).toBe(1);+ expect(container.textContent).toBe('');+ act(() => vi.advanceTimersByTime(50));+ expect(container.textContent).toContain('files.preview.fetchingHtmlResources');+ act(() => state.props.onLoadEnd());+ expect(container.textContent).toBe('');+ expect(hidden()).toBe(false);+});++// Unit regression: a duplicate foreground event must not discard a readable page.+// Actual background/foreground transitions must still release and recreate the native server.+it('keeps the page on duplicate active events and rebuilds only after suspension', async () => {+ root = createRoot(document.createElement('div'));+ const close = vi.fn().mockResolvedValue(undefined);+ const preview: MobileHtmlPreview = { url: 'http://127.0.0.1:1234/a/', documents: [], close };+ const prepare = vi.fn().mockImplementation(async () => ({ ...preview }));+ let snapshot!: ReturnType<typeof useHtmlSnapshot>;+ function Harness() { snapshot = useHtmlSnapshot('/a.html', true, prepare); return null; }+ await act(async () => root!.render(createElement(Harness)));+ await act(async () => state.appStateListeners.forEach(listener => listener('active')));+ expect(snapshot.preview).toEqual(preview);+ expect(prepare).toHaveBeenCalledOnce();+ expect(close).not.toHaveBeenCalled();+ expect(prepare.mock.lastCall?.[3]).toBe(true);+ await act(async () => snapshot.retry());+ expect(snapshot.preview).toEqual(preview);+ expect(prepare.mock.lastCall?.[3]).toBe(false);+ await act(async () => state.appStateListeners.forEach(listener => listener('background')));+ expect(snapshot.preview).toBeUndefined();+ expect(close).toHaveBeenCalledTimes(2);+ await act(async () => state.appStateListeners.forEach(listener => listener('active')));+ expect(snapshot.preview).toEqual(preview);+ expect(prepare).toHaveBeenCalledTimes(3);+ expect(prepare.mock.lastCall?.[3]).toBe(true);+});+it('hides each snapshot until its first document loads, then reveals it', () => {const container = document.createElement('div');root = createRoot(container);@@ -235,3 +289,38 @@ it('ignores late failure events from a replaced preview', () => {act(() => state.props.onError({ nativeEvent: { code: -1001 } }));expect(onError).toHaveBeenCalledOnce();});++// Unit: the real hook must retain usable content during automatic replacement and+// ignore late work after leaving. These timings were absent from manual-retry coverage.+it.each(['changed', 'same', 'failed', 'left'] as const)('replaces a stale snapshot at most once and preserves its owner (%s)', async (outcome) => {+ root = createRoot(document.createElement('div'));+ let finishCheck!: (preview: MobileHtmlPreview | null) => void;+ let failCheck!: (error: Error) => void;+ const initial: MobileHtmlPreview = {+ url: 'http://127.0.0.1:1234/old', documents: [], close: vi.fn().mockResolvedValue(undefined),+ updated: new Promise((resolve, reject) => { finishCheck = resolve; failCheck = reject; }),+ };+ const next: MobileHtmlPreview = {+ url: 'http://127.0.0.1:4321/new', documents: [], close: vi.fn().mockResolvedValue(undefined),+ updated: Promise.resolve(null),+ };+ const prepare = vi.fn().mockResolvedValue(initial);+ let snapshot!: ReturnType<typeof useHtmlSnapshot>;+ function Harness({ enabled = true }: { enabled?: boolean }) {+ snapshot = useHtmlSnapshot('/a.html', enabled, prepare); return null;+ }+ await act(async () => root!.render(createElement(Harness)));+ expect(snapshot.preview).toBe(initial);+ expect(initial.close).not.toHaveBeenCalled();+ if (outcome === 'left') await act(async () => root!.render(createElement(Harness, { enabled: false })));+ await act(async () => {+ if (outcome === 'failed') failCheck(new Error('offline'));+ else finishCheck(outcome === 'same' ? null : next);+ });+ expect(prepare).toHaveBeenCalledOnce();+ expect(snapshot.preview).toBe(outcome === 'changed' ? next : outcome === 'left' ? undefined : initial);+ expect(snapshot.error).toBeUndefined();+ if (outcome === 'left') expect(next.close).toHaveBeenCalledOnce();+ await act(async () => root!.render(createElement(Harness, { enabled: false })));+ expect(initial.close).toHaveBeenCalledOnce();+});diff --git a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts b/apps/mobile/src/__tests__/mobileHtmlPreview.test.tsindex 04d5b5a3d6..81a1553ac4 100644--- a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts+++ b/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts@@ -27,7 +27,7 @@ vi.mock("../../modules/cindy-html-preview/src/CindyHtmlPreviewModule", () => ({get resolveRequest() { return mocks.demand ? mocks.resolveRequest : undefined; },addListener: (event: string, listener: (event: { token: string; id: string; path?: string }) => void) => {mocks.listeners.set(event, listener);- return { remove: () => mocks.listeners.delete(event) };+ return { remove: () => { if (mocks.listeners.get(event) === listener) mocks.listeners.delete(event); } };},},}));@@ -171,6 +171,26 @@ function previewCache() {}describe('persistent HTML preview cache', () => {+ // Unit regression: explicit reload previously restored stale bytes again. Both+ // native APIs must display fresh bytes on this attempt and preserve them for offline reopening.+ it.each([false, true])('bypasses cached bytes on explicit reload (onDemand=%s)', async (demand) => {+ mocks.demand = demand;+ const { deps, listDir, caps } = setup();+ listDir.mockResolvedValue([entry('index.html')]);+ const { saved } = previewCache();+ const stale = new TextEncoder().encode('<p>old</p>');+ saved.set('index.html', stale);+ const preview = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal, undefined, false);+ expect(new TextDecoder().decode(mocks.contents.get('file:///cache/html-previews/' + '01'.repeat(24) + '/0'))).toContain(html);+ expect(saved.get('index.html')).toEqual(bytes);+ await preview.close();+ mocks.remote.mockRejectedValue(new Error('offline'));+ caps.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(html);+ await reopened.close();+ });+// Unit regression: old transfer-cache HTML can be invalid UTF-8 even after the// remote document is repaired. Exercise both native preparation entry points.it.each([false, true])('replaces undecodable cached entries and reopens offline (onDemand=%s)', async (demand) => {@@ -245,24 +265,64 @@ describe('persistent HTML preview cache', () => {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();+ it.each([false, true])('reports changed entry bytes after background refresh without mutating the visible copy (onDemand=%s)', async (demand) => {+ mocks.demand = demand;+ const { deps, listDir } = setup();const { cache, saved } = previewCache();saved.set('index.html', bytes);const updated = new TextEncoder().encode('<p>Updated page</p>');+ listDir.mockResolvedValue([{ ...entry('index.html'), size: updated.length }]);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());+ const replacement = await preview.updated;+ expect(replacement).toBeTruthy();+ expect(replacement?.updated).toBeUndefined();+ expect(mocks.remote).toHaveBeenCalledOnce();+ 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();+ expect(new TextDecoder().decode(mocks.contents.get('file:///cache/html-previews/' + '02'.repeat(24) + '/0'))).toContain('Updated page');+ // The visible replacement owns the whole visit, including its old server.+ await replacement!.close();+ expect(mocks.contents.size).toBe(0);+ expect(mocks.stop).toHaveBeenCalledTimes(2);+ expect(mocks.listeners.size).toBe(0);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');+ expect(new TextDecoder().decode(mocks.contents.get('file:///cache/html-previews/' + '03'.repeat(24) + '/0'))).toContain('Updated page');await reopened.close();});+ it.each([false, true])('does not request a reload for identical HTML (onDemand=%s)', async (demand) => {+ mocks.demand = demand;+ const { deps, listDir } = setup();+ listDir.mockResolvedValue([entry('index.html')]);+ previewCache().saved.set('index.html', bytes);+ const preview = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);+ expect(await preview.updated).toBeNull();+ await preview.close();+ });++ it.each([false, true])('discards a changed HTML refresh that finishes after leaving (onDemand=%s)', async (demand) => {+ mocks.demand = demand;+ const { deps, listDir } = setup();+ previewCache().saved.set('index.html', bytes);+ const fresh = '<p>late</p>';+ listDir.mockResolvedValue([{ ...entry('index.html'), size: fresh.length }]);+ let finish!: () => void;+ mocks.remote.mockReturnValue(new Promise(resolve => {+ finish = () => resolve({ url: '', inlineBase64: btoa(fresh), size: fresh.length });+ }));+ const controller = new AbortController();+ const preview = await prepareMobileHtmlPreview('/site/index.html', deps, controller.signal);+ controller.abort();+ finish();+ expect(await preview.updated).toBeNull();+ await preview.close();+ expect(mocks.contents.size).toBe(0);+ expect(mocks.listeners.size).toBe(0);+ });+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();diff --git a/apps/mobile/src/session/HtmlFileReader.tsx b/apps/mobile/src/session/HtmlFileReader.tsxindex 6b5b728f1f..0903cbf8d9 100644--- a/apps/mobile/src/session/HtmlFileReader.tsx+++ b/apps/mobile/src/session/HtmlFileReader.tsx@@ -49,7 +49,7 @@ 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, loading }: {- preview: MobileHtmlPreview;+ preview?: MobileHtmlPreview;onError(): void;loading?: ReactNode;webViewRef?: RefObject<WebView | null>;@@ -57,7 +57,8 @@ export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInsetonNavigationStateChange?(preview: MobileHtmlPreview, state: WebViewNavigation): void;}) {const { colors } = useTheme();- const source = useMemo(() => ({ uri: preview.url }), [preview.url]);+ const url = preview?.url;+ const source = useMemo(() => url ? { uri: url } : undefined, [url]);const localRef = useRef<WebView>(null);const readerRef = webViewRef ?? localRef;const { viewRef, measure, script, viewportStyle, obscuredContentInsets } = useHtmlBrowserViewport({@@ -67,7 +68,7 @@ export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInsetuseEffect(() => { if (script) readerRef.current?.injectJavaScript(script); }, [script, readerRef, preview]);// WKWebView paints white until the first document load ends; keep the themed page behind it until then.const [paintedPreview, setPaintedPreview] = useState<MobileHtmlPreview | null>(null);- const currentPreview = useRef<MobileHtmlPreview | null>(preview);+ const currentPreview = useRef<MobileHtmlPreview | null | undefined>(preview);useEffect(() => {currentPreview.current = preview;return () => { currentPreview.current = null; };@@ -79,7 +80,9 @@ export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInsetmobileDebugLog('warn', 'files', event, { ms: Date.now() - mountedAt, ...detail });onError();};- return <View ref={viewRef} onLayout={measure} collapsable={false} style={[styles.fill, viewportStyle]}><View style={styles.viewport}><WebView+ // Keep the measured viewport and loading overlay mounted while preparing the local+ // snapshot. Cached opens should not restart a spinner or first measure after WebKit loads.+ return <View ref={viewRef} onLayout={measure} collapsable={false} style={[styles.fill, viewportStyle]}><View style={styles.viewport}>{preview ? <WebViewkey={preview.url}ref={readerRef}testID="filePreview.htmlRendered"@@ -124,7 +127,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]}- />{paintedPreview !== preview && loading ? <View style={StyleSheet.absoluteFill} pointerEvents="none">{loading}</View> : null}</View></View>;+ /> : null}{(!preview || paintedPreview !== preview) && loading ? <View key="loading" 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.tsxindex 30e6f7235b..0684b0165c 100644--- a/apps/mobile/src/session/HtmlPreviewLoading.tsx+++ b/apps/mobile/src/session/HtmlPreviewLoading.tsx@@ -1,3 +1,4 @@+import { useEffect, useState } from 'react';import { ActivityIndicator, StyleSheet, View } from 'react-native';import { useTranslation } from 'react-i18next';import { Text } from '@/components/AppText';@@ -11,6 +12,13 @@ import { formatTransferProgress } from './transferProgress';export function HtmlPreviewLoading({ progress }: { progress?: HtmlPreviewProgress }) {const { t } = useTranslation();const { colors } = useTheme();+ const [waiting, setWaiting] = useState(false);+ useEffect(() => {+ // Cached files normally finish before this; real transfers show their progress immediately.+ const timer = setTimeout(() => setWaiting(true), 200);+ return () => clearTimeout(timer);+ }, []);+ if (!waiting && !progress) return null;return <View style={styles.container} testID="filePreview.htmlResourceLoading"><ActivityIndicator color={colors.textTertiary} /><Text style={[styles.hint, { color: colors.textSecondary }]}>{t('files.preview.fetchingHtmlResources')}</Text>diff --git a/apps/mobile/src/session/mobileHtmlPreview.ts b/apps/mobile/src/session/mobileHtmlPreview.tsindex 420084ac40..845e16fb30 100644--- a/apps/mobile/src/session/mobileHtmlPreview.ts+++ b/apps/mobile/src/session/mobileHtmlPreview.ts@@ -20,11 +20,13 @@ export interface MobileHtmlPreview {url: string;documents: string[];onDemand?: boolean;+ /** One background check of the entry HTML; failures leave the current page intact. */+ updated?: Promise<MobileHtmlPreview | null>;close(): Promise<void>;}export interface HtmlPreviewProgress extends TransferProgress { name: string }type ProgressListener = (progress: HtmlPreviewProgress) => void;-export type PrepareMobileHtmlPreview = (absPath: string, signal: AbortSignal, onProgress?: ProgressListener) => Promise<MobileHtmlPreview>;+export type PrepareMobileHtmlPreview = (absPath: string, signal: AbortSignal, onProgress?: ProgressListener, preferCache?: boolean) => Promise<MobileHtmlPreview>;type HtmlPreviewDeps = RemoteAbsFileFetchDeps & {maker: MobileMakerTransport;@@ -95,7 +97,7 @@ async function materializeResource(deps: HtmlPreviewDeps, root: string, relativeif (html !== undefined) {destination.write(withSnapshotHtmlCsp(html));}- return { filename, mime, bytes: media.size,+ return { filename, mime, bytes: media.size, html,route: media.inlineBase64 !== undefined ? 'inline' : media.url.startsWith('file://') ? 'direct' : 'upload' };} finally { if (media.url.startsWith('file://')) releasePeerMedia(media.url); }} catch (error) {@@ -128,16 +130,18 @@ function sweepInterruptedSnapshots() {/** Source identity stays in the transport; no device credentials enter the snapshot. */export async function prepareMobileHtmlPreview(absPath: string, deps: HtmlPreviewDeps,- signal: AbortSignal, onProgress?: ProgressListener): Promise<MobileHtmlPreview> {+ signal: AbortSignal, onProgress?: ProgressListener, preferCache = true): 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;+ let refreshed: MobileHtmlPreview | null | undefined;const abort = () => {lifetime.abort();void active?.close().catch(() => {});+ void refreshed?.close().catch(() => {});};signal.addEventListener('abort', abort, { once: true });const unsubscribe = subscribeMobileAuthOwner(() => { if (cache && !cache.current()) abort(); });@@ -153,16 +157,25 @@ export async function prepareMobileHtmlPreview(absPath: string, deps: HtmlPrevie});try {const preview = native.startOnDemand && native.resolveRequest- ? await prepareOnDemand(absPath, deps, lifetime.signal, onProgress, cache)- : await prepareLegacy(absPath, deps, lifetime.signal, onProgress, cache);+ ? await prepareOnDemand(absPath, deps, lifetime.signal, onProgress, cache, preferCache)+ : await prepareLegacy(absPath, deps, lifetime.signal, onProgress, cache, preferCache);active = preview;if (lifetime.signal.aborted) { await preview.close(); throw new Error('PREVIEW_CANCELLED'); }- return { ...preview, close: async () => { dispose(); await preview.close(); } };+ const close = async () => { dispose(); await preview.close(); await refreshed?.close(); };+ const updated = preview.updated?.then(async (next) => {+ refreshed = next;+ if (lifetime.signal.aborted) { await next?.close(); return null; }+ return next ? { ...next, close } : null;+ });+ // The original visit owns both immutable copies. Keeping the old server until+ // exit avoids killing in-flight WebKit reads while React commits its replacement.+ return { ...preview, updated, close };} catch (error) { dispose(); throw error; }}async function prepareLegacy(absPath: string, deps: HtmlPreviewDeps, signal: AbortSignal,- onProgress?: ProgressListener, cache?: MobileHtmlPreviewCache, preferCache = true): Promise<MobileHtmlPreview> {+ onProgress?: ProgressListener, cache?: MobileHtmlPreviewCache, preferCache = true,+ onEntryHtml?: (html: string) => void): Promise<MobileHtmlPreview> {const server = native!;assertHtmlSnapshotActive(signal);const { root, entry } = htmlSnapshotLocation(absPath);@@ -255,6 +268,7 @@ async function prepareLegacy(absPath: string, deps: HtmlPreviewDeps, signal: Aboif (text !== undefined) {// Reject invalid UTF-8 instead of publishing a corrupted page. No source text is truncated.destination.write(withSnapshotHtmlCsp(text));+ if (file.relPath === entry) onEntryHtml?.(text);}manifest.push([file.relPath, String(index), mime]);} finally { for (const key of uploaded) deps.deleteOssObject(key); }@@ -275,11 +289,11 @@ async function restoreCachedResource(cache: MobileHtmlPreviewCache, relative: stconst size = await cache?.copy(relative, destination, maxBytes);if (size != null) {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());+ const html = mime === 'text/html' ? new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes()) : undefined;+ if (html !== undefined) {destination.write(withSnapshotHtmlCsp(html));}- return { size, mime };+ return { size, mime, html };}return null;} catch { /* Old transfer copies may predate HTML validation. Fetch a fresh copy. */ }@@ -310,6 +324,7 @@ async function restoreLegacy(absPath: string, deps: HtmlPreviewDeps, signal: Abotry {const manifest: string[][] = [];const restored = [];+ let entryHtml: string | undefined;let remaining = HTML_SNAPSHOT_MAX_BYTES;for (const [index, file] of files.entries()) {const destination = new File(dir, String(index));@@ -320,6 +335,7 @@ async function restoreLegacy(absPath: string, deps: HtmlPreviewDeps, signal: Abocontinue;}const { size, mime } = cached;+ if (file.relPath === entry) entryHtml = cached.html;manifest.push([file.relPath, String(index), mime]);restored.push({ ...file, size });remaining -= size;@@ -327,16 +343,21 @@ async function restoreLegacy(absPath: string, deps: HtmlPreviewDeps, signal: AboassertHtmlSnapshotActive(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 };+ let freshHtml: string | undefined;+ const updated = prepareLegacy(absPath, deps, refresh.signal, undefined, cache, false, (html) => { freshHtml = html; })+ .then(async (fresh) => {+ if (!refresh.signal.aborted && freshHtml !== undefined && freshHtml !== entryHtml) return fresh;+ await fresh.close();+ return null;+ }).catch(() => null);+ return { url, documents: snapshotDocumentPaths(restored), updated, 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: HtmlPreviewDeps,- signal: AbortSignal, onProgress?: ProgressListener, cache?: MobileHtmlPreviewCache): Promise<MobileHtmlPreview> {+ signal: AbortSignal, onProgress?: ProgressListener, cache?: MobileHtmlPreviewCache, preferCache = true,+ preparedEntry?: { file: File; mime: string }): Promise<MobileHtmlPreview> {const server = native!;assertHtmlSnapshotActive(signal);const { root, entry } = htmlSnapshotLocation(absPath);@@ -352,20 +373,28 @@ async function prepareOnDemand(absPath: string, deps: HtmlPreviewDeps,const requests = new Map<string, AbortController>();const pending = new Set<Promise<unknown>>();const materialized = new Map<string, { filename: string; mime: string }>();+ let entryUpdated: Promise<MobileHtmlPreview | null> | undefined;const queue = createFileReadQueue();const loadResource = async (relative: string, filename: string, requestSignal: AbortSignal) => {const destination = new File(dir, filename);- const cached = await restoreCachedResource(cache, relative, destination);+ const cached = preferCache ? await restoreCachedResource(cache, relative, destination) : null;assertHtmlSnapshotActive(requestSignal);if (cached) {const { size, mime } = cached;const updatedName = `${filename}-refresh`;const update = materializeResource(deps, root, relative, dir, updatedName, signal, undefined, cache)- .then(() => {}, () => {}).finally(() => {+ .then((fresh) => {+ if (relative !== entry || signal.aborted || fresh.html === undefined || fresh.html === cached.html) return null;+ // Reuse the bytes just downloaded; companion resources in the replacement+ // use fresh reads instead of inheriting stale CSS/JS from the old document.+ return prepareOnDemand(absPath, deps, signal, undefined, cache, false,+ { file: new File(dir, updatedName), mime: fresh.mime });+ }).catch(() => null).finally(() => {try { new File(dir, updatedName).delete(); } catch {}pending.delete(update);});pending.add(update);+ if (relative === entry) entryUpdated = update;return { filename, mime, bytes: size, route: 'cache' };}return materializeResource(deps, root, relative, dir, filename, requestSignal, onProgress, cache);@@ -454,7 +483,12 @@ async function prepareOnDemand(absPath: string, deps: HtmlPreviewDeps,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);+ const filename = String(sequence++);+ const preparation = preparedEntry ? (async () => {+ await preparedEntry.file.copy(new File(dir, filename));+ assertHtmlSnapshotActive(signal);+ return { filename, mime: preparedEntry.mime };+ })() : loadResource(entry, filename, signal);pending.add(preparation);try { materialized.set(entry, await preparation); } finally { pending.delete(preparation); }assertHtmlSnapshotActive(signal);@@ -463,6 +497,6 @@ async function prepareOnDemand(absPath: string, deps: HtmlPreviewDeps,await server.stop(token);throw new Error('PREVIEW_CANCELLED');}- return { url, documents: ['/' + entry.split('/').map(encodeURIComponent).join('/')], onDemand: true, close };+ return { url, documents: ['/' + entry.split('/').map(encodeURIComponent).join('/')], onDemand: true, updated: entryUpdated, close };} catch (error) { await close(); throw error; }}diff --git a/apps/mobile/src/session/useHtmlSnapshot.ts b/apps/mobile/src/session/useHtmlSnapshot.tsindex 67bfbddcbb..8a29a4d756 100644--- a/apps/mobile/src/session/useHtmlSnapshot.ts+++ b/apps/mobile/src/session/useHtmlSnapshot.ts@@ -15,30 +15,41 @@ export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: PrepuseEffect(() => {const subscription = AppState.addEventListener('change', (state) => {setForeground(state === 'active');- if (state === 'active') setEpoch((value) => value + 1);});return () => subscription.remove();}, []);useEffect(() => {setResult({});- if (!enabled || !foreground) return;+ if (!enabled || !foreground) {+ // A manual reload bypasses stale bytes only for this visit. Returning later+ // must still open the last available cache without waiting for a connection.+ setEpoch(0);+ return;+ }const controller = new AbortController();const startedAt = Date.now();let preview: MobileHtmlPreview | undefined;void prepare(absPath, controller.signal, (progress) => {if (!controller.signal.aborted) setResult((previous) => ({ ...previous, progress, path: absPath, prepare, epoch }));- }).then((value) => {+ }, epoch === 0).then(async (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((previous) => ({ ...previous, preview: value, path: absPath, prepare, epoch }));+ if (controller.signal.aborted) { void value.close().catch(() => {}); return; }+ setResult((previous) => ({ ...previous, preview: value, path: absPath, prepare, epoch }));+ const fresh = await value.updated;+ if (fresh) {+ // Reuse the completed background snapshot. No second remote download and+ // no recursive refresh: this is one check for this opening only.+ if (controller.signal.aborted) void fresh.close().catch(() => {});+ else setResult({ preview: fresh, 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),});- if (!controller.signal.aborted) setResult({ error, path: absPath, prepare, epoch });+ if (!controller.signal.aborted) setResult((previous) => previous.preview ? previous : { error, path: absPath, prepare, epoch });});return () => {controller.abort();diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex e19621b1e0..e01aa13360 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -923,9 +923,15 @@ URL,之后复用持久字节。本次不新增持久 URL 索引,冷启动离Desktop 完整文件与远程 HTML 预览复用现有磁盘副本,后台检查变化;HTML 的大小/mtime仅用于快照展示和传输上限,不作为后台跳过读取的版本判据。复验绕过外层 size/mtime 命中,device 仍可复用主机确认版本的字节,SSH 重新读取;新版原子保存前保留旧副本。HTML 直接通过-现有磁盘索引定位副本,不再另维护进程内元数据索引和刷新集合。后台失败保留旧副本,更新完成后-后续打开使用新版;不强制重载正在操作的 HTML、图片或 PDF。预览持有自己的副本,关闭时仅释放这份副本,-不会删除可复用的源缓存。零字节 HTML 配套资源也可按版本缓存。+现有磁盘索引定位副本,不再另维护进程内元数据索引和刷新集合。两端 HTML 先显示缓存,再在+本次打开的后台读取中比较入口 HTML 内容;不同且新版快照准备完成时自动切换,相同或失败不重载。+Mobile 直接复用后台准备好的快照;Desktop 缓存入口通过现有鉴权的本地预览服务读取一次更新结果,+确认变化后重载。没有持续监听或轮询,检查完成后的修改需从 Cindy 重新打开;手机也可手动刷新,+跳过旧副本并在成功后更新缓存。只改配套资源不触发入口重载。图片、PDF 保持后台更新供后续打开使用。+预览持有自己的副本,关闭时释放本次打开的新旧快照,不删除可复用的源缓存。+零字节 HTML 配套资源也可按版本缓存。+回归覆盖见 [Mobile 快照测试](../../apps/mobile/src/__tests__/mobileHtmlPreview.test.ts) 与+[Desktop 预览测试](../../apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts)。Mobile 分享及 HTML 资源复制在完成、失败、取消后释放传输暂存;独立消费者副本继续由原持有者管理。音视频播放继续用保留的流式地址,不为了缓存而预先下载整份媒体;完整下载仍按上述规则。不可变聊天图片与目录维持已有专用缓存;Mobile 限量文本预览先显示缓存(包括绝对路径),