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。

perf(mobile): 取消历史和媒体磁盘缓存容量淘汰

Dash39c78536f1cc
diff --git a/apps/mobile/src/__tests__/historyDiskStore.test.ts b/apps/mobile/src/__tests__/historyDiskStore.test.ts
index 048b249711..746ce133c7 100644
--- a/apps/mobile/src/__tests__/historyDiskStore.test.ts
+++ b/apps/mobile/src/__tests__/historyDiskStore.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
import { HistoryDiskStore, HISTORY_DISK_BUDGET_BYTES, HISTORY_DISK_ITEM_BYTES, historyValueBytes, type HistoryDiskIO } from '../session/historyDiskStore';
-function fixture(budget = 100) {
+function fixture(budget = HISTORY_DISK_BUDGET_BYTES) {
const files = new Map<string, string>();
const io: HistoryDiskIO = {
read: vi.fn(async name => files.get(name) ?? null),
@@ -30,8 +30,8 @@ describe('history disk cache', () => {
expect(await new HistoryDiskStore(h.io).read('old', current)).toBeNull();
expect(h.io.read).not.toHaveBeenCalledWith('view-old.json');
});
- it('uses a GiB budget and survives a new store without reading every body', async () => {
- expect(HISTORY_DISK_BUDGET_BYTES).toBe(1073741824);
+ it('has no total quota and survives a new store without reading every body', async () => {
+ expect(HISTORY_DISK_BUDGET_BYTES).toBe(Infinity);
const h = fixture();
await h.cache.write('first', 'hello', current);
await h.cache.write('second', 'world', current);
@@ -40,6 +40,19 @@ describe('history disk cache', () => {
expect(await restarted.read('first', current)).toBe('hello');
expect(h.io.read).toHaveBeenCalledTimes(2); // index and requested body only
});
+ it('retains existing history above the old GiB quota when adding another view', async () => {
+ const h = fixture();
+ const index: Record<string, unknown> = {};
+ for (let i = 0; i < 140; i++) {
+ const file = `view-${i}.json`;
+ h.files.set(file, 'existing');
+ index[String(i)] = { file, bytes: HISTORY_DISK_ITEM_BYTES, accessed: i };
+ }
+ h.files.set('index.json', JSON.stringify(index));
+ await h.cache.write('new', 'new body', current);
+ expect(await h.cache.read('0', current)).toBe('existing');
+ expect(h.io.remove).not.toHaveBeenCalled();
+ });
it('retains more than eight views and evicts by actual UTF-8 bytes', async () => {
const h = fixture(30);
for (let i = 0; i < 10; i++) await h.cache.write(String(i), '中', current);
diff --git a/apps/mobile/src/__tests__/remoteMediaDiskCache.test.ts b/apps/mobile/src/__tests__/remoteMediaDiskCache.test.ts
index e9e4d0d9a5..53f0fd5bcd 100644
--- a/apps/mobile/src/__tests__/remoteMediaDiskCache.test.ts
+++ b/apps/mobile/src/__tests__/remoteMediaDiskCache.test.ts
@@ -36,6 +36,18 @@ const URL_B = 'xdt-image://cache/b.png';
const URL_C = 'xdt-image://cache/c.png';
describe('remoteMediaDiskCache', () => {
+ it('retains files above the old 150 MiB quota by default across restarts', async () => {
+ const h = memoryIO();
+ const size = 200 * 1024 * 1024;
+ h.io.download = vi.fn(async (_url, name) => { h.files.set(name, size); return size; });
+ const cache = createRemoteMediaDiskCache(h.io);
+ expect(await cache.store(URL_A, 'https://example.com/a', 'image/png', size)).toBe(true);
+ expect(await cache.store(URL_B, 'https://example.com/b', 'image/png', size)).toBe(true);
+ const restarted = createRemoteMediaDiskCache(h.io);
+ expect(await restarted.lookup(URL_A)).toMatchObject({ size });
+ expect(await restarted.lookup(URL_B)).toMatchObject({ size });
+ expect(h.io.deleteFile).not.toHaveBeenCalled();
+ });
it('misses before store, hits with file uri after store, and persists the index', async () => {
const { io, getIndexText } = memoryIO();
const cache = createRemoteMediaDiskCache(io);
diff --git a/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts b/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts
index c2eddece07..768dcd5cff 100644
--- a/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts
+++ b/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts
@@ -58,7 +58,8 @@ function makeFsDeps(overrides: Partial<SentAttachmentThumbFsDeps> = {}) {
};
}
-beforeEach(() => {
+beforeEach(async () => {
+ await __testing.flushPersist();
__testing.reset();
storage.clear();
});
@@ -110,7 +111,7 @@ describe('sentAttachmentThumbStore', () => {
expect(getSentAttachmentThumbUri(mediaRef)).toContain('sent-attachment-thumbs/');
});
- it('非兜底引用 / 空 sourceUri / 重复引用 / 超大文件不注册', async () => {
+ it('非兜底引用 / 空 sourceUri / 重复引用不注册', async () => {
const { deps, copies } = makeFsDeps();
await registerSentAttachmentThumb('https://example.com/a.jpg', 'file:///cache/a.jpg', deps);
await registerSentAttachmentThumb(undefined, 'file:///cache/a.jpg', deps);
@@ -123,11 +124,11 @@ describe('sentAttachmentThumbStore', () => {
await registerSentAttachmentThumb(OSS_REF, 'file:///cache/other.jpg', deps);
expect(copies).toHaveLength(1);
- // 超过单文件上限的不做兜底(gif / 原样直传的大文件)。
- const big = makeFsDeps({ statSize: async () => __testing.maxSourceBytes + 1 });
+ // 大文件通过原生文件拷贝留底,不再按磁盘预算拒绝。
+ const big = makeFsDeps({ statSize: async () => 30 * 1024 * 1024 });
await registerSentAttachmentThumb(OSS_REF_2, 'file:///cache/huge.gif', big.deps);
- expect(big.copies).toHaveLength(0);
- expect(getSentAttachmentThumbUri(OSS_REF_2)).toBeNull();
+ expect(big.copies).toHaveLength(1);
+ expect(getSentAttachmentThumbUri(OSS_REF_2)).not.toBeNull();
});
it('拷贝失败静默:不写映射、不抛错', async () => {
@@ -140,22 +141,21 @@ describe('sentAttachmentThumbStore', () => {
expect(getSentAttachmentThumbUri(OSS_REF)).toBeNull();
});
- it('超过条目上限时 LRU 淘汰最老条目并删除其文件', async () => {
+ it('超过旧 64 条上限仍保留最老文件', async () => {
const { deps, removed } = makeFsDeps();
- for (let index = 0; index < __testing.maxEntries + 1; index += 1) {
+ for (let index = 0; index < 65; index += 1) {
await registerSentAttachmentThumb(`cindy-oss-attach://m/ref-${index}`, `file:///cache/${index}.jpg`, deps);
}
- expect(getSentAttachmentThumbUri('cindy-oss-attach://m/ref-0')).toBeNull();
- expect(getSentAttachmentThumbUri(`cindy-oss-attach://m/ref-${__testing.maxEntries}`)).not.toBeNull();
- expect(removed).toHaveLength(1);
- expect(removed[0]?.startsWith(`${THUMB_DIR}/thumb-`)).toBe(true);
+ expect(getSentAttachmentThumbUri('cindy-oss-attach://m/ref-0')).not.toBeNull();
+ expect(getSentAttachmentThumbUri(`cindy-oss-attach://m/ref-64`)).not.toBeNull();
+ expect(removed).toHaveLength(0);
});
- it('hydrate 回填持久化映射,清过期条目与目录孤儿文件', async () => {
+ it('hydrate 保留旧映射,只清目录孤儿文件', async () => {
const now = Date.now();
storage.set(__testing.storageKey, JSON.stringify([
{ ossRef: OSS_REF, file: 'thumb-fresh.jpg', at: now - 1000 },
- { ossRef: OSS_REF_2, file: 'thumb-stale.jpg', at: now - __testing.maxAgeMs - 1000 },
+ { ossRef: OSS_REF_2, file: 'thumb-stale.jpg', at: now - 30 * 24 * 60 * 60 * 1000 },
]));
const { deps, removed, setDirFiles } = makeFsDeps();
setDirFiles(['thumb-fresh.jpg', 'thumb-stale.jpg', 'thumb-orphan.jpg']);
@@ -163,16 +163,15 @@ describe('sentAttachmentThumbStore', () => {
await ensureSentAttachmentThumbsHydrated(deps);
expect(getSentAttachmentThumbUri(OSS_REF)).toBe(`${THUMB_DIR}/thumb-fresh.jpg`);
- expect(getSentAttachmentThumbUri(OSS_REF_2)).toBeNull();
- // 过期条目的文件与目录孤儿统一清理。
+ expect(getSentAttachmentThumbUri(OSS_REF_2)).toBe(`${THUMB_DIR}/thumb-stale.jpg`);
+ // 仍被引用的旧文件保留。
expect(removed.sort()).toEqual([
`${THUMB_DIR}/thumb-orphan.jpg`,
- `${THUMB_DIR}/thumb-stale.jpg`,
]);
- // 过期裁剪后的映射写回持久层。
+ // 旧映射仍可供重启恢复。
await __testing.flushPersist();
const parsed = JSON.parse(storage.get(__testing.storageKey)!) as Array<{ ossRef: string }>;
- expect(parsed.map((entry) => entry.ossRef)).toEqual([OSS_REF]);
+ expect(parsed.map((entry) => entry.ossRef)).toEqual([OSS_REF, OSS_REF_2]);
});
it('损坏的持久化内容按空映射处理', async () => {
diff --git a/apps/mobile/src/session/historyDiskStore.ts b/apps/mobile/src/session/historyDiskStore.ts
index ed8d3c7111..c396a6a9c7 100644
--- a/apps/mobile/src/session/historyDiskStore.ts
+++ b/apps/mobile/src/session/historyDiskStore.ts
@@ -1,5 +1,5 @@
-/** Disk-only LRU. The index contains metadata, never message bodies. */
-export const HISTORY_DISK_BUDGET_BYTES = 1024 * 1024 * 1024;
+/** Disk retention has no total quota; explicit lifecycle cleanup still applies. */
+export const HISTORY_DISK_BUDGET_BYTES = Infinity;
export const HISTORY_DISK_ITEM_BYTES = 8 * 1024 * 1024;
/** Conservative JSON/UTF-8 bound with early exit; never copies message bodies. */
@@ -90,8 +90,10 @@ export class HistoryDiskStore {
const old = this.entries![key];
this.entries![key] = { file, bytes, accessed: Date.now() };
const discarded = old ? [old.file] : [];
- let total = Object.values(this.entries!).reduce((sum, entry) => sum + entry.bytes, 0);
- for (const [candidate, entry] of Object.entries(this.entries!).sort((a, b) => a[1].accessed - b[1].accessed)) {
+ let total = Number.isFinite(this.budget)
+ ? Object.values(this.entries!).reduce((sum, entry) => sum + entry.bytes, 0) : 0;
+ for (const [candidate, entry] of Number.isFinite(this.budget)
+ ? Object.entries(this.entries!).sort((a, b) => a[1].accessed - b[1].accessed) : []) {
if (total <= this.budget) break;
if (candidate === key) continue;
delete this.entries![candidate]; total -= entry.bytes; discarded.push(entry.file);
diff --git a/apps/mobile/src/session/remoteMediaDiskCache.ts b/apps/mobile/src/session/remoteMediaDiskCache.ts
index 2fba45aac8..c6745cecc1 100644
--- a/apps/mobile/src/session/remoteMediaDiskCache.ts
+++ b/apps/mobile/src/session/remoteMediaDiskCache.ts
@@ -40,7 +40,7 @@ export interface RemoteMediaDiskCacheIO {
}
export interface RemoteMediaDiskCacheOptions {
- /** 缓存总量上限(字节),默认 150MB。 */
+ /** 可选缓存总量上限(字节),默认不限额。 */
maxBytes?: number;
now?(): number;
}
@@ -73,7 +73,7 @@ export interface RemoteMediaDiskCache {
storeBytes(sourceUrl: string, base64: string, mimeType: string): Promise<boolean>;
}
-const DEFAULT_MAX_BYTES = 150 * 1024 * 1024;
+const DEFAULT_MAX_BYTES = Infinity;
const INDEX_VERSION = 1;
interface IndexEntry {
@@ -167,7 +167,7 @@ export function createRemoteMediaDiskCache(
/** 超出预算按 lastUsedAt 淘汰最旧(调用方随后统一 persistIndex)。 */
async function evictOverBudget(): Promise<void> {
- if (!entries) return;
+ if (!entries || !Number.isFinite(maxBytes)) return;
let total = 0;
for (const entry of entries.values()) total += entry.size;
if (total <= maxBytes) return;
diff --git a/apps/mobile/src/session/sentAttachmentThumbStore.ts b/apps/mobile/src/session/sentAttachmentThumbStore.ts
index 22d2f337d8..50a22dd30a 100644
--- a/apps/mobile/src/session/sentAttachmentThumbStore.ts
+++ b/apps/mobile/src/session/sentAttachmentThumbStore.ts
@@ -9,7 +9,7 @@
* 本 store 补上这个空档:上传成功时把实际 PUT 的文件(降采样产物,通常几百 KB)
* 拷贝进 app 自有目录,记录「ossRef → 本地相对文件名」映射并持久化;渲染用户消息
* 图片时 url 仍是 `cindy-oss-attach://` 且映射命中 → 用本地图当缩略图。桌面端物化后
- * url 变成 `xdt-image://`,兜底自然退场,条目由过期清理回收。
+ * url 变成 `xdt-image://`,兜底自然退场,本地副本保留供再次查看。
*
* 设计要点:
* - 映射存**相对文件名**:iOS app 容器绝对路径会随更新变化,不能持久化绝对路径;
@@ -27,23 +27,13 @@ import { isPayloadDesktopLocalMediaUrl } from '@cindy/maker-shared/payload-summa
const STORAGE_KEY = 'xdt.sentAttachmentThumbs.v1';
/** documentDirectory 下的自有子目录(不放 cache:系统清缓存会把兜底图清裂)。 */
const THUMB_DIR_NAME = 'sent-attachment-thumbs';
-/** 条目上限(LRU,按注册时间淘汰)。窗口期本来就短,64 条覆盖极端连发场景。 */
-const MAX_ENTRIES = 64;
-/** 过期时长:桌面端物化通常秒级完成,7 天足够覆盖「电脑长期离线」的长尾。 */
-const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
-/**
- * 单文件体积上限:降采样产物典型几百 KB;gif / 原样直传可到 30MB(上传上限),
- * 超限的不做本地兜底(气泡回落占位卡,可接受降级),防兜底目录无界膨胀。
- */
-const MAX_SOURCE_BYTES = 8 * 1024 * 1024;
-
/** 拷贝产物扩展名白名单(其余回落 .jpg;只影响文件名,不影响渲染)。 */
const KNOWN_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp']);
interface ThumbEntry {
/** THUMB_DIR_NAME 下的相对文件名。 */
file: string;
- /** 注册时间戳(LRU 淘汰 + 过期清理用)。 */
+ /** 注册时间戳。 */
at: number;
}
@@ -104,7 +94,7 @@ function thumbDir(): string | null {
}
/**
- * 冷启动回填:读持久化映射进内存,顺带清过期条目与目录孤儿文件。幂等,
+ * 冷启动回填:读持久化映射进内存,顺带清目录孤儿文件。幂等,
* 首次查询 / 注册时惰性触发。
*/
export function ensureSentAttachmentThumbsHydrated(
@@ -119,22 +109,13 @@ export function ensureSentAttachmentThumbsHydrated(
async function hydrateInternal(deps: SentAttachmentThumbFsDeps): Promise<void> {
cachedDocDir = await deps.documentDirectory().catch(() => null);
const raw = await AsyncStorage.getItem(STORAGE_KEY).catch(() => null);
- const now = Date.now();
- const keep: Array<[string, ThumbEntry]> = [];
- let dropped = 0;
- for (const [ossRef, entry] of parseStoredEntries(raw)) {
- if (now - entry.at > MAX_AGE_MS) {
- dropped += 1;
- continue;
- }
- keep.push([ossRef, entry]);
- }
+ const keep = parseStoredEntries(raw);
// 内存以磁盘为底、保留 hydrate 期间已注册的新条目(register 先 await hydrate,
// 实际不会先写;防御性合并保证后写胜)。
for (const [ossRef, entry] of keep) {
if (!entries.has(ossRef)) entries.set(ossRef, entry);
}
- // 目录孤儿清理:磁盘上存在但映射不再引用的文件(过期条目的文件也在此统一删)。
+ // 目录孤儿清理:磁盘上存在但映射不再引用的文件。
const dir = thumbDir();
if (dir) {
const kept = new Set([...entries.values()].map((entry) => entry.file));
@@ -143,7 +124,6 @@ async function hydrateInternal(deps: SentAttachmentThumbFsDeps): Promise<void> {
if (!kept.has(name)) void deps.remove(`${dir}/${name}`).catch(() => undefined);
}
}
- if (dropped > 0) schedulePersist();
bump();
}
@@ -175,28 +155,11 @@ export async function registerSentAttachmentThumb(
if (entries.has(ossRef)) return;
const dir = thumbDir();
if (!dir) return;
- const size = await deps.statSize(sourceUri).catch(() => 0);
- if (size > MAX_SOURCE_BYTES) return;
const at = Date.now();
fileSeq += 1;
const file = `thumb-${at}-${fileSeq}.${extForUri(sourceUri)}`;
await deps.makeDirectory(dir);
await deps.copy(sourceUri, `${dir}/${file}`);
- // LRU 淘汰:超上限先删最老条目(含其文件),再入新条目。
- while (entries.size >= MAX_ENTRIES) {
- let oldestKey: string | null = null;
- let oldestAt = Number.POSITIVE_INFINITY;
- for (const [key, entry] of entries) {
- if (entry.at < oldestAt) {
- oldestAt = entry.at;
- oldestKey = key;
- }
- }
- if (!oldestKey) break;
- const evicted = entries.get(oldestKey);
- entries.delete(oldestKey);
- if (evicted) void deps.remove(`${dir}/${evicted.file}`).catch(() => undefined);
- }
entries.set(ossRef, { file, at });
schedulePersist();
bump();
@@ -301,9 +264,6 @@ function schedulePersist(): void {
}
export const __testing = {
- maxAgeMs: MAX_AGE_MS,
- maxEntries: MAX_ENTRIES,
- maxSourceBytes: MAX_SOURCE_BYTES,
storageKey: STORAGE_KEY,
thumbDirName: THUMB_DIR_NAME,
/** 等持久化队列排空(测试断言 AsyncStorage 内容前调用)。 */