Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 持久复用远程图片并提供独立缓存清理
Dash585370c81511
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex de3f6244a2..112b525073 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -414,6 +414,7 @@ import {isCindyPersonalRuntime,} from './cindy-make/versionRuntimeIdentity.js';import { createStorageIpcHandlers } from './cindy-media/storageIpc';+import { clearLocalEntries } from './device-link/remoteMediaCacheStore';import {collectDatabaseSizeWarningStatus,type DatabaseSizeWarningStatus,@@ -8418,6 +8419,7 @@ const registerIpcHandlers = () => {});const storageHandlers = createStorageIpcHandlers({+ clearRemoteMediaMemory: clearLocalEntries,getQueueScanTexts: collectAgentInputQueueScanTexts,loadSnapshotPayloads: loadAllQueueSnapshotPayloads,getRegisteredDraftUrls: getAllRegisteredDraftUrls,@@ -8438,22 +8440,30 @@ const registerIpcHandlers = () => {? Promise.resolve({ bytes: 0, fileCount: 0 }): withActiveChatAttachmentRoot((rootDir) => getFixedDirectoryStats(rootDir)),});- ipcMain.handle('cindy-media:storage-stats', () => storageHandlers.stats());- ipcMain.handle('cindy-media:storage-scan', (_event, params: { draftUrls: string[] }) =>- storageHandlers.scan(params),- );+ ipcMain.handle('cindy-media:storage-stats', (event) => {+ assertTrustedAppRendererEvent(event);+ return storageHandlers.stats();+ });+ ipcMain.handle('cindy-media:storage-scan', (event, params: { draftUrls: string[]; scope?: 'remote-media' }) => {+ assertTrustedAppRendererEvent(event);+ return storageHandlers.scan(params);+ });ipcMain.handle('cindy-media:storage-cleanup',(- _event,+ event,params: {draftUrls: string[];+ scope?: 'remote-media';zeroRefHashes: string[];evictCacheHashes: string[];deadDirNames: string[];cleanTmpFiles: boolean;},- ) => storageHandlers.cleanup(params),+ ) => {+ assertTrustedAppRendererEvent(event);+ return storageHandlers.cleanup(params);+ },);ipcMain.handle('cindy-media:storage-reconcile', () => storageHandlers.reconcile());ipcMain.handle('cindy-media:legacy-images-open-dir', (event) => {diff --git a/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts b/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.tsindex 9963083f34..d93623586d 100644--- a/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts@@ -15,6 +15,9 @@ import type { LedgerDb } from '../ledger';import type { StorageIpcDeps } from '../storageIpc';let tmpUserData = '';+vi.mock('../../device-link/broadcast-tap', () => ({+ captureDataOwnerBroadcastScope: () => ({}), isDataOwnerBroadcastScopeCurrent: () => true,+}));vi.mock('electron', () => ({app: { getPath: () => tmpUserData },@@ -65,6 +68,37 @@ afterEach(() => {const OLD_MS = 100 * 60 * 60 * 1000;+it('clears only remote cache candidates, preserving attachments, shared bytes and other integrations', async () => {+ const remote = await seedBlob('remote', { isCache: true });+ const other = await seedBlob('other', { isCache: true });+ const shared = await seedBlob('shared', { isCache: true });+ const pinned = await seedBlob('pinned', { isCache: false });+ const live = await seedBlob('draft', { isCache: true });+ for (const row of [remote, shared, pinned, live]) await ledger.addRef({+ hash: row.hash, refKind: 'integration-cache', refId: `remote-media:${row.hash}`,+ originId: 'remote-media', originKind: 'integration',+ }, db);+ for (const row of [other, shared]) await ledger.addRef({+ hash: row.hash, refKind: 'integration-cache', refId: `other:${row.hash}`,+ originId: 'other', originKind: 'integration',+ }, db);+ const clearRemoteMediaMemory = vi.fn();+ const handlers = makeHandlers({ clearRemoteMediaMemory });+ const scan = await handlers.scan({ scope: 'remote-media', draftUrls: [live.url] });+ expect(scan.cache.evictable.map((entry) => entry.hash)).toEqual([remote.hash]);+ expect(scan.zeroRef.hashes).toEqual([]);+ const result = await handlers.cleanup({+ scope: 'remote-media', draftUrls: [live.url],+ evictCacheHashes: [remote, other, shared, pinned, live].map((entry) => entry.hash),+ zeroRefHashes: [pinned.hash], deadDirNames: ['images'], cleanTmpFiles: true,+ });+ expect(result.cacheEvicted.deleted).toBe(1);+ expect(result.freedBytes).toBe(remote.bytes);+ expect(await ledger.getBlobInfo(remote.hash, db)).toBeNull();+ for (const row of [other, shared, pinned, live]) expect(await ledger.getBlobInfo(row.hash, db)).not.toBeNull();+ expect(clearRemoteMediaMemory).toHaveBeenCalledTimes(2);+});+async function seedBlob(content: string,opts?: { isCache?: boolean; aged?: boolean; mimeType?: string },@@ -105,6 +139,7 @@ function makeHandlers(overrides?: {clearChatAttachmentsDir?: () => Promise<void>;getLegacyImagesDirStats?: StorageIpcDeps['getLegacyImagesDirStats'];getChatAttachmentsDirStats?: StorageIpcDeps['getChatAttachmentsDirStats'];+ clearRemoteMediaMemory?: () => void;}) {return createStorageIpcHandlers({getQueueScanTexts: () => overrides?.queueTexts ?? [],@@ -118,6 +153,7 @@ function makeHandlers(overrides?: {clearChatAttachmentsDir: overrides?.clearChatAttachmentsDir ?? (async () => undefined),getLegacyImagesDirStats: overrides?.getLegacyImagesDirStats,getChatAttachmentsDirStats: overrides?.getChatAttachmentsDirStats,+ clearRemoteMediaMemory: overrides?.clearRemoteMediaMemory,});}diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.tsindex 5aa5dec8f6..6e708c9da0 100644--- a/apps/desktop/src/main/cindy-media/ledger.ts+++ b/apps/desktop/src/main/cindy-media/ledger.ts@@ -509,6 +509,13 @@ export async function removeGhostDepositRef(return result.changes > 0;}+/** Local attachment reuse must not bypass a remote cache's owner/device index. */+export async function hasNonCacheBlob(hash: string, db: LedgerDb = defaultDb()): Promise<boolean> {+ const rows = await db.select({ hash: mediaBlobs.hash }).from(mediaBlobs)+ .where(and(eq(mediaBlobs.hash, hash), eq(mediaBlobs.isCache, false))).limit(1).all();+ return rows.length > 0;+}+/** 查某指纹的落盘元数据(改图代办等"手里只有指纹"的调用方用);无账即 null。 */export async function getBlobInfo(hash: string,diff --git a/apps/desktop/src/main/cindy-media/storageIpc.ts b/apps/desktop/src/main/cindy-media/storageIpc.tsindex f3acfb289d..7823fbf12f 100644--- a/apps/desktop/src/main/cindy-media/storageIpc.ts+++ b/apps/desktop/src/main/cindy-media/storageIpc.ts@@ -27,6 +27,8 @@ import * as recycler from './recycler';import * as legacyDeadDirs from './legacyDeadDirs';import type { FixedDirectoryStats } from './fixedDirectory';import type { LiveHashSources } from './recycler';+import { getDbClient } from '../localDb/client/current';+import { captureRemoteMediaOwner, invalidateRemoteMediaPersistentWrites, REMOTE_MEDIA_INTEGRATION } from '../device-link/remoteMediaPersistentCache';const log = createLogger('cindy-media-storage-ipc');@@ -54,12 +56,14 @@ export interface StorageIpcDeps {clearChatAttachmentsDir?: () => Promise<void>;getLegacyImagesDirStats?: () => Promise<FixedDirectoryStats>;getChatAttachmentsDirStats?: () => Promise<FixedDirectoryStats>;+ clearRemoteMediaMemory?: () => void;}export interface StorageStatsResult {success: boolean;error?: string;blobs: ledger.MediaStorageStats;+ remoteMedia?: FixedDirectoryStats;legacy: { bytes: number; fileCount: number };fixedCaches: {legacyImages: FixedDirectoryStats;@@ -69,6 +73,7 @@ export interface StorageStatsResult {}export interface StorageScanParams {+ scope?: 'remote-media';/** renderer 收集的全部会话草稿附件 URL(活引用暂存区 (1))。 */draftUrls: string[];}@@ -83,6 +88,7 @@ export interface StorageScanResult {}export interface StorageCleanupParams {+ scope?: 'remote-media';draftUrls: string[];/** scan 给出、用户确认的零引用候选指纹。 */zeroRefHashes: string[];@@ -202,15 +208,17 @@ export function createStorageIpcHandlers(deps: StorageIpcDeps) {async stats(): Promise<StorageStatsResult> {try {- const [blobs, deadDirs, legacyImages, chatAttachments] = await Promise.all([+ const [blobs, deadDirs, legacyImages, chatAttachments, remoteMedia] = await Promise.all([ledger.getStorageStats(deps.db),legacyDeadDirs.scanDeadDirs(deps.legacyRootDir),deps.getLegacyImagesDirStats?.() ?? Promise.resolve({ bytes: 0, fileCount: 0 }),deps.getChatAttachmentsDirStats?.() ?? Promise.resolve({ bytes: 0, fileCount: 0 }),+ ledger.listCacheBlobsByLru(deps.db, REMOTE_MEDIA_INTEGRATION),]);return {success: true,blobs,+ remoteMedia: { bytes: remoteMedia.reduce((sum, row) => sum + row.bytes, 0), fileCount: remoteMedia.length },legacy: { bytes: 0, fileCount: 0 },fixedCaches: { legacyImages, chatAttachments },deadDirs,@@ -234,6 +242,15 @@ export function createStorageIpcHandlers(deps: StorageIpcDeps) {async scan(params: StorageScanParams): Promise<StorageScanResult> {try {+ if (params?.scope === 'remote-media') {+ const assertCurrent = captureRemoteMediaOwner();+ const db = deps.db ?? getDbClient().drizzle;+ const live = await collectLive(deps, params.draftUrls ?? []);+ assertCurrent();+ const cache = await recycler.scanCache({ live, limitBytes: 0, integration: REMOTE_MEDIA_INTEGRATION }, db);+ assertCurrent();+ return { success: true, zeroRef: EMPTY_ZERO_REF, cache, tmpFileCount: 0, deadDirs: [] };+ }const live = await collectLive(deps, params?.draftUrls ?? []);const [zeroRef, cache, staleTmp, deadDirs] = await Promise.all([recycler.scanZeroRef({ live }, deps.db),@@ -276,6 +293,23 @@ export function createStorageIpcHandlers(deps: StorageIpcDeps) {throwIpcError('INVALID_PARAMS', 'cindy-media storage cleanup: params required');}try {+ if (params.scope === 'remote-media') {+ const assertCurrent = captureRemoteMediaOwner();+ const db = deps.db ?? getDbClient().drizzle;+ invalidateRemoteMediaPersistentWrites();+ deps.clearRemoteMediaMemory?.();+ const live = await collectLive(deps, params.draftUrls ?? []);+ assertCurrent();+ const cacheEvicted = await recycler.evictCacheBlobs({+ hashes: params.evictCacheHashes ?? [], live,+ integration: REMOTE_MEDIA_INTEGRATION, assertStillValid: assertCurrent,+ }, db);+ assertCurrent();+ deps.clearRemoteMediaMemory?.();+ return { zeroRef: { deleted: 0, freedBytes: 0, skipped: 0 }, cacheEvicted,+ deadDirs: { removed: [], skipped: [], freedBytes: 0 }, tmpFilesRemoved: 0,+ freedBytes: cacheEvicted.freedBytes };+ }// 执行时重新取证:扫描→确认之间用户可能又粘了图/发了排队消息。const live = await collectLive(deps, params.draftUrls ?? []);const zeroRef = await recycler.deleteZeroRefBlobs(diff --git a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.tsindex e29b7e4e30..880d5856a8 100644--- a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts@@ -91,6 +91,17 @@ afterEach(() => {vi.useRealTimers();});+it('does not cache an OSS upload under a version when the source changed during upload', async () => {+ const url = 'xdt-file://local?path=' + encodeURIComponent(path.resolve('work/report.pdf'));+ uploadLocalFile.mockImplementation(async () => {+ statMock.mockResolvedValue({ isFile: () => true, size: 42, mtimeMs: 2000 });+ return { key: 'changed-source', size: 42, contentType: 'application/pdf' };+ });+ const result = await fetchLocalMediaToOss({ url });+ expect(result.ossKey).toBe('changed-source');+ expect(result.version).toBeUndefined();+});+describe('fetchLocalMediaToOss — scheme 路由', () => {const sharedTask: SharedTaskPeerCapture = {author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'guest', accountId: 'user', displayName: 'Guest' },@@ -249,6 +260,7 @@ describe('fetchLocalMediaToOss — scheme 路由', () => {ossKey: 'cindy/device-link/u/uuid.ext',mimeType: 'image/png',size: 42,+ version: expect.stringMatching(/^[a-f0-9]{64}$/),});});diff --git a/apps/desktop/src/main/device-link/__tests__/remoteFileVersionCache.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteFileVersionCache.test.tsindex 54158f9d98..1e0d986bed 100644--- a/apps/desktop/src/main/device-link/__tests__/remoteFileVersionCache.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/remoteFileVersionCache.test.ts@@ -24,6 +24,13 @@ afterEach(async () => {await fs.rm(state.root, { recursive: true, force: true });});const metadata = { version: 'a'.repeat(64), size: 5, mimeType: 'text/html' };+it('retains a complete fallback download for a later version-validated read', async () => {+ await remoteFileVersionCache('device', 'url', metadata)!.put(Buffer.from('hello'));+ state.generation++;+ const file = await remoteFileVersionCache('device', 'url', metadata)!.get();+ expect(await fs.readFile(file!, 'utf8')).toBe('hello');+ expect(await remoteFileVersionCache('device', 'url', { ...metadata, version: 'b'.repeat(64) })!.get()).toBeNull();+});it('keeps large files across new cache instances and login generations, with independent owner/device/url identities', async () => {const file = path.join(state.root, 'original');const size = 17 * 1024 * 1024;diff --git a/apps/desktop/src/main/device-link/__tests__/remoteMediaCacheStore.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteMediaCacheStore.test.tsindex 31f112f3f7..17147a5ea1 100644--- a/apps/desktop/src/main/device-link/__tests__/remoteMediaCacheStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/remoteMediaCacheStore.test.ts@@ -4,6 +4,8 @@import { describe, it, expect, vi, beforeEach } from 'vitest';const removeRemote = vi.hoisted(() => vi.fn(async () => {}));+const owner = vi.hoisted(() => ({ key: 'owner:1' }));+vi.mock('../../appSessionState', () => ({ activeOwnerScopeKey: () => owner.key }));vi.mock('../mediaTransfer', () => ({ removeRemote }));vi.mock('../../logger', () => ({createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),@@ -23,11 +25,19 @@ import {const D = 'dev-1';beforeEach(() => {+ owner.key = 'owner:1';__resetForTests();removeRemote.mockClear();});describe('lookup / record', () => {+ it('does not reuse warm bytes across account generations', () => {+ recordLocal(D, 'xdt-image://s/a.png', Buffer.from('private'), 'image/png');+ owner.key = 'other:2';+ expect(lookup(D, 'xdt-image://s/a.png')).toBeUndefined();+ owner.key = 'owner:3';+ expect(lookup(D, 'xdt-image://s/a.png')).toBeUndefined();+ });it('recordLocal 后 lookup 命中(同 key),不同 origUrl 不串', () => {recordLocal(D, 'xdt-image://s/a.png', Buffer.from([1, 2, 3]), 'image/png');const e = lookup(D, 'xdt-image://s/a.png');diff --git a/apps/desktop/src/main/device-link/__tests__/remoteMediaPersistentCache.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteMediaPersistentCache.test.tsnew file mode 100644index 0000000000..eace79ed98--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/remoteMediaPersistentCache.test.ts@@ -0,0 +1,142 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import type { LedgerDb } from '../../cindy-media/ledger';++const state = vi.hoisted(() => ({+ root: '',+ owner: 'alice',+ generation: 1,+ db: undefined as LedgerDb | undefined,+}));+vi.mock('electron', () => ({ app: { getPath: () => state.root } }));+vi.mock('../../appSessionState', () => ({+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: state.owner }),+}));+vi.mock('../../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: state.db }) }));+vi.mock('../broadcast-tap', () => ({+ captureDataOwnerBroadcastScope: () => state.generation,+ isDataOwnerBroadcastScopeCurrent: (generation: number) => generation === state.generation,+}));++import * as schema from '../../localDb/schema';+import { listAllBlobRecords, listCacheBlobsByLru } from '../../cindy-media/ledger';+import { resolveHashRef } from '../../cindy-media/blobStore';+import {+ invalidateRemoteMediaPersistentWrites,+ remoteMediaPersistentCache,+} from '../remoteMediaPersistentCache';+import { remoteFileVersionCache } from '../remoteFileVersionCache';++const { default: migration0071 } =+ (await import('../../../../drizzle/scripts/0071_bright_ultron')) as {+ default: { run: (db: Database.Database) => void };+ };+let raw: Database.Database;+const png = Buffer.from('89504e470d0a1a0a0000000d49484452', 'hex');+const url = `cindy-media://blobs/${createHash('sha256').update(png).digest('hex')}.png`;+function reopen() {+ raw = new Database(path.join(state.root, 'ledger.db'));+ raw.pragma('foreign_keys = ON');+ state.db = drizzle(raw, { schema }) as unknown as LedgerDb;+}+beforeEach(async () => {+ state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'remote-image-cache-'));+ state.owner = 'alice';+ state.generation = 1;+ reopen();+ const sql = await fs.readFile(+ path.resolve(__dirname, '../../../../drizzle/0070_woozy_harpoon.sql'),+ 'utf8',+ );+ for (const statement of sql.split('--> statement-breakpoint'))+ if (statement.trim()) raw.exec(statement);+ migration0071.run(raw);+});+afterEach(async () => {+ raw.close();+ await fs.rm(state.root, { recursive: true, force: true });+});++it('reuses image bytes after closing and reopening the database, across login generations', async () => {+ await remoteMediaPersistentCache('computer', url)!.put(png, 'image/png');+ raw.close();+ state.generation++;+ reopen();+ const cached = await remoteMediaPersistentCache('computer', url)!.get(1024);+ expect(cached?.bytes).toEqual(png);+ expect((await listCacheBlobsByLru(state.db, 'remote-media')).length).toBe(1);+});++it('direct transfers and preview downloads share one persistent index and cleanup category', async () => {+ const direct = remoteFileVersionCache('computer', url, {+ version: 'b'.repeat(64),+ size: png.length,+ mimeType: 'image/png',+ })!;+ await direct.put(png);+ expect((await remoteMediaPersistentCache('computer', url)!.get(1024))?.bytes).toEqual(png);+ await remoteMediaPersistentCache('computer', url)!.put(png, 'image/png');+ expect(await listCacheBlobsByLru(state.db, 'remote-file')).toEqual([]);+ expect(await listCacheBlobsByLru(state.db, 'remote-media')).toHaveLength(1);+ expect(await direct.get()).not.toBeNull();+});++it('isolates device, account and original URL even when their bytes are identical', async () => {+ await remoteMediaPersistentCache('computer', url)!.put(png, 'image/png');+ expect(await remoteMediaPersistentCache('other-computer', url)!.get(1024)).toBeNull();+ expect(+ await remoteMediaPersistentCache('computer', 'xdt-image://history/image.png')!.get(1024),+ ).toBeNull();+ state.owner = 'bob';+ state.generation++;+ expect(await remoteMediaPersistentCache('computer', url)!.get(1024)).toBeNull();+});++it('detects a corrupt local file and refuses oversized cache reads', async () => {+ const cache = remoteMediaPersistentCache('computer', url)!;+ await cache.put(png, 'image/png');+ expect(await cache.get(1)).toBeNull();+ const [record] = await listAllBlobRecords(state.db);+ const file = resolveHashRef(record.hash, record.ext).absPath;+ await fs.writeFile(file, Buffer.alloc(png.length));+ expect(await cache.get(1024)).toBeNull();+ const direct = remoteFileVersionCache('computer', url, {+ version: 'b'.repeat(64), size: png.length, mimeType: 'image/png',+ })!;+ expect(await direct.get()).toBeNull();+ await direct.put(png);+ expect(await direct.get()).toBe(file);+ expect((await cache.get(1024))?.bytes).toEqual(png);+ await fs.rm(file);+ expect(await cache.get(1024)).toBeNull();+});++it('does not persist arbitrary paths, false image MIME, or mismatched content addresses', async () => {+ expect(remoteMediaPersistentCache('computer', 'xdt-file://local/?path=/image.png')).toBeNull();+ await remoteMediaPersistentCache('computer', url)!.put(Buffer.from('not an image'), 'image/png');+ await remoteMediaPersistentCache('computer', `cindy-media://blobs/${'a'.repeat(64)}.png`)!.put(+ png,+ 'image/png',+ );+ expect(await listAllBlobRecords(state.db)).toEqual([]);+});++it('drops a late write after account switching without adding a cache index', async () => {+ const pending = remoteMediaPersistentCache('computer', url)!.put(png, 'image/png');+ state.owner = 'bob';+ state.generation++;+ await expect(pending).rejects.toThrow('FILE_PEER_CANCELLED');+ expect(await listCacheBlobsByLru(state.db, 'remote-media')).toEqual([]);+});++it('does not refill a cache that was cleared during its background write', async () => {+ const pending = remoteMediaPersistentCache('computer', url)!.put(png, 'image/png');+ invalidateRemoteMediaPersistentWrites();+ await expect(pending).rejects.toThrow('REMOTE_MEDIA_CACHE_CLEARED');+ expect(await listCacheBlobsByLru(state.db, 'remote-media')).toEqual([]);+});diff --git a/apps/desktop/src/main/device-link/__tests__/remoteMediaProtocol.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteMediaProtocol.test.tsindex e0d41f3676..e7ae4c7deb 100644--- a/apps/desktop/src/main/device-link/__tests__/remoteMediaProtocol.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/remoteMediaProtocol.test.ts@@ -16,9 +16,18 @@ vi.mock('electron', () => ({}));const tryPeerFile = vi.hoisted(() => vi.fn());+const persistentGet = vi.hoisted(() => vi.fn(async () => null));+const persistentPut = vi.hoisted(() => vi.fn(async () => {}));+vi.mock('../../cindy-media/integrationCache', () => ({ integrationCacheGet: vi.fn(), integrationCachePut: vi.fn() }));+const owner = vi.hoisted(() => ({ key: 'owner:1', current: true }));+vi.mock('../../appSessionState', () => ({ activeOwnerScopeKey: () => owner.key }));+vi.mock('../remoteMediaPersistentCache', async (importOriginal) => {+ const original = await importOriginal<typeof import('../remoteMediaPersistentCache')>();+ return { ...original, remoteMediaPersistentCache: () => ({ get: persistentGet, put: persistentPut }) };+});vi.mock('../broadcast-tap', () => ({captureDataOwnerBroadcastScope: () => ({}),- isDataOwnerBroadcastScopeCurrent: () => true,+ isDataOwnerBroadcastScopeCurrent: () => owner.current,}));vi.mock('../filePeer', () => ({ tryPeerFile }));@@ -58,7 +67,7 @@ vi.mock('../../file-browser/ssh-media', () => ({ serveSshRemoteMedia }));const blobResolveSafe = vi.hoisted(() => vi.fn());vi.mock('../../cindy-media/blobStore', () => ({ resolveSafe: blobResolveSafe }));const touchBlob = vi.hoisted(() => vi.fn(async () => {}));-vi.mock('../../cindy-media/ledger', () => ({ touchBlob }));+vi.mock('../../cindy-media/ledger', () => ({ touchBlob, hasNonCacheBlob: vi.fn(async () => true) }));const fsReadFile = vi.hoisted(() => vi.fn());vi.mock('node:fs/promises', () => ({default: { readFile: fsReadFile },@@ -81,6 +90,9 @@ const URL_VID = buildRemoteMediaUrl({ kind: 'device', deviceId: 'dev-1' }, 'xdt-beforeEach(() => {vi.clearAllMocks();+ owner.current = true;+ owner.key = 'owner:1';+ persistentGet.mockResolvedValue(null);tryPeerFile.mockResolvedValue(null);lookup.mockReturnValue(undefined);evictEntry.mockReturnValue(true); // 默认无 in-flight 消费者,可逐出@@ -94,6 +106,47 @@ beforeEach(() => {});describe('handleRemoteMedia', () => {+ it('serves a persisted image after the memory cache is empty without contacting the host', async () => {+ const bytes = Buffer.from('saved');+ persistentGet.mockResolvedValueOnce({ bytes, mimeType: 'image/png' } as never);+ recordLocal.mockReturnValue({ kind: 'local', bytes, mimeType: 'image/png' });+ const response = await handleRemoteMedia(URL_IMG, null);+ expect(Buffer.from(await response.arrayBuffer())).toEqual(bytes);+ expect(remoteInvoke).not.toHaveBeenCalled();+ expect(persistentPut).not.toHaveBeenCalled();+ });++ it('persists downloaded images even when the host only supports the OSS fallback', async () => {+ const bytes = Buffer.from('downloaded');+ remoteInvoke.mockResolvedValue({ ok: true, result: { ossKey: 'image', mimeType: 'image/png', size: bytes.length } });+ downloadToBuffer.mockResolvedValue({ bytes });+ recordLocal.mockReturnValue({ kind: 'local', bytes, mimeType: 'image/png' });+ expect((await handleRemoteMedia(URL_IMG, null)).status).toBe(200);+ expect(persistentPut).toHaveBeenCalledWith(bytes, 'image/png');+ });++ it('revalidates mutable paths instead of serving their old warm image', async () => {+ lookup.mockReturnValue({ kind: 'local', bytes: Buffer.from('old'), mimeType: 'image/png' });+ const bytes = Buffer.from('new');+ remoteInvoke.mockResolvedValue({ ok: true, result: { ossKey: '', inlineBase64: bytes.toString('base64'), mimeType: 'image/png', size: bytes.length } });+ recordLocal.mockReturnValue({ kind: 'local', bytes, mimeType: 'image/png' });+ const url = buildRemoteMediaUrl({ kind: 'device', deviceId: 'dev-1' }, 'xdt-file://local/?path=/image.png');+ const response = await handleRemoteMedia(url, null);+ expect(Buffer.from(await response.arrayBuffer())).toEqual(bytes);+ expect(remoteInvoke).toHaveBeenCalled();+ });++ it('rejects a download finishing after an account switch without publishing warm or disk bytes', async () => {+ remoteInvoke.mockResolvedValue({ ok: true, result: { ossKey: 'image', mimeType: 'image/png', size: 3 } });+ downloadToBuffer.mockImplementationOnce(async () => {+ owner.current = false;+ return { bytes: Buffer.from('old') };+ });+ expect((await handleRemoteMedia(URL_IMG, null)).status).toBe(502);+ expect(recordLocal).not.toHaveBeenCalled();+ expect(persistentPut).not.toHaveBeenCalled();+ });+it('peer image enters the existing cache and releases its temporary file without OSS', async () => {remoteInvoke.mockResolvedValue({ok: true,diff --git a/apps/desktop/src/main/device-link/mediaFetch.ts b/apps/desktop/src/main/device-link/mediaFetch.tsindex 567add273b..670c2e4d41 100644--- a/apps/desktop/src/main/device-link/mediaFetch.ts+++ b/apps/desktop/src/main/device-link/mediaFetch.ts@@ -512,9 +512,11 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu// cindy-media 地址=内容指纹,永不变更,是最理想的上传去重键。const cacheable = url.startsWith('xdt-image://') || url.startsWith('cindy-media://');- let st: { size: number; mtimeMs: number } | null = null;- if (cacheable) {- st = await stat(absPath);+ const versioned = !cacheable && !/^(audio|video)\//.test(+ mimeType ?? mimeOf((uploadExtHint ?? path.extname(absPath)).replace(/^\./, '').toLowerCase()),+ );+ const st = cacheable || versioned ? await stat(absPath) : null;+ if (cacheable && st) {if (!skipCache) {const hit = lookupUploadCache(cacheKey, st.size, st.mtimeMs, Date.now());if (hit) {@@ -541,7 +543,13 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu});}log.debug(`media:fetch ${url.slice(0, 40)} → ossKey=${uploaded.key} size=${uploaded.size}`);- return { ossKey: uploaded.key, mimeType: uploaded.contentType, size: uploaded.size };+ // Fallback downloads can join the same durable version cache as direct transfers.+ // A changing source remains viewable but must never be indexed under an old version.+ const afterUpload = versioned ? await stat(absPath).catch(() => null) : null;+ const version = st && afterUpload && uploaded.size === st.size+ && fileVersion(absPath, st, sourceVersion) === fileVersion(absPath, afterUpload, sourceVersion)+ ? fileVersion(absPath, st, sourceVersion) : undefined;+ return { ossKey: uploaded.key, mimeType: uploaded.contentType, size: uploaded.size, ...(version ? { version } : {}) };}export const __testing = {diff --git a/apps/desktop/src/main/device-link/remoteFileVersionCache.ts b/apps/desktop/src/main/device-link/remoteFileVersionCache.tsindex 3bc9b56d65..3c1e429e0e 100644--- a/apps/desktop/src/main/device-link/remoteFileVersionCache.ts+++ b/apps/desktop/src/main/device-link/remoteFileVersionCache.ts@@ -1,5 +1,5 @@import { createHash } from 'node:crypto';-import { promises as fs } from 'node:fs';+import { constants, promises as fs } from 'node:fs';import { validFileVersion, type DeviceFileResult } from '@cindy/device-link';import { getActiveAppSession } from '../appSessionState';import { getDbClient } from '../localDb/client/current';@@ -17,6 +17,7 @@ import {} from '../file-browser/remote-file-cache';import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './broadcast-tap';import { removeRefs } from '../cindy-media/ledger';+import { captureRemoteMediaCacheValidity, isImmutableRemoteMedia, REMOTE_MEDIA_INTEGRATION } from './remoteMediaPersistentCache';const INTEGRATION = 'remote-file';export type FileVersionMetadata = Pick<DeviceFileResult, 'version' | 'size' | 'mimeType'> & {@@ -39,11 +40,16 @@ export function remoteFileVersionCache(const source = createHash('sha256').update(JSON.stringify([session.mode, session.dataOwnerId, device, url])).digest('hex');- const key = `${INTEGRATION}:${source}:${version}`;+ // Direct and OSS image downloads share one index and one cleanup owner.+ const retained = mimeType.startsWith('image/') && isImmutableRemoteMedia(url);+ const integration = retained ? REMOTE_MEDIA_INTEGRATION : INTEGRATION;+ const key = retained ? `${integration}:${source}` : `${integration}:${source}:${version}`;+ const assertRetained = retained ? captureRemoteMediaCacheValidity() : () => {};const media = /^(image|audio|video|model)\//.test(mimeType);const db = media ? getDbClient().drizzle : undefined;const assertCurrent = () => {if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');+ assertRetained();};return {async invalidate(): Promise<void> {@@ -56,7 +62,7 @@ export function remoteFileVersionCache({hashes: [hit.hash],live: new Set(),- integration: INTEGRATION,+ integration,assertStillValid: assertCurrent,},db,@@ -74,40 +80,68 @@ export function remoteFileVersionCache(}const hit = await integrationCacheGet(key, db);assertCurrent();- if (!hit) return null;+ if (!hit || (retained && url.startsWith('cindy-media://')+ && hit.hash !== url.split('/').pop()!.split('.')[0])) return null;const stat = await fs.lstat(hit.absPath).catch(() => null);assertCurrent();- return stat?.isFile() && stat.size === size ? hit.absPath : null;+ if (!stat?.isFile() || stat.size !== size) return null;+ if (retained) {+ // A preview miss must not hit the same corrupt bytes through filePeer.+ const file = await fs.open(hit.absPath, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => null);+ if (!file) return null;+ try {+ const hash = createHash('sha256');+ for await (const chunk of file.createReadStream({ autoClose: false })) {+ assertCurrent();+ hash.update(chunk);+ }+ if (hash.digest('hex') !== hit.hash) return null;+ } finally {+ await file.close();+ }+ assertCurrent();+ }+ return hit.absPath;},- async put(file: string): Promise<void> {+ async put(file: string | Buffer): Promise<void> {assertCurrent();+ if (Buffer.isBuffer(file) && file.length !== size) return;if (!media) return writeVersionedRemoteFile(source, version, file, size, assertCurrent);// A copy that cannot fit the existing cache budget would evict everything// else and immediately be evicted itself. It remains available to its consumer.- if (size > CACHE_LIMIT_BYTES) return;+ if (!retained && size > CACHE_LIMIT_BYTES) return;// Bounded sniff; never load a large media file into main-process memory.- const handle = await fs.open(file, 'r');let verified: string | null;- try {- const probe = Buffer.alloc(Math.min(size, 4096));- const { bytesRead } = await handle.read(probe, 0, probe.length, 0);- verified = sniffMediaMime(probe.subarray(0, bytesRead), mimeType);- } finally {- await handle.close();+ if (Buffer.isBuffer(file)) {+ verified = sniffMediaMime(file.subarray(0, 4096), mimeType);+ } else {+ const handle = await fs.open(file, 'r');+ try {+ const probe = Buffer.alloc(Math.min(size, 4096));+ const { bytesRead } = await handle.read(probe, 0, probe.length, 0);+ verified = sniffMediaMime(probe.subarray(0, bytesRead), mimeType);+ } finally {+ await handle.close();+ }}assertCurrent();if (!verified || !supportedMime(verified)) return;- await integrationCachePut(+ const written = await integrationCachePut({cacheKey: key,- integration: INTEGRATION,- filePath: file,+ integration,+ ...(typeof file === 'string' ? { filePath: file } : { buffer: file }),mimeType: verified,assertStillValid: assertCurrent,},db,);assertCurrent();+ if (retained) {+ if (url.startsWith('cindy-media://') && written.hash !== url.split('/').pop()!.split('.')[0])+ await written.rollbackRef();+ return;+ }// Use the warehouse's existing byte budget. Only this integration's cache// is eligible: attachments, pinned media and other integrations stay protected.// The consumer owns the input file, not this warehouse copy. Even thediff --git a/apps/desktop/src/main/device-link/remoteMediaCacheStore.ts b/apps/desktop/src/main/device-link/remoteMediaCacheStore.tsindex 9cf821e7b6..7ac86c724d 100644Binary files a/apps/desktop/src/main/device-link/remoteMediaCacheStore.ts and b/apps/desktop/src/main/device-link/remoteMediaCacheStore.ts differdiff --git a/apps/desktop/src/main/device-link/remoteMediaPersistentCache.ts b/apps/desktop/src/main/device-link/remoteMediaPersistentCache.tsnew file mode 100644index 0000000000..655bde5d5e--- /dev/null+++ b/apps/desktop/src/main/device-link/remoteMediaPersistentCache.ts@@ -0,0 +1,103 @@+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import { constants } from 'node:fs';+import { getActiveAppSession } from '../appSessionState';+import { getDbClient } from '../localDb/client/current';+import { integrationCacheGet, integrationCachePut } from '../cindy-media/integrationCache';+import { sniffMediaMime } from '../cindy-media/sniffMediaMime';+import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './broadcast-tap';++export const REMOTE_MEDIA_INTEGRATION = 'remote-media';+let cacheGeneration = 0;+export function invalidateRemoteMediaPersistentWrites(): void {+ cacheGeneration++;+}++export function captureRemoteMediaOwner(): () => void {+ const owner = captureDataOwnerBroadcastScope();+ return () => {+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');+ };+}++export function captureRemoteMediaCacheValidity(): () => void {+ const assertOwner = captureRemoteMediaOwner();+ const generation = cacheGeneration;+ return () => {+ assertOwner();+ if (generation !== cacheGeneration) throw new Error('REMOTE_MEDIA_CACHE_CLEARED');+ };+}++/** Managed attachment identities are immutable. File-system URLs must be revalidated. */+export function isImmutableRemoteMedia(url: string): boolean {+ return (+ /^cindy-media:\/\/blobs\/[a-f0-9]{64}\.[a-z0-9]+$/.test(url) ||+ /^xdt-image:\/\/[^/?#]+\/[^/?#]+$/.test(url)+ );+}++/** Only an index adapter: bytes and references belong to the existing media warehouse.+ * No age/size eviction here. The owner explicitly clears these reusable copies in Storage.+ * Capture the database and owner before downloading so late work cannot enter a new account. */+export function remoteMediaPersistentCache(device: string, url: string) {+ if (!isImmutableRemoteMedia(url)) return null;+ const session = getActiveAppSession();+ if (!session.dataOwnerId) return null;+ const assertCurrent = captureRemoteMediaCacheValidity();+ const db = getDbClient().drizzle;+ const key = `${REMOTE_MEDIA_INTEGRATION}:${createHash('sha256')+ .update(JSON.stringify([session.mode, session.dataOwnerId, device, url]))+ .digest('hex')}`;+ return {+ async get(maxBytes: number) {+ assertCurrent();+ const hit = await integrationCacheGet(key, db);+ assertCurrent();+ if (!hit || !hit.mimeType.startsWith('image/')) return null;+ const file = await fs.open(hit.absPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const stat = await file.stat();+ if (!stat.isFile() || stat.size > maxBytes) return null;+ const bytes = Buffer.alloc(stat.size);+ let offset = 0;+ while (offset < bytes.length) {+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);+ if (!bytesRead) return null;+ offset += bytesRead;+ }+ assertCurrent();+ // A damaged cache is a miss, not an indefinitely broken image.+ if (+ bytes.length > maxBytes ||+ createHash('sha256').update(bytes).digest('hex') !== hit.hash+ )+ return null;+ return { bytes, mimeType: hit.mimeType };+ } finally {+ await file.close();+ }+ },+ async put(bytes: Buffer, mimeType: string) {+ assertCurrent();+ const verified = sniffMediaMime(bytes, mimeType);+ if (!verified?.startsWith('image/')) return;+ // Never attach bytes to a remote content hash that they do not actually match.+ if (+ url.startsWith('cindy-media://') &&+ createHash('sha256').update(bytes).digest('hex') !== url.split('/').pop()!.split('.')[0]+ )+ return;+ await integrationCachePut(+ {+ cacheKey: key,+ integration: REMOTE_MEDIA_INTEGRATION,+ buffer: bytes,+ mimeType: verified,+ assertStillValid: assertCurrent,+ },+ db,+ );+ },+ };+}diff --git a/apps/desktop/src/main/device-link/remoteMediaProtocol.ts b/apps/desktop/src/main/device-link/remoteMediaProtocol.tsindex bb8f8e0a75..068e9220ca 100644--- a/apps/desktop/src/main/device-link/remoteMediaProtocol.ts+++ b/apps/desktop/src/main/device-link/remoteMediaProtocol.ts@@ -34,10 +34,14 @@ import { DL_MEDIA_FETCH_CHANNEL } from '@cindy/device-link';import { downloadToBuffer, openMediaStream, removeRemote } from './mediaTransfer';import * as cache from './remoteMediaCacheStore';import type { RemoteMediaEntry, StreamEntry } from './remoteMediaCacheStore';+import { activeOwnerScopeKey } from '../appSessionState';+import { remoteFileVersionCache } from './remoteFileVersionCache';+import { captureRemoteMediaOwner, isImmutableRemoteMedia, remoteMediaPersistentCache } from './remoteMediaPersistentCache';const log = createLogger('device-link:remoteMediaProtocol');interface MediaFetchResult {+ version?: string;ossKey: string;mimeType: string;size: number;@@ -69,6 +73,7 @@ async function serveLocalCindyMediaBlob(origUrl: string,rangeHeader: string | null,): Promise<Response | null> {+ const assertCurrent = captureRemoteMediaOwner();let resolved: { absPath: string; mimeType: string; hash: string };try {resolved = blobStore.resolveSafe(origUrl);@@ -77,7 +82,11 @@ async function serveLocalCindyMediaBlob(}let buffer: Buffer;try {+ // Only current-account attachments may bypass the device-scoped cache index.+ if (!await ledger.hasNonCacheBlob(resolved.hash)) return null;+ assertCurrent();buffer = await fs.readFile(resolved.absPath);+ assertCurrent();} catch {return null; // 本机无此 blob:走远程取件}@@ -94,17 +103,30 @@ async function serveLocalCindyMediaBlob(const inflight = new Map<string, Promise<RemoteMediaEntry>>();function inflightKeyOf(deviceId: string, origUrl: string): string {- return `${deviceId} ${origUrl}`;+ return `${activeOwnerScopeKey()} ${deviceId} ${origUrl}`;}/** 取得缓存条目:命中直接返回,未命中向被控端取件并落缓存(并发去重)。 */async function ensureEntry(deviceId: string, origUrl: string): Promise<RemoteMediaEntry> {const hit = cache.lookup(deviceId, origUrl);- if (hit) return hit;+ // A path can change in place. Let the existing host stat/version cache validate it.+ if (hit && (hit.kind === 'stream' || isImmutableRemoteMedia(origUrl))) return hit;const k = inflightKeyOf(deviceId, origUrl);const pending = inflight.get(k);if (pending) return pending;- const p = fetchAndCache(deviceId, origUrl).finally(() => inflight.delete(k));+ const assertCurrent = captureRemoteMediaOwner();+ const p = (async () => {+ let disk: ReturnType<typeof remoteMediaPersistentCache> = null;+ try { disk = remoteMediaPersistentCache(deviceId, origUrl); } catch { /* Cache is optional. */ }+ const saved = await disk?.get(LOCAL_BUFFER_MAX).catch(() => null);+ assertCurrent();+ if (saved) return cache.recordLocal(deviceId, origUrl, saved.bytes, saved.mimeType);+ const entry = await fetchAndCache(deviceId, origUrl);+ assertCurrent();+ if (entry.kind === 'local') await disk?.put(entry.bytes, entry.mimeType).catch(() => undefined);+ assertCurrent();+ return entry;+ })().finally(() => inflight.delete(k));inflight.set(k, p);return p;}@@ -129,8 +151,14 @@ async function downloadLocalEntry(origUrl: string,fetched: MediaFetchResult,): Promise<RemoteMediaEntry> {+ const assertCurrent = captureRemoteMediaOwner();+ let versioned: ReturnType<typeof remoteFileVersionCache> = null;+ try { versioned = remoteFileVersionCache(deviceId, origUrl, fetched); } catch { /* Optional cache. */ }try {const { bytes } = await downloadToBuffer(fetched.ossKey);+ assertCurrent();+ await versioned?.put(bytes).catch(() => undefined);+ assertCurrent();return cache.recordLocal(deviceId, origUrl, bytes, fetched.mimeType);} finally {void removeRemote(fetched.ossKey);@@ -162,29 +190,35 @@ function toEntry(}async function fetchAndCache(deviceId: string, origUrl: string): Promise<RemoteMediaEntry> {+ const assertCurrent = captureRemoteMediaOwner();const fetched = await readRemoteDeviceFile(deviceId, origUrl, remoteInvoke, {maxPeerBytes: LOCAL_BUFFER_MAX,stream: true,});if ('path' in fetched) {try {+ const bytes = await fs.readFile(fetched.path);+ assertCurrent();return cache.recordLocal(deviceId,origUrl,- await fs.readFile(fetched.path),+ bytes,fetched.mimeType,);} finally {await fetched.dispose();}}+ assertCurrent();try {return await toEntry(deviceId, origUrl, fetched);} catch (err) {+ assertCurrent();// 下载失败的常见根因:被控端图片上传去重缓存返回了悬空 key(对象已被消费方用后删)。// 带 skipCache 重取一次强制重传;仍失败按原语义抛给上层(renderer 占位 + 可重试)。log.warn(`remote media download failed, retrying with skipCache: ${String(err)}`);const refetched = await invokeMediaFetch(deviceId, origUrl, true);+ assertCurrent();return toEntry(deviceId, origUrl, refetched);}}@@ -322,12 +356,15 @@ async function handleRemoteMedia(return serveSshRemoteMedia(parsed.origin, parsed.origUrl, rangeHeader);}const deviceId = parsed.origin.deviceId;+ const assertCurrent = captureRemoteMediaOwner();try {if (parsed.origUrl.startsWith('cindy-media://')) {const local = await serveLocalCindyMediaBlob(parsed.origUrl, rangeHeader);+ assertCurrent();if (local) return local;}const entry = await ensureEntry(deviceId, parsed.origUrl);+ assertCurrent();if (entry.kind === 'local') return serveLocal(entry, rangeHeader);try {return await serveStream(entry, rangeHeader, signal);@@ -380,6 +417,7 @@ async function handleRemoteMedia(// 被控端去重缓存可能把同一把 stale key 再记回缓存、覆盖掉新对象。const p = (async () => {const refetched = await invokeMediaFetch(deviceId, parsed.origUrl, true);+ assertCurrent();return toEntry(deviceId, parsed.origUrl, refetched);})().finally(() => inflight.delete(k));inflight.set(k, p);diff --git a/apps/desktop/src/main/file-browser/remote-file-cache.ts b/apps/desktop/src/main/file-browser/remote-file-cache.tsindex b7a9db3fdd..a8c7250159 100644--- a/apps/desktop/src/main/file-browser/remote-file-cache.ts+++ b/apps/desktop/src/main/file-browser/remote-file-cache.ts@@ -53,7 +53,7 @@ export async function removeVersionedRemoteFile(source: string, version: string)}export async function writeVersionedRemoteFile(- source: string, version: string, from: string, size: number, assertCurrent: () => void,+ source: string, version: string, from: string | Buffer, size: number, assertCurrent: () => void,): Promise<void> {if (size > MAX_CACHE_BYTES) return;const destination = versionedCachePath(source, version);@@ -65,7 +65,8 @@ export async function writeVersionedRemoteFile(assertCurrent();const temporary = path.join(cacheDir(), `${randomUUID()}.part`);try {- await fs.copyFile(from, temporary, constants.COPYFILE_FICLONE);+ if (typeof from === 'string') await fs.copyFile(from, temporary, constants.COPYFILE_FICLONE);+ else await fs.writeFile(temporary, from, { flag: 'wx', mode: 0o600 });if ((await fs.stat(temporary)).size !== size) return;await fs.chmod(temporary, 0o600);assertCurrent();diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex cffee832a1..9c66d54dac 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4414,6 +4414,7 @@ contextBridge.exposeInMainWorld('electronAPI', {success: boolean;error?: string;blobs: { totalCount: number; totalBytes: number; cacheCount: number; cacheBytes: number };+ remoteMedia?: { bytes: number; fileCount: number };legacy: { bytes: number; fileCount: number };fixedCaches: {legacyImages: { bytes: number; fileCount: number };@@ -4431,6 +4432,7 @@ contextBridge.exposeInMainWorld('electronAPI', {scan: (params: {draftUrls: string[];+ scope?: 'remote-media';}): Promise<{success: boolean;error?: string;@@ -4455,6 +4457,7 @@ contextBridge.exposeInMainWorld('electronAPI', {cleanup: (params: {draftUrls: string[];+ scope?: 'remote-media';zeroRefHashes: string[];evictCacheHashes: string[];deadDirNames: string[];diff --git a/apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts b/apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.tsindex 46479df093..cd5582890c 100644--- a/apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts+++ b/apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts@@ -5,6 +5,7 @@ export default {id: 'storage',order: 17,entries: [+ { id: 'settings.about.storage.remoteMediaLabel', fallbackTargetId: 'settings-panel-storage', tab: 'storage', targetId: 'settings-search-settings-about-storage-remoteMediaLabel', titleKey: 'settings.about.storage.remoteMediaLabel', sectionKey: 'settings.tabs.storage', descriptionKey: 'settings.about.storage.remoteMediaDescription' },{ id: 'storage', tab: 'storage', targetId: 'settings-panel-storage', titleKey: 'settings.tabs.storage', sectionKey: 'settings.about.storage.title' },{ id: 'settings.about.storage.databaseSectionTitle', fallbackTargetId: 'settings-panel-storage', tab: 'storage', targetId: 'settings-search-settings-about-storage-databaseSectionTitle', titleKey: 'settings.about.storage.databaseSectionTitle', sectionKey: 'settings.tabs.storage' },{ id: 'settings.about.storage.mediaSectionTitle', fallbackTargetId: 'settings-panel-storage', tab: 'storage', targetId: 'settings-search-settings-about-storage-mediaSectionTitle', titleKey: 'settings.about.storage.mediaSectionTitle', sectionKey: 'settings.tabs.storage', descriptionKey: 'settings.about.storage.mediaSectionHint' },diff --git a/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx b/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsxindex 12c6d05805..0b2a5850ae 100644--- a/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx+++ b/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx@@ -59,6 +59,7 @@ type CleanPhase =export function StorageManagementCard() {const { t } = useTranslation();+ const { confirm } = useConfirmDialog();const [stats, setStats] = useState<StatsResult | null>(null);const [databaseBytes, setDatabaseBytes] = useState<number | null>(null);const [warningThresholdGiB, setWarningThresholdGiB] = useState(10);@@ -156,6 +157,34 @@ export function StorageManagementCard() {}};+ const handleClearRemoteMedia = async () => {+ if (cleanupBusyRef.current) return;+ cleanupBusyRef.current = true;+ try {+ const api = window.electronAPI.cindyMediaStorage;+ const scan = await api.scan({ draftUrls: getAllDraftAttachmentUrls(), scope: 'remote-media' });+ if (!scan.success) throw new Error('scan failed');+ const bytes = scan.cache.evictable.reduce((sum, entry) => sum + entry.bytes, 0);+ if (!await confirm({+ title: t('settings.about.storage.remoteMediaClearTitle'),+ description: t('settings.about.storage.remoteMediaClearDescription', { size: formatBytes(bytes) }),+ confirmText: t('settings.about.storage.remoteMediaClearButton'),+ cancelText: t('settings.about.storage.cancelButton'),+ })) return;+ const result = await api.cleanup({+ scope: 'remote-media', draftUrls: getAllDraftAttachmentUrls(),+ evictCacheHashes: scan.cache.evictable.map((entry) => entry.hash),+ zeroRefHashes: [], deadDirNames: [], cleanTmpFiles: false,+ });+ toast.success(t('settings.about.storage.cleanupDoneToast', { size: formatBytes(result.freedBytes) }));+ void refreshStats();+ } catch {+ toast.error(t('settings.about.storage.cleanupFailed'));+ } finally {+ cleanupBusyRef.current = false;+ }+ };+const handleScan = async () => {if (cleanupBusyRef.current) return;cleanupBusyRef.current = true;@@ -382,6 +411,21 @@ export function StorageManagementCard() {</CardButton></div></div>+ <div aria-hidden className="h-px w-full bg-[var(--settings-theme-card-border)]" />+ <div className="flex items-center justify-between gap-3 px-[18px] py-4">+ <div className="flex min-w-0 flex-col gap-1">+ <span className="text-13 text-[var(--settings-section-sublabel)]">+ <span id="settings-search-settings-about-storage-remoteMediaLabel">{t('settings.about.storage.remoteMediaLabel')}</span>+ {' · '}{stats?.remoteMedia ? formatBytes(stats.remoteMedia.bytes) : t('settings.about.storage.unknown')}+ </span>+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">+ {t('settings.about.storage.remoteMediaDescription')}+ </p>+ </div>+ <CardButton onClick={handleClearRemoteMedia}>+ {t('settings.about.storage.remoteMediaClearButton')}+ </CardButton>+ </div></div><div className="flex items-baseline justify-between gap-3 px-0.5">diff --git a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsxindex 23b6ce2a1c..8d955aa9dc 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx@@ -135,6 +135,32 @@ beforeEach(() => {afterEach(cleanup);describe('StorageManagementCard fixed cache directories', () => {+ it('scans only remote image copies and requires confirmation before clearing that scope', async () => {+ const api = window.electronAPI.cindyMediaStorage;+ vi.mocked(api.scan).mockResolvedValue({+ success: true, zeroRef: { count: 0, bytes: 0, hashes: [], protectedCount: 0 },+ cache: { totalBytes: 12, count: 1, limitBytes: 0, excessBytes: 12,+ evictable: [{ hash: 'cached-image', ext: '.png', bytes: 12 }] },+ tmpFileCount: 0, deadDirs: [],+ });+ vi.mocked(api.cleanup).mockResolvedValue({+ freedBytes: 12, zeroRef: { deleted: 0, skipped: 0, freedBytes: 0 },+ cacheEvicted: { deleted: 1, skipped: 0, freedBytes: 12 },+ deadDirs: { removed: [], skipped: [], freedBytes: 0 }, tmpFilesRemoved: 0,+ });+ render(<StorageManagementCard />);+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.storage.remoteMediaClearButton' }));+ await screen.findByRole('alertdialog');+ expect(api.scan).toHaveBeenCalledWith({ scope: 'remote-media', draftUrls: [] });+ expect(api.cleanup).not.toHaveBeenCalled();+ const buttons = screen.getAllByRole('button', { name: 'settings.about.storage.remoteMediaClearButton' });+ fireEvent.click(buttons[buttons.length - 1]);+ await waitFor(() => expect(api.cleanup).toHaveBeenCalledWith({+ scope: 'remote-media', draftUrls: [], evictCacheHashes: ['cached-image'],+ zeroRefHashes: [], deadDirNames: [], cleanTmpFiles: false,+ }));+ });+it('renders both directory actions without scanning either directory', async () => {render(<StorageManagementCard />);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 12febe0879..fb53d820cf 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2100,6 +2100,11 @@"statsFailed": "Stats temporarily unavailable","refreshStatsButton": "Refresh storage usage","legacyUsage": "Legacy data (read-only, not part of cleanup): {{size}}",+ "remoteMediaLabel": "Remote image cache",+ "remoteMediaDescription": "Downloaded images stay on this computer for reuse after restarting Cindy.",+ "remoteMediaClearButton": "Clear remote cache",+ "remoteMediaClearTitle": "Clear remote image cache?",+ "remoteMediaClearDescription": "Free {{size}} on this computer. Images will download again when opened; original files and saved attachments are kept.","legacyImagesLabel": "Image cache directory","legacyImagesDescription": "Cindy does not scan or clean this directory automatically. Deleting files may make images in message history unavailable; review them before deleting.","legacyImagesOpenButton": "Open directory",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex bd7570c657..75529a6311 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2073,6 +2073,11 @@"statsFailed": "統計を一時的に利用できません","refreshStatsButton": "ストレージ使用量を更新","legacyUsage": "旧バージョンのデータ(読み取り専用、クリーンアップ対象外): {{size}}",+ "remoteMediaLabel": "リモート画像キャッシュ",+ "remoteMediaDescription": "ダウンロードした画像をこのコンピューターに保存し、Cindy の再起動後も再利用します。",+ "remoteMediaClearButton": "リモートキャッシュを削除",+ "remoteMediaClearTitle": "リモート画像キャッシュを削除しますか?",+ "remoteMediaClearDescription": "このコンピューターの {{size}} を解放します。次に開くと再ダウンロードします。元のファイルと保存済みの添付ファイルは保持されます。","legacyImagesLabel": "画像キャッシュディレクトリ","legacyImagesDescription": "Cindy はこのディレクトリを自動でスキャンまたはクリーンアップしません。ファイルを削除するとメッセージ履歴の画像が表示できなくなる場合があるため、内容を確認してから操作してください。","legacyImagesOpenButton": "ディレクトリを開く",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 977648c683..54dabd82d0 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2073,6 +2073,11 @@"statsFailed": "통계를 일시적으로 사용할 수 없습니다","refreshStatsButton": "저장 공간 사용량 새로 고침","legacyUsage": "이전 버전 데이터(읽기 전용, 정리 대상 아님): {{size}}",+ "remoteMediaLabel": "원격 이미지 캐시",+ "remoteMediaDescription": "다운로드한 이미지를 이 컴퓨터에 보관하여 Cindy를 다시 시작한 후에도 재사용합니다.",+ "remoteMediaClearButton": "원격 캐시 삭제",+ "remoteMediaClearTitle": "원격 이미지 캐시를 삭제할까요?",+ "remoteMediaClearDescription": "이 컴퓨터에서 {{size}}를 확보합니다. 다시 열면 다운로드하며, 원본 파일과 저장된 첨부 파일은 유지됩니다.","legacyImagesLabel": "이미지 캐시 디렉터리","legacyImagesDescription": "Cindy는 이 디렉터리를 자동으로 검사하거나 정리하지 않습니다. 파일을 삭제하면 메시지 기록의 이미지가 표시되지 않을 수 있으므로 확인 후 작업해 주세요.","legacyImagesOpenButton": "디렉터리 열기",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex f808e8269e..facb82a0c9 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2073,6 +2073,11 @@"statsFailed": "统计暂时不可用","refreshStatsButton": "刷新存储占用","legacyUsage": "旧版本数据(只读,不参与清理):{{size}}",+ "remoteMediaLabel": "远程图片缓存",+ "remoteMediaDescription": "下载过的图片保留在这台电脑上,重启 Cindy 后仍可复用。",+ "remoteMediaClearButton": "清理远程缓存",+ "remoteMediaClearTitle": "清理远程图片缓存?",+ "remoteMediaClearDescription": "释放本机 {{size}}。再次查看时会重新下载,原始文件和已保存的附件会保留。","legacyImagesLabel": "图片缓存目录","legacyImagesDescription": "Cindy 不会自动扫描或清理此目录。删除文件后,历史消息中的图片可能无法显示,请自行确认后操作。","legacyImagesOpenButton": "打开目录",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 344cb28aa9..f084422158 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -2073,6 +2073,11 @@"statsFailed": "統計暫時無法使用","refreshStatsButton": "重新整理儲存空間用量","legacyUsage": "舊版本資料(只讀,不參與清理):{{size}}",+ "remoteMediaLabel": "遠端圖片快取",+ "remoteMediaDescription": "下載過的圖片保留在這台電腦上,重新啟動 Cindy 後仍可重複使用。",+ "remoteMediaClearButton": "清理遠端快取",+ "remoteMediaClearTitle": "清理遠端圖片快取?",+ "remoteMediaClearDescription": "釋放本機 {{size}}。再次檢視時會重新下載,原始檔案和已儲存的附件會保留。","legacyImagesLabel": "圖片快取目錄","legacyImagesDescription": "Cindy 不會自動掃描或清理此目錄。刪除檔案後,歷史訊息中的圖片可能無法顯示,請自行確認後操作。","legacyImagesOpenButton": "開啟目錄",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex e66c935d3c..2143ac9748 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3778,6 +3778,7 @@ interface ElectronAPI {success: boolean;error?: string;blobs: { totalCount: number; totalBytes: number; cacheCount: number; cacheBytes: number };+ remoteMedia?: { bytes: number; fileCount: number };legacy: { bytes: number; fileCount: number };fixedCaches: {legacyImages: { bytes: number; fileCount: number };@@ -3792,7 +3793,7 @@ interface ElectronAPI {eligible: boolean;}>;}>;- scan: (params: { draftUrls: string[] }) => Promise<{+ scan: (params: { draftUrls: string[]; scope?: 'remote-media' }) => Promise<{success: boolean;error?: string;zeroRef: { count: number; bytes: number; hashes: string[]; protectedCount: number };@@ -3815,6 +3816,7 @@ interface ElectronAPI {}>;cleanup: (params: {draftUrls: string[];+ scope?: 'remote-media';zeroRefHashes: string[];evictCacheHashes: string[];deadDirNames: string[];diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex ce925360ae..132cf48ed0 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -81,6 +81,13 @@引用与 pin,不能清理聊天附件或其他集成的共享字节。其他媒体清理维持原手动流程。普通 HTML 等非媒体仍走 `remote-file-cache`。完整身份、复验与平台清理策略见[`protocol-compatibility.md`](protocol-compatibility.md)「远程文件连接复用与版本缓存」。+- 桌面聊天的不可变远程图片通过 `device-link/remoteMediaPersistentCache.ts` 复用媒体总仓,+ `remote-media` 索引包含账号、来源设备和原始地址。先查内存、再查磁盘,缓存命中不取件;+ 重启和断连不清理,不增加自动到期或容量淘汰。设置中的「远程图片缓存」复用账本扫描和+ 条件删除,只清该命名空间独占的缓存,保护草稿、已保存附件及其他集成共享字节。+ 普通路径不按 URL 永久缓存:继续由主机复核版本,完整中转下载也可写入已有版本缓存;+ 音视频仍走流式播放。旧主机不返回版本时不把可修改文件登记为长期有效。+ 回归见 `remoteMediaPersistentCache.test.ts`、`remoteMediaProtocol.test.ts` 与 `storageIpc.test.ts`。- 零引用入仓只适用于已有草稿或生成结果提交链路。新增零引用窗口时,必须证明内容在消息落库前不会被回收,并用测试覆盖成功、失败、取消和重试。- 三款官方壁纸改为 OSS/CDN 按需分发(2026-10-15 用户裁决,替代此前全部随包的决定)。