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。

merge(main): 合并 HTML 弱网预览并收敛缓存刷新

Dash9faaf17594a2
diff --cc apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
index 3b751d2b49,5fc433a134..6574ab9db8
--- 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
@@@ -4,6 -4,6 +4,7 @@@ import os from 'node:os'
import path from 'node:path';
import { EventEmitter } from 'node:events';
import { FileServiceRpcError } from '@cindy/remote-file-service/client';
++import { sharedTaskHostPeer } from '@cindy/device-link';
const mocks = vi.hoisted(() => ({
handle: vi.fn(),
trusted: vi.fn(),
@@@ -61,13 -61,13 +62,16 @@@ it('rejects an untrusted guest before a
await expect(mocks.handle.mock.calls[0][1]({}, args)).rejects.toThrow('PERMISSION_DENIED');
expect(stat).not.toHaveBeenCalled();
});
--it('returns an actionable typed error when the remote cannot read files', async () => {
++it.each(['remote', sharedTaskHostPeer('shared', 'host')])('requires a remote read for %s even if a guest has old cached bytes', async (deviceId) => {
const stat = vi.fn().mockRejectedValue(new Error('METHOD_NOT_FOUND'));
-- registerHtmlPreviewIpc({ stat, read: vi.fn() });
-- await expect(mocks.handle.mock.calls[0][1]({}, args)).rejects.toMatchObject({
++ const cached = vi.fn(async () => deviceId === 'remote' ? null : '/stale-guest.html');
++ const source = { ...args, origin: { kind: 'device', deviceId } };
++ registerHtmlPreviewIpc({ stat, read: vi.fn(), cached });
++ await expect(mocks.handle.mock.calls[0][1]({}, source)).rejects.toMatchObject({
code: 'HTML_PREVIEW_UNSUPPORTED',
});
-- expect(stat).toHaveBeenCalledExactlyOnceWith(args, '/remote/preview', 'index.html', expect.any(AbortSignal));
++ expect(stat).toHaveBeenCalledExactlyOnceWith(source, '/remote/preview', 'index.html', expect.any(AbortSignal));
++ if (deviceId !== 'remote') expect(cached).not.toHaveBeenCalled();
});
// Unit tier, fake clock: the real metadata reader must survive transient
@@@ -215,63 -215,6 +219,65 @@@ it('opens a preview before downloading
await expect(mocks.handle.mock.calls[0][1]({}, args)).resolves.toMatchObject({ ok: true });
expect(read).not.toHaveBeenCalled();
});
+it.each([1, 2])('serves cached HTML while stat is blocked, then refreshes with mtime %s', async (mtimeMs) => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-swr-test-'));
+ let reply!: (value: any) => void;
+ const metadata = { relPath: 'index.html', type: 'file' as const, size: 3, mtimeMs: 1 };
+ const stat = vi.fn(async () => metadata);
- const read = vi.fn(async () => path.join(dir, 'old.html'));
++ let cached: string | null = null;
++ const read = vi.fn(async () => { cached = path.join(dir, 'old.html'); return cached; });
+ try {
+ await fs.writeFile(path.join(dir, 'old.html'), 'old');
+ await fs.writeFile(path.join(dir, 'new.html'), 'new');
- registerHtmlPreviewIpc({ stat, read });
++ registerHtmlPreviewIpc({ stat, read, cached: async () => cached });
+ const open = mocks.handle.mock.calls[0][1];
+ const first = await open({}, args);
+ expect(await (await readResource(first.url, '/index.html')).text()).toContain('old');
+ stat.mockImplementationOnce(() => new Promise(resolve => { reply = resolve; }));
+ const second = await open({}, args);
+ expect(await (await readResource(second.url, '/index.html')).text()).toContain('old');
+ expect(read).toHaveBeenCalledOnce();
- read.mockResolvedValueOnce(path.join(dir, 'new.html'));
++ read.mockImplementationOnce(async () => { cached = path.join(dir, 'new.html'); return cached; });
+ reply({ ...metadata, mtimeMs });
+ await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+ const third = await open({}, args);
+ expect(await (await readResource(third.url, '/index.html')).text()).toContain('new');
+ expect(await (await readResource(second.url, '/index.html')).text()).toContain('old');
+ } finally { await fs.rm(dir, { recursive: true, force: true }); }
+});
+// #6292 + #6288 integration, unit tier: previous cancellation cases only cover
+// uncached preparation. Cancel a cached preview during a stalled background stat;
+// its transport must abort and a later open must be able to revalidate again.
+it('releases a cancelled cached refresh so the next preview can revalidate', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-refresh-cancel-'));
+ const metadata = { relPath: 'index.html', type: 'file' as const, size: 3, mtimeMs: 1 };
+ const stat = vi.fn(async (_args, _root, _rel, _signal: AbortSignal) => metadata);
- const read = vi.fn(async () => path.join(dir, 'old.html'));
++ let cached: string | null = null;
++ const read = vi.fn(async () => { cached = path.join(dir, 'old.html'); return cached; });
+ try {
+ await fs.writeFile(path.join(dir, 'old.html'), 'old');
- registerHtmlPreviewIpc({ stat, read });
++ registerHtmlPreviewIpc({ stat, read, cached: async () => cached });
+ const open = mocks.handle.mock.calls[0][1];
+ const cancel = mocks.handle.mock.calls[1][1];
+ const first = await open({}, args);
+ expect(await (await readResource(first.url, '/index.html')).text()).toContain('old');
+ let refreshSignal!: AbortSignal;
+ stat.mockImplementationOnce((_args, _root, _rel, signal) => {
+ refreshSignal = signal;
+ return new Promise(() => {});
+ });
+ const sender = Object.assign(new EventEmitter(), { id: 20 });
+ const second = await open({ sender }, { ...args, requestId: 'cached-preview' });
+ expect(await (await readResource(second.url, '/index.html')).text()).toContain('old');
+ await cancel({ sender }, 'cached-preview');
+ expect(refreshSignal.aborted).toBe(true);
+ const callsBeforeReopen = stat.mock.calls.length;
+ const third = await open({}, args);
+ expect(await (await readResource(third.url, '/index.html')).text()).toContain('old');
+ expect(stat.mock.calls.length).toBeGreaterThan(callsBeforeReopen);
- expect(read).toHaveBeenCalledTimes(2);
++ await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+ } finally { await fs.rm(dir, { recursive: true, force: true }); }
+});
it('passes the captured owner guard through reference-free cache ingestion', async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-owner-test-'));
try {
diff --cc apps/desktop/src/main/file-browser/html-preview-ipc.ts
index 8a6e5cae78,984ae69099..a95c716ef1
--- a/apps/desktop/src/main/file-browser/html-preview-ipc.ts
+++ b/apps/desktop/src/main/file-browser/html-preview-ipc.ts
@@@ -77,11 -71,6 +73,7 @@@ export function registerHtmlPreviewIpc(
try {
previewLocation(args);
const scope = captureDataOwnerBroadcastScope();
- const ownerKey = scope.ownerScopeKey;
- const cacheable = !!ownerKey && !(args.origin.kind === 'device' && isSharedTaskPeer(args.origin.deviceId));
- if (cacheOwner !== ownerKey) { files.clear(); cacheOwner = ownerKey; }
- const keyOf = (root: string, rel: string) => JSON.stringify([ownerKey, args.origin, args.workdir, root, rel]);
- const selected = new Map<string, CachedFile>();
++ const cacheable = !!scope.ownerScopeKey && !(args.origin.kind === 'device' && isSharedTaskPeer(args.origin.deviceId));
const isCurrent = () =>
!shuttingDown &&
!request.controller.signal.aborted &&
@@@ -101,17 -90,13 +93,13 @@@
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) => {
++ cached: args.origin.kind === 'local' || !cacheable ? 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')
+ if (args.origin.kind !== 'local') {
- const key = keyOf(root, rel);
- const cached = cacheable ? files.get(key) : undefined;
- const stat = cached && await fs.stat(cached.path).catch(() => null);
- if (cached && stat?.isFile() && stat.size === cached.metadata.size) {
- selected.set(key, cached);
- return cached.metadata;
- }
- selected.delete(key);
- files.delete(key);
return readPreviewMetadata(
(attemptSignal) => remote.stat(args, root, rel, attemptSignal),
signal ?? request.controller.signal,
@@@ -124,14 -108,7 +112,9 @@@
return statEntry(root, rel);
},
read: async (root, entry, signal) => {
- if (args.origin.kind !== 'local') return remote.read(args, root, entry, signal);
+ if (args.origin.kind !== 'local') {
- const key = keyOf(root, entry.relPath);
- const cached = selected.get(key);
- if (cached) return cached.path;
- const file = await remote.read(args, root, entry, signal);
- if (cacheable && isCurrent() && !signal?.aborted) files.set(key, { metadata: entry, path: file });
- return file;
++ return remote.read(args, root, entry, signal);
+ }
const source = path.join(root, entry.relPath);
const [rootReal, real] = await Promise.all([fs.realpath(root), fs.realpath(source)]);
if (
diff --cc apps/mobile/app/files/preview/[sessionId].tsx
index 7c7fe9ff59,49cdc13165..69464a10aa
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@@ -1231,13 -1233,13 +1232,14 @@@ 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;
+ const unavailable = (value: TextPreviewState) => setState((previous) =>
+ previous.status === 'ready' ? previous : value);
void readTextFile(item.relPath)
.then((res: FileBrowserReadFileResult) => {
if (cancelled) return;
@@@ -1285,9 -1281,9 +1287,9 @@@
});
return () => {
cancelled = true;
- if (!settled) loadedRef.current = false;
+ 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),
diff --cc apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 99ffa2f13b,64c0608980..cf55e8eca9
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@@ -11,9 -10,8 +11,10 @@@ import
} from "@/device-link/mobileMakerTransport";
import type { RemoteInvoke } from "@/device-link/mobileMakerTransport";
import { installPeerFileDownload } from "@/device-link/peerFileRegistry";
+const fileCache = vi.hoisted(() => ({ readLatest: vi.fn(), readInline: vi.fn(), storeInline: vi.fn(), invalidate: vi.fn(), download: vi.fn() }));
+vi.mock('@/device-link/peerFileCache', () => ({ createPeerFileCache: async () => fileCache }));
import { isDirectPreviewableMediaUrl, resolveMobileRemoteMedia } from "@/session/remoteMedia";
+ import { fetchRemoteAbsFileOnce } from '@/session/remoteAbsFileFetch';
import {
setMobileAuthOwner,
__testing as authOwnerTesting,
@@@ -38,52 -36,6 +39,69 @@@ function harness()
}
describe("mobile maker transport", () => {
+ it('reads through an older shared host without sending unknown metadata-only fields', async () => {
+ const result = { ossKey: '', size: 3, mimeType: 'text/plain', inlineBase64: 'YWJj' };
+ const invoke = vi.fn(async (_device, _channel, [request]) => {
+ if ('metadataOnly' in request) throw new Error('PERMISSION_DENIED');
+ return result;
+ });
+ const maker = createMobileMakerTransport({ deviceId: sharedTaskHostPeer('shared', 'host'), invoke: invoke as RemoteInvoke });
+ expect(await maker.fetchRemoteMedia('xdt-file://open?path=/a.txt', { stream: false })).toEqual(result);
+ expect(await maker.fetchRemoteMedia('xdt-file://open?path=/a.txt', { stream: false })).toEqual(result);
+ expect(invoke).toHaveBeenCalledTimes(2);
+ });
+ it('opens a cached file without waiting for connection or host metadata, then refreshes in background', async () => {
+ setMobileAuthOwner('cache-first-owner');
+ const cached = { ossKey: '', size: 3, mimeType: 'application/pdf', version: 'a'.repeat(64), inlineBase64: 'YWJj' };
+ fileCache.readLatest.mockResolvedValueOnce(cached);
+ let connect!: () => void;
+ const beforeFetch = vi.fn(() => new Promise<void>(resolve => { connect = resolve; }));
+ const invoke = vi.fn(async () => ({ ...cached, inlineBase64: undefined, transferRequired: true }));
+ const maker = createMobileMakerTransport({ deviceId: 'cached-device', invoke: invoke as RemoteInvoke });
+ try {
+ expect(await maker.fetchRemoteMedia('xdt-file://open?path=/cached.pdf', { stream: false, beforeFetch })).toEqual(cached);
+ expect(invoke).not.toHaveBeenCalled();
+ expect(beforeFetch).toHaveBeenCalledOnce();
+ connect();
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledOnce());
+ } finally { authOwnerTesting.reset(); vi.clearAllMocks(); }
+ });
++ // #6292 + #6299, unit: HTML owns its visible cache. Its background fetch must
++ // return fresh bytes, not re-store the transport's stale snapshot indefinitely.
++ it('refreshes HTML from the host even when the transfer cache contains an older copy', async () => {
++ setMobileAuthOwner('html-refresh-owner');
++ const cached = { ossKey: '', size: 3, mimeType: 'text/html', version: 'a'.repeat(64), inlineBase64: 'b2xk' };
++ const fresh = { ...cached, version: 'b'.repeat(64), inlineBase64: 'bmV3' };
++ fileCache.readLatest.mockResolvedValue(cached);
++ const invoke = vi.fn(async () => fresh);
++ const maker = createMobileMakerTransport({ deviceId: 'html-refresh', invoke: invoke as RemoteInvoke });
++ try {
++ const result = await fetchRemoteAbsFileOnce({ maker, deviceId: 'html-refresh', openLink: async () => {},
++ presignGet: vi.fn() }, '/page.html');
++ expect(result.inlineBase64).toBe(fresh.inlineBase64);
++ expect(invoke).toHaveBeenCalled();
++ expect(fileCache.readLatest).not.toHaveBeenCalled();
++ } finally { fileCache.readLatest.mockReset(); authOwnerTesting.reset(); vi.clearAllMocks(); }
++ });
+ it('checks the host version on every small-file read, reuses disk bytes, and honors forced refresh', async () => {
+ setMobileAuthOwner('cache-owner');
+ const result = { ossKey: '', size: 3, mimeType: 'text/html', version: 'a'.repeat(64), inlineBase64: 'YWJj' };
+ let stored: typeof result | null = null;
+ fileCache.readInline.mockImplementation(async () => stored);
+ fileCache.storeInline.mockImplementation(async (_device, _url, value) => { stored = value; });
+ fileCache.invalidate.mockImplementation(async () => { stored = null; });
+ const invoke = vi.fn(async (_device, _channel, [args]) => args.metadataOnly
+ ? { ...result, inlineBase64: undefined, transferRequired: true } : result);
+ const maker = createMobileMakerTransport({ deviceId: 'd', invoke: invoke as RemoteInvoke });
+ try {
+ expect(await maker.fetchRemoteMedia('xdt-file://open?path=/a.html', { stream: false })).toEqual(result);
+ expect(await maker.fetchRemoteMedia('xdt-file://open?path=/a.html', { stream: false })).toEqual(result);
+ expect(invoke).toHaveBeenCalledTimes(3);
+ await maker.fetchRemoteMedia('xdt-file://open?path=/a.html', { stream: false, skipCache: true });
+ expect(fileCache.invalidate).toHaveBeenCalledWith('d', 'xdt-file://open?path=/a.html');
+ expect(invoke).toHaveBeenCalledTimes(5);
+ } finally { authOwnerTesting.reset(); vi.clearAllMocks(); }
+ });
describe.each([
["video", "video/mp4", "mp4"],
["audio", "audio/mpeg", "mp3"],
diff --cc apps/mobile/src/__tests__/peerFileCache.test.ts
index 03b7f54eae,6a30b78b8f..682e1be054
--- a/apps/mobile/src/__tests__/peerFileCache.test.ts
+++ b/apps/mobile/src/__tests__/peerFileCache.test.ts
@@@ -32,6 -37,6 +37,12 @@@ vi.mock("expo-file-system", () => (
.map((p) => (typeof p === "string" ? p : p.uri))
.join("/");
}
++ static async downloadFileAsync(url: string, target: { uri: string }) {
++ const bytes = disk.files.get(url);
++ if (!bytes) throw new Error("missing");
++ disk.files.set(target.uri, bytes.slice());
++ return new File(target.uri);
++ }
get exists() {
return disk.files.has(this.uri);
}
@@@ -41,7 -54,8 +60,9 @@@
delete() {
disk.files.delete(this.uri);
}
+ async base64() { return Buffer.from(disk.files.get(this.uri)!).toString('base64'); }
+ async text() { return new TextDecoder().decode(disk.files.get(this.uri)); }
- write(text: string) { disk.files.set(this.uri, new TextEncoder().encode(text)); }
++ write(value: string | Uint8Array) { disk.files.set(this.uri, typeof value === "string" ? new TextEncoder().encode(value) : value); }
async copy(target: { uri: string }) {
disk.copying = true;
if (disk.gate) await disk.gate;
@@@ -53,42 -67,14 +74,14 @@@
}
},
}));
- vi.mock("@/session/remoteMediaDiskCacheExpo", () => ({
- downloadRemoteMediaShareTemp: async (url: string) => {
- const uri = `file:///download-${++disk.seq}`;
- const bytes = disk.files.get(url);
- if (!bytes) return null;
- disk.files.set(uri, bytes.slice());
- return uri;
- },
- createExpoRemoteMediaDiskCacheIO: (namespace: string) => {
- const uri = (name: string) => `file:///cache/${namespace}/${name}`;
- return {
- ensureDir() {},
- readIndexText: async () => disk.indexes.get(namespace) ?? null,
- writeIndexText: (text: string) => {
- disk.indexes.set(namespace, text);
- },
- fileExists: (name: string) => disk.files.has(uri(name)),
- fileSize: (name: string) => disk.files.get(uri(name))?.length ?? -1,
- fileUri: uri,
- deleteFile: (name: string) => {
- disk.files.delete(uri(name));
- },
- listFiles: () =>
- [...disk.files.keys()]
- .filter((p) => p.startsWith(`file:///cache/${namespace}/`))
- .map((p) => p.split("/").at(-1)!),
- download: async (source: string, name: string) => {
- const bytes = source.startsWith('data:') ? Buffer.from(source.split(',')[1], 'base64') : disk.files.get(source);
- if (!bytes) return null;
- disk.files.set(uri(name), bytes.slice());
- return bytes.length;
- },
- };
- },
- }));
+ import { createRemoteMediaDiskCache } from '@/session/remoteMediaDiskCache';
+ import { createExpoRemoteMediaDiskCacheIO } from '@/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 { FILE_PEER_MAX_BYTES, sharedTaskHostPeer } from '@cindy/device-link';
+ import { remoteFileMediaUrl } from '@/session/fileBrowserGallery';
import {
clearPeerMedia,
peerMediaUri,
@@@ -101,27 -88,85 +95,107 @@@ afterEach(() =>
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');
++ // Shared guests must revalidate membership before reading, including HTML.
++ expect(createMobileHtmlPreviewCache(sharedTaskHostPeer('shared', 'host'), '/site')).toBeUndefined();
+ 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) };
+it('reuses completed OSS downloads through the same cache and does not retain changed-sized bytes', async () => {
+ const cache = await createPeerFileCache('oss-owner');
+ disk.files.set('https://oss/file', new Uint8Array(5));
+ const result = await cache.download('device', 'url', metadata, 'https://oss/file', () => true);
+ expect(result).not.toBeNull();
+ releasePeerMedia(peerMediaUri(result!)!);
+ expect(await cache.read('device', 'url', metadata, () => true)).not.toBeNull();
+ expect(await cache.download('device', 'changed', { ...metadata, size: 6 }, 'https://oss/file', () => true)).toBeNull();
+ expect(await cache.read('device', 'changed', metadata, () => true)).toBeNull();
+});
+it.each([0, 5])('shares %s-byte inline files with the durable version cache', async size => {
+ const cache = await createPeerFileCache(`inline-${size}`);
+ const result = { ossKey: '', ...metadata, size, inlineBase64: Buffer.alloc(size, 7).toString('base64') };
+ await cache.storeInline('device', 'url', result);
+ expect(await cache.readLatest('device', 'url', () => true)).toEqual(result);
+ expect(await cache.readInline('device', 'url', result, () => true)).toEqual(result);
+ expect(await cache.readInline('other-device', 'url', result, () => true)).toBeNull();
+ expect(await cache.readInline('device', 'url', { ...result, version: 'b'.repeat(64) }, () => true)).toBeNull();
+ expect(await cache.readLatest('device', 'url', () => true)).toEqual(result);
+});
+ // PR #6299: the mocked cache IO hid empty-file rejection. Exercise the real cache
+ // and Expo adapter with an in-memory filesystem (unit): empty first writes and
+ // nonempty -> empty refresh must survive an index reload and shadow old transfers.
+ it.each(['', '<p>Old</p>'])('persists empty preview files after initial content %j', async (initial) => {
+ const account = `empty-preview-${initial.length}`;
+ const owner = JSON.stringify(['global', account]);
+ setMobileAuthOwner(account);
+ const cache = createMobileHtmlPreviewCache('desktop', '/site')!;
+ const source = new File(`file:///input-${account}.html`);
+ const destination = new File(`file:///output-${account}.html`);
+ source.write('<p>Old transfer</p>');
+ const transfer = await createPeerFileCache(owner);
+ const meta = { ...metadata, size: source.size };
+ const media = { ossKey: '', ...meta };
+ recordPeerMedia(media, source.uri, () => {});
+ await transfer.store('desktop', remoteFileMediaUrl('/site/index.html', undefined, undefined,
+ { baseDir: '/site', maxBytes: FILE_PEER_MAX_BYTES }), meta, media);
+ source.write(initial);
+ await cache.store('index.html', source, 'text/html');
+ source.write('');
+ await cache.store('index.html', source, 'text/html');
+ expect(await cache.copy('index.html', destination)).toBe(0);
+ expect(await destination.text()).toBe('');
+ const namespace = `files-${createHash('sha256').update(owner).digest('hex')}`;
+ const reopened = createRemoteMediaDiskCache(createExpoRemoteMediaDiskCacheIO(namespace));
+ const identity = JSON.stringify(['desktop', null, '/site', 'resource', 'index.html']);
+ const hit = await reopened.lookup(`html-preview:${identity}`);
+ expect(hit?.size).toBe(0);
+ expect(await new File(hit!.uri).text()).toBe('');
+ });
async function seed(owner: string) {
const cache = await createPeerFileCache(owner);
const uri = `file:///received/${owner}`;
diff --cc apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
index 7c4225c686,779a050ec0..4e5ced4816
--- a/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
+++ b/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
@@@ -39,30 -39,18 +40,41 @@@ function makeDeps(overrides: Partial<
}
describe('fetchRemoteAbsFileToUrl', () => {
+ it.each([true, false])('reclaims the cloud object only after a local copy is available: %s', async (downloaded) => {
+ const { deps } = makeDeps();
+ const local = { ossKey: '', size: 3, mimeType: 'image/png' };
+ const uri = 'file:///cached-absolute.png';
+ const dispose = vi.fn();
+ recordPeerMedia(local, uri, dispose);
+ const deleteOssObject = vi.fn();
+ const cacheDownload = vi.fn(async () => {
+ expect(deleteOssObject).not.toHaveBeenCalled();
+ return downloaded ? local : null;
+ });
+ deps.maker.fetchRemoteMedia = vi.fn(async () => ({
+ ...local, ossKey: 'absolute/cloud-key', cacheDownload,
+ }));
+ try {
+ const url = await fetchRemoteAbsFileToUrl({ ...deps, stream: false, deleteOssObject }, '/tmp/shot.png');
+ expect(url).toBe(downloaded ? uri : 'https://oss.example/get/abc');
+ expect(cacheDownload).toHaveBeenCalledWith('https://oss.example/get/abc');
+ expect(deleteOssObject.mock.calls).toEqual(downloaded ? [['absolute/cloud-key']] : []);
+ expect(dispose).not.toHaveBeenCalled();
+ } finally { clearPeerMedia(); }
+ });
+
+ // 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 () => {
+ it('revalidates complete files while retaining streaming URLs', async () => {
for (const first of [true, false]) {
const { deps, fetchRemoteMedia } = makeDeps();
await fetchRemoteAbsFileToUrl({ ...deps, stream: first }, '/media.mp4');
diff --cc apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
index 8a92757133,632a7c39bb..6b7213c2a7
--- a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
+++ b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
@@@ -84,53 -62,7 +84,53 @@@ beforeEach(() =>
io.deleteAsync.mockClear();
});
+describe('versioned cache with the Expo adapter', () => {
+ // #6292: IO used to overwrite good bytes before store checked the length.
+ // Existing tests only covered a new version/name. Unit: same-name refresh
+ // through the real cache and Expo adapter must preserve old bytes and index.
+ it.each([undefined, 'a'.repeat(64)])('preserves a good copy on truncated refresh (version %s)', async version => {
+ const cache = createRemoteMediaDiskCache(createExpoRemoteMediaDiskCacheIO());
+ expect(await cache.store('resource', 'https://example.com/good', 'application/pdf', 5, version)).toBe(true);
+ const old = await cache.lookup('resource');
+ io.move.mockClear();
+ io.remove.mockClear();
+ io.size = 3;
+ expect(await cache.store('resource', 'https://example.com/truncated', 'application/pdf', 5, version)).toBe(false);
+ expect(io.move).not.toHaveBeenCalled();
+ expect(io.remove.mock.calls.every(([uri]) => uri.endsWith('.dl.tmp'))).toBe(true);
+ expect(await cache.lookup('resource')).toEqual(old);
+ io.size = 7;
+ expect(await cache.store('resource', 'https://example.com/complete', 'application/pdf', 7, version)).toBe(true);
+ expect(await cache.lookup('resource')).toMatchObject({ size: 7 });
+ });
+ it.each(['data:text/css;base64,', 'file:///empty.css', 'https://example.com/empty.css'])(
- 'retains a confirmed empty file from %s without accepting empty unversioned images', async source => {
++ 'retains a declared empty file from %s but rejects undeclared empty downloads', async source => {
+ io.size = 0;
+ const cache = createRemoteMediaDiskCache(createExpoRemoteMediaDiskCacheIO());
+ const version = 'a'.repeat(64);
+ expect(await cache.store('resource', source, 'text/css', 0, version)).toBe(true);
+ expect(await cache.lookup('resource', version)).toMatchObject({ size: 0, version, mimeType: 'text/css' });
+ expect(io.remove).not.toHaveBeenCalled();
+ expect(io.move).toHaveBeenCalled();
- expect(await cache.store('image', 'https://example.com/empty.png', 'image/png', 0)).toBe(false);
++ expect(await cache.store('image', 'https://example.com/empty.png', 'image/png')).toBe(false);
+ expect(await cache.lookup('image')).toBeNull();
+ },
+ );
+});
+
describe('bounded temporary media downloads', () => {
+ it('keeps a preview copy alive after transport staging expires, until its owner releases it', async () => {
+ const { recordPeerMedia, releasePeerMedia } = await import('@/device-link/peerFileRegistry');
+ const dispose = vi.fn();
+ recordPeerMedia({ ossKey: '', size: 5, mimeType: 'application/pdf' }, 'file:///peer/source', dispose);
+ const retained = await retainRemoteFilePreview('file:///peer/source', 'application/pdf', 'preview.pdf');
+ expect(io.copied.has(retained.uri)).toBe(true);
+ expect(dispose).toHaveBeenCalledOnce();
+ releasePeerMedia('file:///peer/source');
+ expect(io.remove).not.toHaveBeenCalled();
+ retained.release();
+ expect(io.remove).toHaveBeenCalledExactlyOnceWith(retained.uri);
+ });
it('keeps the file until the asynchronous consumer finishes, then removes it', async () => {
let finish!: (value: string) => void;
const read = vi.fn(() => new Promise<string>((done) => { finish = done; }));
diff --cc apps/mobile/src/device-link/peerFileCache.ts
index 22ba6f1e9a,1aa76da138..ff9578156d
--- a/apps/mobile/src/device-link/peerFileCache.ts
+++ b/apps/mobile/src/device-link/peerFileCache.ts
@@@ -40,45 -39,15 +40,52 @@@ async function openPeerFileCache(owner
persistAccess: true,
},
);
- return {
+ const api = {
+ async readLatest(device: string, url: string, active: () => boolean): Promise<DeviceFileResult | null> {
+ const hit = await cache.lookup(JSON.stringify([device, url]));
+ if (!active() || !hit || !validFileVersion(hit.version)) return null;
+ const metadata = { size: hit.size, mimeType: hit.mimeType, version: hit.version };
+ return hit.size <= FILE_INLINE_MAX_BYTES
+ ? api.readInline(device, url, metadata, active)
+ : api.read(device, url, metadata, active);
+ },
+ /** A completed OSS fallback joins the same version cache as direct downloads. */
+ async download(device: string, url: string, metadata: Metadata, downloadUrl: string,
+ active: () => boolean, signal?: AbortSignal): Promise<LocalPeerMedia | null> {
+ if (!active() || !validFileVersion(metadata.version) || !(await api.prune(device, url, metadata.size))) return null;
+ const uri = await downloadRemoteMediaShareTemp(downloadUrl, metadata.mimeType, undefined, signal);
+ if (!uri) return null;
+ const file = new File(uri);
+ const dispose = () => { if (file.exists) file.delete(); };
+ if (!active() || signal?.aborted || file.size !== metadata.size) { dispose(); return null; }
+ const result = { ossKey: '', ...metadata };
+ if (!recordPeerMedia(result, uri, dispose)) { dispose(); return null; }
+ await api.store(device, url, metadata, result).catch(() => undefined);
+ if (!active() || signal?.aborted) { releasePeerMedia(uri); return null; }
+ return result;
+ },
+ async readInline(device: string, url: string, metadata: Metadata, active: () => boolean) {
+ if (!validFileVersion(metadata.version) || metadata.size > FILE_INLINE_MAX_BYTES) return null;
+ const hit = await cache.lookup(JSON.stringify([device, url]), metadata.version);
+ if (!active() || !hit || hit.size !== metadata.size) return null;
+ const inlineBase64 = await new File(hit.uri).base64();
+ if (!active()) return null;
+ return { ossKey: '', ...metadata, inlineBase64 };
+ },
+ async storeInline(device: string, url: string, result: DeviceFileResult) {
+ if (!validFileVersion(result.version) || typeof result.inlineBase64 !== 'string'
+ || result.size > FILE_INLINE_MAX_BYTES) return;
+ await cache.store(JSON.stringify([device, url]),
+ `data:${result.mimeType};base64,${result.inlineBase64}`, result.mimeType, result.size, result.version);
+ },
+ prune: (device: string, url: string, size: number) => cache.prune(2 * size, JSON.stringify([device, url])),
+ // 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])),
async read(
diff --cc apps/mobile/src/device-link/peerFileTransport.tsx
index 8493be6a53,4deca6be13..81b9a6654e
--- a/apps/mobile/src/device-link/peerFileTransport.tsx
+++ b/apps/mobile/src/device-link/peerFileTransport.tsx
@@@ -596,9 -599,9 +599,9 @@@ export function PeerFileTransport()
mobileDebugLog('debug', 'files', 'file cache hit', { trace: readTrace, size: cached.size });
return cached;
}
- if (metadata) await cache?.prune(metadata.size).catch(() => false);
+ if (metadata) await cache?.prune(device, url, 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);
diff --cc apps/mobile/src/session/mobileHtmlPreviewCache.ts
index 0000000000,87d8fd0a37..58d1f8e9a4
mode 000000,100644..100644
--- a/apps/mobile/src/session/mobileHtmlPreviewCache.ts
+++ b/apps/mobile/src/session/mobileHtmlPreviewCache.ts
@@@ -1,0 -1,70 +1,70 @@@
+ import { File } from 'expo-file-system';
-import { FILE_PEER_MAX_BYTES } from '@cindy/device-link';
++import { FILE_PEER_MAX_BYTES, isSharedTaskPeer } 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;
++ if (!owner.accountId || isSharedTaskPeer(deviceId)) 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 --cc apps/mobile/src/session/remoteAbsFileFetch.ts
index 6fe8541c74,7ebdc800c5..3bb0f239c3
--- a/apps/mobile/src/session/remoteAbsFileFetch.ts
+++ b/apps/mobile/src/session/remoteAbsFileFetch.ts
@@@ -180,8 -178,7 +185,9 @@@ export async function fetchRemoteAbsFil
return resolveMobileRemoteMedia(
{ kind: 'image', url: remoteFileMediaUrl(absPath, undefined, ssh, constraints) },
{ fetchRemoteMedia: deps.maker.fetchRemoteMedia, presignGet: deps.presignGet },
- { onOssKey, signal, stream: false, beforeFetch: () => deps.openLink(deps.deviceId),
- discardBackgroundOssKey: deps.deleteOssObject },
- { onOssKey, signal, stream: false, ...(onProgress ? { onProgress } : {}) },
++ // HTML already restores its visible snapshot before calling here. Returning
++ // another stale snapshot would write old bytes back into that preview cache.
++ { onOssKey, signal, stream: false, skipCache: true, ...(onProgress ? { onProgress } : {}) },
);
});
}
diff --cc apps/mobile/src/session/remoteMedia.ts
index 96628524fc,529a173a4e..b5cdd2ebf6
--- a/apps/mobile/src/session/remoteMedia.ts
+++ b/apps/mobile/src/session/remoteMedia.ts
@@@ -51,9 -48,8 +51,11 @@@ export interface MobileResolvedRemoteMe
}
export interface MobileRemoteMediaFetchOptions {
+ /** Local callbacks: only connect on a cache miss or during background revalidation. */
+ beforeFetch?: () => Promise<unknown>;
+ retainBackground?: (result: MobileRemoteMediaFetchResult, isCurrent?: () => boolean) => Promise<void>;
+ /** 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;
@@@ -73,8 -69,7 +75,9 @@@ export interface MobileRemoteMediaResol
}
export interface MobileRemoteMediaResolveOptions {
+ beforeFetch?: () => Promise<unknown>;
+ discardBackgroundOssKey?: (key: string) => void;
+ onProgress?: (loaded: number, total: number) => void;
stream?: boolean;
signal?: AbortSignal;
/** 强制被控端绕过上传去重缓存(上次的 ossKey 已悬空时的自愈路径)。 */
@@@ -201,16 -196,7 +204,17 @@@ export async function resolveMobileRemo
throw new Error(i18n.t("composer.attachments.notFetchableMedia"));
}
const fetchOpts = {
+ ...(opts?.beforeFetch ? { beforeFetch: opts.beforeFetch } : {}),
+ ...(opts?.stream === false ? { retainBackground: async (result: MobileRemoteMediaFetchResult, isCurrent?: () => boolean) => {
+ if (!result.ossKey || isCurrent?.() === false) return;
+ try {
+ const signed = await deps.presignGet(result.ossKey);
+ const copy = await result.cacheDownload?.(signed.getUrl);
+ const uri = copy && peerMediaUri(copy);
+ if (uri) releasePeerMedia(uri);
+ } finally { if (isCurrent?.() !== false) opts.discardBackgroundOssKey?.(result.ossKey); }
+ } } : {}),
+ ...(opts?.onProgress ? { onProgress: opts.onProgress } : {}),
...(opts?.stream !== undefined ? { stream: opts.stream } : {}),
...(opts?.onOssKey ? { onDiscardOssKey: opts.onOssKey } : {}),
...(opts?.signal ? { signal: opts.signal } : {}),
diff --cc apps/mobile/src/session/remoteMediaDiskCache.ts
index 1a6b750ff6,e25d3433d3..438aa5755b
--- a/apps/mobile/src/session/remoteMediaDiskCache.ts
+++ b/apps/mobile/src/session/remoteMediaDiskCache.ts
@@@ -30,9 -30,8 +30,9 @@@ export interface RemoteMediaDiskCacheI
* 下载 url 到缓存文件;成功返回字节数,失败返回 null(不抛)。
* 契约:落位必须原子(临时位置下载、成功后移入)——失败时不得破坏已存在的
* 同名文件,store 的失败清理依赖这一点区分「半成品」与「现存好文件」。
+ * 提供 expectedSize 时必须在移入前校验,尺寸不符返回 null 并保留旧文件。
*/
- download(url: string, name: string, options?: { allowEmpty: boolean; expectedSize?: number }): Promise<number | null>;
+ download(url: string, name: string, expectedSize?: number): Promise<number | null>;
/**
* 把 base64 字节写入缓存文件(inline 缩略图落盘用);成功返回字节数,失败返回
* null(不抛)。契约与 download 相同:落位必须原子,失败不得破坏既有同名文件。
diff --cc apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
index ffc3b4626e,a592ec6eff..a18a9ef7cb
--- a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
+++ b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
@@@ -265,8 -244,7 +264,8 @@@ export function createExpoRemoteMediaDi
try {
const downloaded = await copyRemoteFile(url, tmp);
const size = downloaded.size ?? -1;
- if (size < 0 || (size === 0 && !options?.allowEmpty) ||
- (options?.expectedSize !== undefined && size !== options.expectedSize)) {
- if (!downloaded.exists || size < 0 || (size === 0 && expectedSize !== 0)) {
++ if (!downloaded.exists || size < 0 || (size === 0 && expectedSize !== 0) ||
++ (expectedSize !== undefined && size !== expectedSize)) {
if (tmp.exists) tmp.delete();
return null;
}
diff --cc docs/dev-rules/protocol-compatibility.md
index 2f1fce7075,e6cc6f49df..fb8c8b05bc
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@@ -870,35 -869,10 +870,37 @@@ HTML 等普通文件复用 `remote-file
Mobile 复用 `remote-media` 磁盘缓存,放入 realm/账号 SHA-256 命名空间;无固定容量
门槛,仅在现有传输空间预留不足时按 LRU 清理(保留 256 MiB,并考虑下载与消费者副本)。
-访问顺序落盘、版本不同删除旧条目;版本进入物理文件名,避免异步复制撞上覆盖写。
+访问顺序落盘,新版本完整保存后再替换旧条目;版本进入物理文件名,避免异步复制撞上覆盖写。
+下载尺寸在原子移入前校验,同版本或无版本刷新被截断时也不得覆盖旧文件。
系统清掉目录后,下一次取件自动重建。两端消费者均拿独立副本,清缓存不删正在预览的副本。
强制刷新只跳过旧副本的读取,成功后仍更新缓存,避免下次普通打开又命中损坏副本。
-已有 OSS 和流式媒体缓存维持原生命周期;此缓存只保存已完成的 peer 整文件下载。
+完整文件读取统一复用版本缓存,覆盖 inline 小文件、peer 下载及已经完成的 OSS 回退下载。
+`device-link:media:fetch` 在 `prepareOnly: true` 时接受可选 `metadataOnly: true`:
+仍先授权并从打开的文件句柄取版本,但小文件也只返回 `transferRequired: true` 与元数据。
+两端共用读取策略:小文件先查同一版本缓存,未命中再以原 `prepareOnly` 请求取 inline 字节;
+大文件沿用 peer/OSS 读取。同账号旧 Host 忽略 `metadataOnly`,新控制端接收原 inline/OSS 结果;
+共享任务的旧 Host 使用闭集参数白名单,两端访客不发送 `metadataOnly`,沿用先授权的 inline/OSS
+读取。新 Host 同时接受布尔型 `metadataOnly`,不改变成员、附件归属及工作目录校验。
+旧控制端不传此字段,新 Host 保持原行为。两段式导出缺版本时,以导出前后主机版本和大小一致
+作为登记条件,变化或无版本的结果不登记为长期有效。缓存失败不阻断正常读取。
- Mobile 的 HTML 资源、文件浏览器原图、PDF、下载/分享使用完整文件路径,先取当前账号、设备、
++Mobile 的文件浏览器原图、PDF、下载/分享使用完整文件路径,先取当前账号、设备、
+完整 URL 对应的本地缓存,再后台检查版本;同源在途后台检查合并。连接恢复也放到缓存读取之后。
++HTML 由预览层复用同一账号磁盘缓存并持有独立快照;后台取件跳过传输层的旧快照,
++避免将旧内容再次写回预览缓存。空文件以明确的 expectedSize === 0 为依据保存。
+相对路径到主机 URL 的映射只保留在进程内;Mobile 重启后的首次相对路径读取仍需在线查询
+URL,之后复用持久字节。本次不新增持久 URL 索引,冷启动离线相对路径预览不在覆盖范围内。
- Desktop 完整文件与远程 HTML 预览复用已知元数据和现有磁盘副本,后台检查变化;HTML 的大小/mtime
++Desktop 完整文件与远程 HTML 预览复用现有磁盘副本,后台检查变化;HTML 的大小/mtime
+仅用于快照展示和传输上限,不作为后台跳过读取的版本判据。复验绕过外层 size/mtime 命中,
- device 仍可复用主机确认版本的字节,SSH 重新读取;新版原子保存前保留旧副本。进程重启后
- 尚无元数据索引时先查询版本,字节仍可从已有磁盘缓存复用。后台失败保留旧副本,更新完成后
++device 仍可复用主机确认版本的字节,SSH 重新读取;新版原子保存前保留旧副本。HTML 直接通过
++现有磁盘索引定位副本,不再另维护进程内元数据索引和刷新集合。后台失败保留旧副本,更新完成后
+后续打开使用新版;不强制重载正在操作的 HTML、图片或 PDF。预览持有自己的副本,关闭时仅释放这份副本,
+不会删除可复用的源缓存。零字节 HTML 配套资源也可按版本缓存。
+Mobile 分享及 HTML 资源复制在完成、失败、取消后释放传输暂存;独立消费者副本继续由原持有者管理。
+音视频播放继续用保留的流式地址,不为了缓存而预先下载整份媒体;完整下载仍按上述规则。
+不可变聊天图片与目录维持已有专用缓存;Mobile 限量文本预览先显示缓存(包括绝对路径),
+后台读取后更新当前文本,失败不遮住已有内容,文本不改为无界整文件下载。
+主机确认 BINARY_FILE/OVERSIZE 后撤销下次打开使用的文本缓存,但不清空当前显示的快照。
+不增加缓存目录、额度、通道、服务端改动或 Mobile 原生指纹;完整优化需要两端客户端更新。
网络帧仍是旧版可读的 16 KiB,不增加 wire 通道。新版接收运行时仅在本地桥接声明
批量写入时,把已到达帧合为至多 256 KiB 后串行写盘;仍按实际写入块数归还流控额度,