Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): preserve cached bytes and release consumed staging files

Dash532ed255a84a
diff --git a/apps/mobile/app/files/[sessionId].tsx b/apps/mobile/app/files/[sessionId].tsx
index 1bada65123..a5618855d6 100644
--- a/apps/mobile/app/files/[sessionId].tsx
+++ b/apps/mobile/app/files/[sessionId].tsx
@@ -569,7 +569,8 @@ function RemoteFileBrowserContent() {
);
mime = shareMimeForFileName(item.name);
}
- if (run.cancelled) return;
+ // Consume late staging results even after cancellation; the helper
+ // releases them without starting another copy or download.
const localUri = await downloadRemoteMediaShareTemp(url, mime, item.name, run.abort.signal);
if (run.cancelled) return;
if (!localUri) throw new Error(t('files.browser.downloadFailed'));
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 5aa4a0c1ab..7c7fe9ff59 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -565,7 +565,7 @@ function RemoteFilePreviewContent() {
stream: false,
isCancelled: () => run.cancelled,
});
- if (run.cancelled) return;
+ // The copy helper also releases a late staging result after cancellation.
// 传原始文件名:分享单按真实扩展名识别类型(PDF/视频等非图片 mime 不在
// extOfMime 映射里,不带名字会落成 .img 让接收方无法预览)。
const mime = shareMimeForFileName(item.name);
@@ -1242,6 +1242,11 @@ function TextPreviewPage({
.then((res: FileBrowserReadFileResult) => {
if (cancelled) return;
if (!res.ok) {
+ // Keep the visible snapshot, but don't seed future opens from text
+ // the host has confirmed is no longer previewable.
+ if (cacheable && (res.code === 'OVERSIZE' || res.code === 'BINARY_FILE')) {
+ storeCachedPreviewText(cacheScope, workdir, item.relPath, item.mtimeMs, null);
+ }
// A failed refresh must not hide the text the user is already reading.
if (res.code === 'OVERSIZE') {
unavailable({
diff --git a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
index 3fcf94453e..8a92757133 100644
--- a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
+++ b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
@@ -7,9 +7,11 @@ import {
createExpoRemoteMediaDiskCacheIO,
} from '@/session/remoteMediaDiskCacheExpo';
import { createRemoteMediaDiskCache } from '@/session/remoteMediaDiskCache';
+import { clearPeerMedia, recordPeerMedia, canStagePeerMedia } from '@/device-link/peerFileRegistry';
const io = vi.hoisted(() => ({
size: 5,
+ sizes: new Map<string, number>(),
copying: new Set<string>(),
copied: new Set<string>(),
download: vi.fn(),
@@ -47,31 +49,60 @@ vi.mock('expo-file-system', () => ({
await new Promise((done) => setTimeout(done, 0));
io.copying.delete(target.uri);
io.copied.add(target.uri);
+ io.sizes.set(target.uri, this.size);
}
- get size() { return io.copying.has(this.uri) ? 0 : io.size; }
+ get size() { return io.copying.has(this.uri) ? 0 : (io.sizes.get(this.uri) ?? io.size); }
get exists() { return true; }
async base64() { return 'aGVsbG8='; }
async text() { return ''; }
- write() {}
- moveSync(target: { uri: string }) { io.move(this.uri, target.uri); }
- delete() { io.remove(this.uri); }
+ write(value: string | Uint8Array) { io.sizes.set(this.uri, value.length); }
+ moveSync(target: { uri: string }) {
+ io.sizes.set(target.uri, this.size);
+ io.sizes.delete(this.uri);
+ io.move(this.uri, target.uri);
+ }
+ delete() { io.sizes.delete(this.uri); io.remove(this.uri); }
static downloadFileAsync = io.download;
},
}));
beforeEach(() => {
+ vi.restoreAllMocks();
io.size = 5;
+ io.sizes.clear();
+ clearPeerMedia();
io.copying.clear();
io.copied.clear();
io.remove.mockClear();
io.move.mockClear();
- io.download.mockReset().mockImplementation(async (_url, target) => target);
+ io.download.mockReset().mockImplementation(async (_url, target) => {
+ io.sizes.set(target.uri, io.size);
+ return target;
+ });
io.resumable.mockReset().mockResolvedValue({ status: 200 });
io.cancel.mockClear();
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 => {
io.size = 0;
@@ -141,6 +172,38 @@ describe('bounded temporary media downloads', () => {
});
describe('share temp downloads', () => {
+ // #6292: file/browser/preview/chat exports copy a staged URI but previously
+ // left the source and its budget alive for five minutes. Exercise the shared
+ // production copy entry for success/failure/cancel; existing preview-only
+ // ownership coverage missed the download/share path. Unit, no real files.
+ it.each(['success', 'failure', 'cancel', 'cancel-before'] as const)('releases staging after a %s share copy', async outcome => {
+ const source = 'file:///peer/share-source';
+ const dispose = vi.fn();
+ const size = 2 * 1024 * 1024 * 1024;
+ recordPeerMedia({ ossKey: '', size: 1, mimeType: 'application/pdf' }, 'file:///peer/other', () => {});
+ expect(recordPeerMedia({ ossKey: '', size, mimeType: 'application/pdf' }, source, dispose)).toBe(true);
+ expect(canStagePeerMedia(size)).toBe(false);
+ if (outcome === 'failure') {
+ const { File } = await import('expo-file-system');
+ vi.spyOn(File.prototype, 'copy').mockRejectedValueOnce(new Error('disk full'));
+ }
+ const abort = new AbortController();
+ if (outcome === 'cancel-before') abort.abort();
+ const copy = downloadRemoteMediaShareTemp(source, 'application/pdf', 'share.pdf', abort.signal);
+ if (outcome !== 'cancel-before') expect(dispose).not.toHaveBeenCalled();
+ if (outcome === 'cancel') abort.abort();
+ const uri = await copy;
+ expect(dispose).toHaveBeenCalledOnce();
+ expect(canStagePeerMedia(size)).toBe(true);
+ if (outcome === 'success') {
+ expect(uri).toMatch(/\/share.pdf$/);
+ expect(io.remove).not.toHaveBeenCalled();
+ } else {
+ expect(uri).toBeNull();
+ if (outcome === 'cancel-before') expect(io.copied.size).toBe(0);
+ }
+ vi.restoreAllMocks();
+ });
it('keeps the existing download path when no cancellation signal is given', async () => {
expect(await downloadRemoteMediaShareTemp('https://example.com/a.pdf', 'application/pdf', 'a.pdf'))
.toMatch(/\/a\.pdf$/);
diff --git a/apps/mobile/src/session/fileBrowserCache.ts b/apps/mobile/src/session/fileBrowserCache.ts
index 22f3d8ff72..5d6213ac4d 100644
--- a/apps/mobile/src/session/fileBrowserCache.ts
+++ b/apps/mobile/src/session/fileBrowserCache.ts
@@ -5,7 +5,7 @@
* 规则 7),后台静默刷新后原位更新;跨启动仍有上次快照可秒开。
* 2. 文本迷你缩略图片段:小文件(≤96KB)拉一次首块,渲染真实内容迷你页;
* 片段(≤2KB)内存 + AsyncStorage 双层缓存,key 含 mtime 天然失效。
- * 3. 预览正文:内存 LRU(mtime keyed),翻页/重进不再重复拉取。
+ * 3. 预览正文:内存 LRU(账号/设备/路径),翻页/重进先展示旧内容再后台更新。
*
* AsyncStorage 侧统一带索引数组做 LRU 剪枝,防无限膨胀。
*/
@@ -277,11 +277,12 @@ export function storeCachedPreviewText(
workdir: string,
relPath: string,
_mtimeMs: number,
- value: CachedPreviewText,
+ value: CachedPreviewText | null,
): void {
workdir = JSON.stringify([scope, workdir]);
const key = snippetKey(workdir, relPath, 0);
previewTextMemory.delete(key);
+ if (value === null) return;
previewTextMemory.set(key, value);
while (previewTextMemory.size > PREVIEW_TEXT_MAX_ENTRIES) {
const oldest = previewTextMemory.keys().next().value;
diff --git a/apps/mobile/src/session/remoteMediaDiskCache.ts b/apps/mobile/src/session/remoteMediaDiskCache.ts
index d80f7d5fab..1a6b750ff6 100644
--- a/apps/mobile/src/session/remoteMediaDiskCache.ts
+++ b/apps/mobile/src/session/remoteMediaDiskCache.ts
@@ -30,8 +30,9 @@ export interface RemoteMediaDiskCacheIO {
* 下载 url 到缓存文件;成功返回字节数,失败返回 null(不抛)。
* 契约:落位必须原子(临时位置下载、成功后移入)——失败时不得破坏已存在的
* 同名文件,store 的失败清理依赖这一点区分「半成品」与「现存好文件」。
+ * 提供 expectedSize 时必须在移入前校验,尺寸不符返回 null 并保留旧文件。
*/
- download(url: string, name: string, options?: { allowEmpty: boolean }): Promise<number | null>;
+ download(url: string, name: string, options?: { allowEmpty: boolean; expectedSize?: number }): Promise<number | null>;
/**
* 把 base64 字节写入缓存文件(inline 缩略图落盘用);成功返回字节数,失败返回
* null(不抛)。契约与 download 相同:落位必须原子,失败不得破坏既有同名文件。
@@ -261,11 +262,12 @@ export function createRemoteMediaDiskCache(
// version must never race an overwrite of the same physical file.
const name = `${key}${version ? `-${version}` : ''}.${extOfMime(mimeType)}`;
const prev = entries?.get(key);
- const size = await io.download(downloadUrl, name, { allowEmpty: !!version && expectedSize === 0 });
- if (size !== null && expectedSize !== undefined && size !== expectedSize) {
- await Promise.resolve(io.deleteFile(name)).catch(() => undefined);
- return false;
- }
+ // Validate before the IO publishes bytes: checking afterwards could
+ // delete a same-version file that already replaced the good copy.
+ const size = await io.download(downloadUrl, name, {
+ allowEmpty: !!version && expectedSize === 0,
+ expectedSize,
+ });
return commitWrittenFile(key, name, prev, size, mimeType, version);
};
const pending = downloading.get(key);
diff --git a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
index f3ce41f429..ffc3b4626e 100644
--- a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
+++ b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
@@ -83,9 +83,7 @@ async function copyRemoteFile(
/** A visible preview owns its copy; transport staging and cache eviction cannot expire it. */
export async function retainRemoteFilePreview(url: string, mimeType: string, fileName: string) {
if (!url.startsWith('file://') && !url.startsWith('data:')) return { uri: url, release() {} };
- let uri: string | null;
- try { uri = await downloadRemoteMediaShareTemp(url, mimeType, fileName); }
- finally { if (url.startsWith('file://')) releasePeerMedia(url); }
+ const uri = await downloadRemoteMediaShareTemp(url, mimeType, fileName);
if (!uri) throw new Error('PREVIEW_CACHE_FAILED');
return {
uri,
@@ -109,6 +107,7 @@ export async function downloadRemoteMediaShareTemp(
signal?: AbortSignal,
): Promise<string | null> {
try {
+ if (signal?.aborted) return null;
const dir = new Directory(Paths.cache, SHARE_TMP_DIR_NAME);
dir.create({ intermediates: true, idempotent: true });
const unique = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
@@ -133,6 +132,10 @@ export async function downloadRemoteMediaShareTemp(
return file.exists ? file.uri : null;
} catch {
return null; // 分享失败由调用方兜底提示
+ } finally {
+ // Sharing and visible previews both own their new copy after this handoff.
+ // Only registered transport staging is released; ordinary local files stay.
+ if (url.startsWith('file://')) releasePeerMedia(url);
}
}
@@ -182,6 +185,7 @@ export async function withDownloadedRemoteMediaFile<T>(
} catch {
return null;
} finally {
+ if (url.startsWith('file://')) releasePeerMedia(url);
// 临时文件用完即删:资源可能几十个,留着会把 cache 目录堆满。
try {
target?.delete();
@@ -261,7 +265,8 @@ export function createExpoRemoteMediaDiskCacheIO(namespace?: string): RemoteMedi
try {
const downloaded = await copyRemoteFile(url, tmp);
const size = downloaded.size ?? -1;
- if (size < 0 || (size === 0 && !options?.allowEmpty)) {
+ if (size < 0 || (size === 0 && !options?.allowEmpty) ||
+ (options?.expectedSize !== undefined && size !== options.expectedSize)) {
if (tmp.exists) tmp.delete();
return null;
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index cca087e315..2f1a7c11e0 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -857,6 +857,7 @@ HTML 等普通文件复用 `remote-file-cache` 的 4 GiB 总量上限、LRU 与
Mobile 复用 `remote-media` 磁盘缓存,放入 realm/账号 SHA-256 命名空间;无固定容量
门槛,仅在现有传输空间预留不足时按 LRU 清理(保留 256 MiB,并考虑下载与消费者副本)。
访问顺序落盘,新版本完整保存后再替换旧条目;版本进入物理文件名,避免异步复制撞上覆盖写。
+下载尺寸在原子移入前校验,同版本或无版本刷新被截断时也不得覆盖旧文件。
系统清掉目录后,下一次取件自动重建。两端消费者均拿独立副本,清缓存不删正在预览的副本。
强制刷新只跳过旧副本的读取,成功后仍更新缓存,避免下次普通打开又命中损坏副本。
完整文件读取统一复用版本缓存,覆盖 inline 小文件、peer 下载及已经完成的 OSS 回退下载。
@@ -870,15 +871,19 @@ Mobile 复用 `remote-media` 磁盘缓存,放入 realm/账号 SHA-256 命名
作为登记条件,变化或无版本的结果不登记为长期有效。缓存失败不阻断正常读取。
Mobile 的 HTML 资源、文件浏览器原图、PDF、下载/分享使用完整文件路径,先取当前账号、设备、
完整 URL 对应的本地缓存,再后台检查版本;同源在途后台检查合并。连接恢复也放到缓存读取之后。
+相对路径到主机 URL 的映射只保留在进程内;Mobile 重启后的首次相对路径读取仍需在线查询
+URL,之后复用持久字节。本次不新增持久 URL 索引,冷启动离线相对路径预览不在覆盖范围内。
Desktop 完整文件与远程 HTML 预览复用已知元数据和现有磁盘副本,后台检查变化;HTML 的大小/mtime
仅用于快照展示和传输上限,不作为后台跳过读取的版本判据。复验绕过外层 size/mtime 命中,
device 仍可复用主机确认版本的字节,SSH 重新读取;新版原子保存前保留旧副本。进程重启后
尚无元数据索引时先查询版本,字节仍可从已有磁盘缓存复用。后台失败保留旧副本,更新完成后
后续打开使用新版;不强制重载正在操作的 HTML、图片或 PDF。预览持有自己的副本,关闭时仅释放这份副本,
不会删除可复用的源缓存。零字节 HTML 配套资源也可按版本缓存。
+Mobile 分享及 HTML 资源复制在完成、失败、取消后释放传输暂存;独立消费者副本继续由原持有者管理。
音视频播放继续用保留的流式地址,不为了缓存而预先下载整份媒体;完整下载仍按上述规则。
不可变聊天图片与目录维持已有专用缓存;Mobile 限量文本预览先显示缓存(包括绝对路径),
后台读取后更新当前文本,失败不遮住已有内容,文本不改为无界整文件下载。
+主机确认 BINARY_FILE/OVERSIZE 后撤销下次打开使用的文本缓存,但不清空当前显示的快照。
不增加缓存目录、额度、通道、服务端改动或 Mobile 原生指纹;完整优化需要两端客户端更新。
网络帧仍是旧版可读的 16 KiB,不增加 wire 通道。新版接收运行时仅在本地桥接声明