Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(desktop): make wallpaper lifecycle client-owned
DavidShen16498dfb27a7
diff --git a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.tsindex 73d4ecccd3..9544dcacc5 100644--- a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts+++ b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts@@ -65,13 +65,13 @@ const persisted = {};describe('appearance settings IPC authorization', () => {- it('authorizes the CDN video request and rechecks owner after download', async () => {+ it('authorizes the CDN request and keeps it valid across account switches', async () => {const handler = mocks.ipcHandle.mock.calls.find(([name]) => name === 'appearance-settings:ensure-wallpaper-video')?.[1];mocks.ensureVideo.mockResolvedValueOnce(null);expect(await handler({}, 'cindy-window')).toBeNull();expect(mocks.assertTrustedAppRendererEvent).toHaveBeenCalled();- mocks.ensureVideo.mockImplementationOnce(async () => { mocks.owner = 'owner-b:2'; return 'old-owner-url'; });- await expect(handler({}, 'cindy-window')).rejects.toThrow('Wallpaper owner changed');+ mocks.ensureVideo.mockImplementationOnce(async () => { mocks.owner = 'owner-b:2'; return 'client-video-url'; });+ expect(await handler({}, 'cindy-window')).toBe('client-video-url');});it('rejects an untrusted CDN request before starting a download', async () => {mocks.assertTrustedAppRendererEvent.mockImplementation(() => { throw new Error('untrusted'); });@@ -80,31 +80,29 @@ describe('appearance settings IPC authorization', () => {expect(mocks.ensureVideo).not.toHaveBeenCalled();});it.each(['appearance-settings:import-wallpaper', 'appearance-settings:remove-wallpaper'])(- 'rejects %s when the owner changes during module loading',+ 'allows %s when the account changes during module loading',async (channel) => {const handler = mocks.ipcHandle.mock.calls.find(([name]) => name === channel)?.[1];const pending = handler({ sender: {} });mocks.owner = 'owner-b:2';- await expect(pending).rejects.toThrow('Unable to');- expect(mocks.importWallpaper).not.toHaveBeenCalled();- expect(mocks.removeWallpaper).not.toHaveBeenCalled();+ await expect(pending).resolves.not.toBeUndefined();+ expect(channel.endsWith('import-wallpaper') ? mocks.importWallpaper : mocks.removeWallpaper).toHaveBeenCalledOnce();},);it.each(['appearance-settings:import-wallpaper', 'appearance-settings:remove-wallpaper'])(- 'rejects %s while the owner boundary is pending',+ 'allows %s while account teardown is pending',async (channel) => {const handler = mocks.ipcHandle.mock.calls.find(([name]) => name === channel)?.[1];const pending = handler({ sender: {} });mocks.boundaryPending = true;- await expect(pending).rejects.toThrow('Unable to');- expect(mocks.importWallpaper).not.toHaveBeenCalled();- expect(mocks.removeWallpaper).not.toHaveBeenCalled();+ await expect(pending).resolves.not.toBeUndefined();+ expect(channel.endsWith('import-wallpaper') ? mocks.importWallpaper : mocks.removeWallpaper).toHaveBeenCalledOnce();},);it('does not let a renderer inject a path or media URL through the generic preference channel', () => {expect(__testing.parsePatch({ wallpaperId: 'custom' })).toEqual({ wallpaperId: 'custom' });expect(() =>- __testing.parsePatch({ customWallpaperUrl: `cindy-media://blobs/${'a'.repeat(64)}.webp` }),+ __testing.parsePatch({ customWallpaperUrl: `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp` }),).toThrow('unknown appearance field');expect(() => __testing.parsePatch({ wallpaperPath: '/private.png' })).toThrow('unknown appearance field',@@ -195,7 +193,7 @@ describe('appearance settings IPC authorization', () => {it('withholds private media from utility bootstrap and broadcasts, while retaining it for app content', async () => {const settings = normalizeAppearanceSettings({wallpaperId: 'custom',- customWallpaperUrl: `cindy-media://blobs/${'a'.repeat(64)}.webp`,+ customWallpaperUrl: `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp`,});const utility = { isDestroyed: () => false, webContents: { isDestroyed: () => false, send: vi.fn() } };const content = { isDestroyed: () => false, webContents: { isDestroyed: () => false, send: vi.fn(), setZoomFactor: vi.fn() } };diff --git a/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts b/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.tsindex ca94df8bd5..ad30b905d4 100644--- a/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts+++ b/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts@@ -25,8 +25,8 @@ import {writeAppearanceSettingsPatch,} from '../appearance-settings-store';-const urlA = `cindy-media://blobs/${'a'.repeat(64)}.webp`;-const urlB = `cindy-media://blobs/${'b'.repeat(64)}.webp`;+const urlA = `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp`;+const urlB = `cindy-media://client-wallpaper/${'b'.repeat(64)}.webp`;beforeEach(() => {h.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wallpaper-shared-'));h.owner = 'a';@@ -34,11 +34,6 @@ beforeEach(() => {});afterEach(() => fs.rmSync(h.dir, { recursive: true, force: true }));-function seedLegacy(owner: string, url: string) {- fs.mkdirSync(path.join(h.dir, owner), { recursive: true });- fs.writeFileSync(path.join(h.dir, owner, 'custom-wallpaper.json'), JSON.stringify({ url }));-}-describe('profile-wide wallpaper preference', () => {it('shares selection, replacement and reset across accounts, including sign-out', async () => {await customWallpaperStore.writePatchAtomic({ url: urlA });@@ -70,34 +65,7 @@ describe('profile-wide wallpaper preference', () => {expect(readAppearanceSettings().wallpaperId).toBe('cindy-dream');});- it('adopts the active preview image once, and never resurrects removed images from another account', async () => {- seedLegacy('a', urlA);- seedLegacy('b', urlB);- await writeAppearanceSettingsPatch({ wallpaperId: 'custom' });- expect(readAppearanceSettings()).toMatchObject({- wallpaperId: 'custom',- customWallpaperUrl: urlA,- });- h.owner = 'b';- expect(readCustomWallpaperUrl()).toBe(urlA);- await customWallpaperStore.writePatchAtomic({ url: '' }, { preserveDefaults: true });- h.owner = 'a';- expect(readAppearanceSettings()).toMatchObject({ wallpaperId: 'none', customWallpaperUrl: '' });- expect(JSON.parse(fs.readFileSync(path.join(h.dir, 'custom-wallpaper.json'), 'utf8'))).toEqual({- url: '',- });- });-- it('waits for a settled active account before adopting a preview image', () => {- seedLegacy('a', urlA);- h.pending = true;- expect(readCustomWallpaperUrl()).toBe('');- h.pending = false;- expect(readCustomWallpaperUrl()).toBe(urlA);- });-- it('preserves unreadable shared settings instead of replacing them with a legacy image', async () => {- seedLegacy('a', urlA);+ it('preserves unreadable shared settings until an explicit reset', async () => {const target = path.join(h.dir, 'custom-wallpaper.json');fs.writeFileSync(target, '{broken');expect(readCustomWallpaperUrl()).toBe('');diff --git a/apps/desktop/src/main/__tests__/customWallpaper.test.ts b/apps/desktop/src/main/__tests__/customWallpaper.test.tsindex 045cc90ffd..b34b27d426 100644--- a/apps/desktop/src/main/__tests__/customWallpaper.test.ts+++ b/apps/desktop/src/main/__tests__/customWallpaper.test.ts@@ -1,158 +1,175 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import sharp from 'sharp';-const h = vi.hoisted(() => ({- picker: vi.fn(),- read: vi.fn(),- ingest: vi.fn(),- write: vi.fn(),- remove: vi.fn(),- removeId: vi.fn(),- keep: vi.fn(),- valid: vi.fn(),- snapshot: { client: { drizzle: {} }, userId: 'test', clientEpoch: 1 },+const h = vi.hoisted(() => ({ dir: '', picker: vi.fn(), account: 'a', db: vi.fn() }));+vi.mock('electron', () => ({+ app: { getPath: () => h.dir },+ dialog: { showOpenDialog: h.picker },}));-vi.mock('electron', () => ({ dialog: { showOpenDialog: h.picker } }));-vi.mock('../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));-vi.mock('../utils/readBoundedFile.js', () => ({ readBoundedFileNoFollow: h.read }));-vi.mock('../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => h.snapshot }));-vi.mock('../appSessionState.js', () => ({ ownerScopedUserDataPath: () => `test-lock-${h.snapshot.userId}` }));-vi.mock('../device-link/crossProcessLock.js', () => ({- withCrossProcessLock: (_p: string, _o: unknown, fn: Function) => fn({ held: true }),+vi.mock('../localDb/client/current.js', () => ({+ getDbClient: h.db,+ getCurrentDbClientSnapshot: h.db,}));-vi.mock('../cindy-media/refCompensationJournal.js', () => ({- captureMediaRefCompensationScope: () => ({ assertStillValid: h.valid }),-}));-vi.mock('../cindy-media/ingest.js', () => ({ ingestMedia: h.ingest }));-vi.mock('../cindy-media/ledger.js', () => ({- removeRefById: h.removeId,- removeRefs: h.remove,- removeRefsExceptId: h.keep,-}));-vi.mock('../custom-wallpaper-settings.js', () => ({- customWallpaperStore: { writePatchAtomic: h.write },+vi.mock('../appSessionState.js', () => ({+ getActiveAppSession: () => {+ throw new Error('Wallpaper must not read the account');+ },+ activeOwnerScopeKey: () => {+ throw new Error('Wallpaper must not read the account');+ },}));import {importCustomWallpaper,- prepareWallpaperImage,removeCustomWallpaper,+ prepareWallpaperImage,} from '../custom-wallpaper';+import { customWallpaperStore, readCustomWallpaperUrl } from '../custom-wallpaper-settings';+import {+ writeBlob,+ readFile,+ readClientWallpaperFile,+ listBlobFiles,+} from '../cindy-media/blobStore';+import * as recycler from '../cindy-media/recycler';-const url = `cindy-media://blobs/${'a'.repeat(64)}.webp`;-beforeEach(async () => {- vi.resetAllMocks();- h.snapshot = { client: { drizzle: {} }, userId: 'test', clientEpoch: 1 };- h.picker.mockResolvedValue({ canceled: false, filePaths: ['chosen-image'] });- h.read.mockResolvedValue(- await sharp({ create: { width: 8, height: 4, channels: 3, background: 'blue' } })- .png()- .toBuffer(),- );- h.ingest.mockResolvedValue({ url, hash: 'a'.repeat(64), refIds: ['new-ref'] });+beforeEach(() => {+ h.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'client-wallpaper-test-'));+ h.account = 'a';+ h.db.mockImplementation(() => {+ throw new Error('No account database');+ });+ h.picker.mockReset();+});+afterEach(() => {+ expect(h.db).not.toHaveBeenCalled();+ vi.restoreAllMocks();+ fs.rmSync(h.dir, { recursive: true, force: true });});-describe('custom wallpaper import', () => {- it('lets another owner remove the shared image while the old owner picker remains open', async () => {- let closePicker!: (value: { canceled: boolean; filePaths: string[] }) => void;- h.picker.mockReturnValueOnce(new Promise(resolve => { closePicker = resolve; }));- const oldImport = importCustomWallpaper({} as never);- const rejected = expect(oldImport).rejects.toThrow('Wallpaper owner changed');- await vi.waitFor(() => expect(h.picker).toHaveBeenCalledOnce());- h.snapshot = { client: { drizzle: {} }, userId: 'other', clientEpoch: 2 };- const removal = removeCustomWallpaper();- try {- await vi.waitFor(() => expect(h.write).toHaveBeenCalledOnce());- } finally {- closePicker({ canceled: true, filePaths: [] });- await rejected;- await removal;- }- expect(h.ingest).not.toHaveBeenCalled();- expect(h.remove).toHaveBeenCalledWith(expect.anything(), h.snapshot.client.drizzle);- });+async function selectImage(color = 'blue') {+ const bytes = await sharp({ create: { width: 8, height: 4, channels: 3, background: color } })+ .png()+ .toBuffer();+ const file = path.join(h.dir, color + '.png');+ fs.writeFileSync(file, bytes);+ h.picker.mockResolvedValue({ canceled: false, filePaths: [file] });+ return bytes;+}+const parent = {} as never;- it('serializes operations for the same owner until their picker closes', async () => {- let closePicker!: (value: { canceled: boolean; filePaths: string[] }) => void;- h.picker.mockReturnValueOnce(new Promise(resolve => { closePicker = resolve; }));- const importing = importCustomWallpaper({} as never);- await vi.waitFor(() => expect(h.picker).toHaveBeenCalledOnce());- const removal = removeCustomWallpaper();- await Promise.resolve();- expect(h.write).not.toHaveBeenCalled();- closePicker({ canceled: true, filePaths: [] });- await importing;- await removal;- expect(h.write).toHaveBeenCalledOnce();- });- it('decodes and pins the image before publishing, then removes only older wallpaper refs', async () => {- expect(await importCustomWallpaper({} as never)).toBe(true);- expect(h.ingest).toHaveBeenCalledWith(- expect.objectContaining({- mimeType: 'image/webp',- isCache: false,- refs: [{ refKind: 'import', refId: 'desktop-custom-wallpaper', originKind: 'user' }],- assertStillValid: expect.any(Function),- }),- h.snapshot.client.drizzle,- );- const metadata = await sharp(h.ingest.mock.calls[0][0].buffer).metadata();- expect(metadata).toMatchObject({ format: 'webp', width: 8, height: 4 });- expect(metadata.exif).toBeUndefined();- expect(h.write).toHaveBeenCalledWith({ url });- expect(h.keep).toHaveBeenCalledWith(- { refKind: 'import', refId: 'desktop-custom-wallpaper', keepId: 'new-ref' },- h.snapshot.client.drizzle,+describe('client-owned custom wallpaper lifecycle', () => {+ it('imports without a database, then replaces and removes across account switches without touching identical chat bytes', async () => {+ const original = await selectImage();+ const chat = await writeBlob({+ buffer: await prepareWallpaperImage(original),+ mimeType: 'image/webp',+ });+ expect(await importCustomWallpaper(parent)).toBe(true);+ const first = readCustomWallpaperUrl();+ expect(first).toContain('cindy-media://client-wallpaper/');+ expect((await readClientWallpaperFile(first)).buffer).toEqual(+ (await readFile(chat.url)).buffer,);- expect(h.ingest.mock.invocationCallOrder[0]).toBeLessThan(h.write.mock.invocationCallOrder[0]);- expect(h.write.mock.invocationCallOrder[0]).toBeLessThan(h.keep.mock.invocationCallOrder[0]);- });- it('cancels without changing the preference or media', async () => {- h.picker.mockResolvedValue({ canceled: true, filePaths: [] });- expect(await importCustomWallpaper({} as never)).toBe(false);- expect(h.read).not.toHaveBeenCalled();- expect(h.write).not.toHaveBeenCalled();+ h.account = 'b';+ await selectImage('red');+ await importCustomWallpaper(parent);+ await expect(readClientWallpaperFile(first)).rejects.toThrow();+ const second = readCustomWallpaperUrl();+ expect(second).not.toBe(first);+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(1);+ h.account = ''; // Signed out: removing the client preference still works.+ await removeCustomWallpaper();+ expect(readCustomWallpaperUrl()).toBe('');+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(0);+ expect((await readFile(chat.url)).buffer).toEqual(await prepareWallpaperImage(original));+ await removeCustomWallpaper(); // Idempotent, with no owner reference to release.});- it('rejects invalid or unsupported files without publishing', async () => {- h.read.mockResolvedValue(- Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"></svg>'),- );- await expect(importCustomWallpaper({} as never)).rejects.toThrow('INVALID_PARAMS');- expect(h.ingest).not.toHaveBeenCalled();- await expect(prepareWallpaperImage(Buffer.from('not an image'))).rejects.toThrow(- 'INVALID_PARAMS',++ it('allows remove while a picker is open and publishes the later choice even after switching accounts', async () => {+ await selectImage();+ await importCustomWallpaper(parent);+ await selectImage('red');+ const file = path.join(h.dir, 'red.png');+ let close!: (value: unknown) => void;+ h.picker.mockReturnValueOnce(+ new Promise((resolve) => {+ close = resolve;+ }),);- h.read.mockResolvedValue(null);- await expect(importCustomWallpaper({} as never)).rejects.toThrow('INVALID_PARAMS');+ const pending = importCustomWallpaper(parent);+ h.account = 'b';+ await removeCustomWallpaper();+ expect(readCustomWallpaperUrl()).toBe('');+ close({ canceled: false, filePaths: [file] });+ expect(await pending).toBe(true);+ expect(readCustomWallpaperUrl()).not.toBe('');});- it('compensates only the new reference when saving fails', async () => {- h.write.mockRejectedValue(new Error('disk'));- await expect(importCustomWallpaper({} as never)).rejects.toThrow('disk');- expect(h.removeId).toHaveBeenCalledWith('new-ref', h.snapshot.client.drizzle);- expect(h.keep).not.toHaveBeenCalled();++ it('serializes concurrent publications and retains only the final client reference', async () => {+ await selectImage();+ const a = path.join(h.dir, 'blue.png');+ await selectImage('red');+ const b = path.join(h.dir, 'red.png');+ h.picker.mockResolvedValueOnce({ canceled: false, filePaths: [a] });+ h.picker.mockResolvedValueOnce({ canceled: false, filePaths: [b] });+ await Promise.all([importCustomWallpaper(parent), importCustomWallpaper(parent)]);+ const current = readCustomWallpaperUrl();+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(1);+ expect((await readClientWallpaperFile(current)).buffer.length).toBeGreaterThan(0);});- it('does not clear a successfully published image if old-reference cleanup fails', async () => {- h.keep.mockRejectedValue(new Error('db'));- expect(await importCustomWallpaper({} as never)).toBe(true);- expect(h.removeId).not.toHaveBeenCalled();++ it('keeps the published image after save failure and collects the unused bytes on the next successful operation', async () => {+ await selectImage();+ await importCustomWallpaper(parent);+ const first = readCustomWallpaperUrl();+ await selectImage('red');+ vi.spyOn(customWallpaperStore, 'writePatchAtomic').mockRejectedValueOnce(new Error('disk'));+ await expect(importCustomWallpaper(parent)).rejects.toThrow('disk');+ expect(readCustomWallpaperUrl()).toBe(first);+ await expect(readClientWallpaperFile(first)).resolves.toBeDefined();+ await removeCustomWallpaper();+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(0);});- it('rejects an owner switch while the picker is open', async () => {- h.picker.mockImplementation(async () => {- h.valid.mockImplementation(() => {- throw new Error('owner changed');- });- return { canceled: false, filePaths: ['chosen-image'] };- });- await expect(importCustomWallpaper({} as never)).rejects.toThrow('owner changed');- expect(h.read).not.toHaveBeenCalled();- expect(h.ingest).not.toHaveBeenCalled();++ it('does not recycle files when settings cannot be parsed or removal cannot be saved', async () => {+ await selectImage();+ await importCustomWallpaper(parent);+ const first = readCustomWallpaperUrl();+ fs.writeFileSync(path.join(h.dir, 'custom-wallpaper.json'), '{broken');+ await selectImage('red');+ await expect(importCustomWallpaper(parent)).rejects.toThrow('unreadable');+ await expect(readClientWallpaperFile(first)).resolves.toBeDefined();+ vi.spyOn(customWallpaperStore, 'resetAtomic').mockRejectedValueOnce(new Error('disk'));+ await expect(removeCustomWallpaper()).rejects.toThrow('disk');+ await expect(readClientWallpaperFile(first)).resolves.toBeDefined();+ await removeCustomWallpaper();+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(0);});- it('forgets the preference before removing its references', async () => {++ it('retains a successful publication when recycling fails and retries on the next removal', async () => {+ await selectImage();+ await importCustomWallpaper(parent);+ await selectImage('red');+ vi.spyOn(recycler, 'recycleClientWallpapers').mockRejectedValueOnce(new Error('busy'));+ await importCustomWallpaper(parent);+ await expect(readClientWallpaperFile(readCustomWallpaperUrl())).resolves.toBeDefined();await removeCustomWallpaper();- expect(h.write).toHaveBeenCalledWith({ url: '' }, { preserveDefaults: true });- expect(h.write.mock.invocationCallOrder[0]).toBeLessThan(h.remove.mock.invocationCallOrder[0]);- h.write.mockRejectedValue(new Error('disk'));- h.remove.mockClear();- await expect(removeCustomWallpaper()).rejects.toThrow('disk');- expect(h.remove).not.toHaveBeenCalled();+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(0);+ });++ it('cancels and rejects invalid input without changing the current image', async () => {+ await selectImage();+ await importCustomWallpaper(parent);+ const original = readCustomWallpaperUrl();+ h.picker.mockResolvedValueOnce({ canceled: true, filePaths: [] });+ expect(await importCustomWallpaper(parent)).toBe(false);+ fs.writeFileSync(path.join(h.dir, 'blue.png'), 'invalid');+ await expect(importCustomWallpaper(parent)).rejects.toThrow('INVALID_PARAMS');+ expect(readCustomWallpaperUrl()).toBe(original);+ await expect(prepareWallpaperImage(Buffer.from('<svg/>'))).rejects.toThrow('INVALID_PARAMS');+ await expect(prepareWallpaperImage(Buffer.alloc(0))).rejects.toThrow('INVALID_PARAMS');});});diff --git a/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts b/apps/desktop/src/main/__tests__/wallpaperVideo.test.tsindex 0c4d8824d5..25b568273c 100644--- a/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts+++ b/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts@@ -13,22 +13,29 @@ vi.mock('../../shared/wallpaper-video-manifest.json', () => ({ default: {vi.mock('../appSessionState.js', () => ({ activeOwnerScopeKey: () => m.owner, isAppSessionBoundaryPending: () => m.boundary }));vi.mock('../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => m.snapshot }));vi.mock('../cindy-media/refCompensationJournal.js', () => ({ captureMediaRefCompensationScope: () => ({ assertStillValid: m.assert }) }));-vi.mock('../cindy-media/ingest.js', () => ({ ingestMedia: m.ingest }));-vi.mock('../cindy-media/ledger.js', () => ({ getIntegrationCacheHash: m.cached, touchBlob: m.touch, removeRefsExceptId: m.remove }));-vi.mock('../cindy-media/blobStore.js', () => ({ resolveHashRef: () => ({ absPath: '/safe/video.mp4' }) }));+vi.mock('../cindy-media/ingest.js', () => ({ ingestClientWallpaper: m.ingest }));+vi.mock('../cindy-media/ledger.js', () => ({ getIntegrationCacheHash: m.cached, touchBlob: m.touch }));+vi.mock('../cindy-media/blobStore.js', () => ({+ resolveHashRef: () => ({ absPath: '/safe/video.mp4' }),+ blobUrl: (hash: string, ext: string) => 'cindy-media://client-wallpaper/' + hash + ext,+}));+vi.mock('../cindy-media/clientWallpaperLock.js', () => ({ withClientWallpaperLock: (action: () => Promise<unknown>) => action() }));+vi.mock('../cindy-media/recycler.js', () => ({ recycleClientWallpapers: m.remove }));vi.mock('../utils/readBoundedFile.js', () => ({ readBoundedFileNoFollow: m.read }));vi.mock('../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://cdn.example/cindy' }));vi.mock('../maker-host/outbound-fetch.js', () => ({ guardedOutboundFetch: m.fetch }));-import { ensureWallpaperVideo, matchesWallpaperVideo } from '../wallpaper-video';+import { ensureWallpaperVideo, matchesWallpaperVideo, __testing } from '../wallpaper-video';const hash = createHash('sha256').update('abc').digest('hex');-const url = 'cindy-media://blobs/' + hash + '.mp4';+const url = 'cindy-media://client-wallpaper/' + hash + '.mp4';beforeEach(() => {vi.clearAllMocks();+ __testing.reset();m.snapshot = { client: { drizzle: {} } };m.owner = 'one'; m.boundary = false;m.cached.mockResolvedValue(null); m.read.mockResolvedValue(null);m.ingest.mockResolvedValue({ url, refIds: ['ref-1'] });+ m.remove.mockResolvedValue(undefined);m.fetch.mockImplementation(async () => ({ response: new Response('abc'), release: m.release }));});@@ -47,19 +54,20 @@ describe('optional CDN wallpaper video', () => {expect(matchesWallpaperVideo(Buffer.from('abc'), { bytes: 3, sha256: hash })).toBe(true);expect(matchesWallpaperVideo(Buffer.from('abd'), { bytes: 3, sha256: hash })).toBe(false);});- it('downloads once for concurrent windows, verifies and ingests a reclaimable cache reference', async () => {+ it('downloads once for concurrent windows and publishes a client-owned video', async () => {const result = await Promise.all([ensureWallpaperVideo('cindy-window'), ensureWallpaperVideo('cindy-window')]);expect(result).toEqual([url, url]);expect(m.fetch).toHaveBeenCalledOnce();expect(m.fetch.mock.calls[0][0]).toBe('https://cdn.example/cindy/wallpapers/' + hash + '.mp4');- expect(m.ingest).toHaveBeenCalledWith(expect.objectContaining({ isCache: true, refs: [expect.objectContaining({ refKind: 'integration-cache' })] }), m.snapshot.client.drizzle);+ expect(m.ingest).toHaveBeenCalledWith({ buffer: Buffer.from('abc'), mimeType: 'video/mp4' });+ expect(m.remove).toHaveBeenCalledWith([url], '.mp4');expect(m.release).toHaveBeenCalledOnce();});it('validates and reuses cached media offline without adding references', async () => {m.cached.mockResolvedValue(hash); m.read.mockResolvedValue(Buffer.from('abc'));expect(await ensureWallpaperVideo('cindy-window')).toBe(url);expect(m.fetch).not.toHaveBeenCalled(); expect(m.ingest).not.toHaveBeenCalled();- expect(m.touch).toHaveBeenCalledWith(hash, m.snapshot.client.drizzle);+ expect(m.touch).not.toHaveBeenCalled();});it.each([null, Buffer.from('bad')])('redownloads a missing or damaged cache', async bytes => {m.cached.mockResolvedValue(hash); m.read.mockResolvedValue(bytes);@@ -77,17 +85,15 @@ describe('optional CDN wallpaper video', () => {expect(m.fetch).toHaveBeenCalledOnce(); expect(m.ingest).not.toHaveBeenCalled();if (reason !== 'offline') expect(m.release).toHaveBeenCalledOnce();});- it('does not fetch during an owner transition or ingest a download after a switch', async () => {+ it('shares downloads during account transitions without an account database', async () => {m.boundary = true;- expect(await ensureWallpaperVideo('cindy-window')).toBeNull();- expect(m.fetch).not.toHaveBeenCalled();- m.boundary = false;m.fetch.mockImplementation(async () => {m.owner = 'two';return { response: new Response('abc'), release: m.release };});- expect(await ensureWallpaperVideo('cindy-window')).toBeNull();- expect(m.ingest).not.toHaveBeenCalled();+ expect(await ensureWallpaperVideo('cindy-window')).toBe(url);+ expect(m.ingest).toHaveBeenCalledOnce();+ expect(m.cached).not.toHaveBeenCalled();expect(m.release).toHaveBeenCalledOnce();});});diff --git a/apps/desktop/src/main/appearance-settings-ipc.ts b/apps/desktop/src/main/appearance-settings-ipc.tsindex c830ab022a..cc90ced83a 100644--- a/apps/desktop/src/main/appearance-settings-ipc.ts+++ b/apps/desktop/src/main/appearance-settings-ipc.ts@@ -1,6 +1,5 @@import { BrowserWindow, ipcMain } from 'electron';import { extractIpcError } from '../shared/ipcError.js';-import { activeOwnerScopeKey, isAppSessionBoundaryPending } from './appSessionState.js';import {APPEARANCE_LIMITS,@@ -34,17 +33,6 @@ export const APPEARANCE_SETTINGS_CHANGED_CHANNEL = 'appearance-settings:changed'let registered = false;-function captureWallpaperOwner(): () => void {- const owner = activeOwnerScopeKey();- const assertValid = () => {- if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner) {- throwIpcError('INTERNAL', 'Wallpaper owner changed');- }- };- assertValid();- return assertValid;-}-export function registerAppearanceSettingsIpc(): void {if (registered) return;registered = true;@@ -67,11 +55,8 @@ export function registerAppearanceSettingsIpc(): void {// Local Desktop appearance only: no remote allowlist and no renderer-supplied path.ipcMain.handle('appearance-settings:ensure-wallpaper-video', async (event, id: unknown) => {assertTrustedAppRendererEvent(event);- const assertOwner = captureWallpaperOwner();const { ensureWallpaperVideo } = await import('./wallpaper-video.js');- assertOwner();const result = await ensureWallpaperVideo(id);- assertOwner();return result;});@@ -79,12 +64,9 @@ export function registerAppearanceSettingsIpc(): void {assertTrustedAppRendererEvent(event);const parent = BrowserWindow.fromWebContents(event.sender);if (!parent) throwIpcError('INVALID_PARAMS', 'Wallpaper picker requires an application window');- const assertOwner = captureWallpaperOwner();try {const { importCustomWallpaper } = await import('./custom-wallpaper.js');- assertOwner();if (!(await importCustomWallpaper(parent))) return null;- assertOwner();const settings = readAppearanceSettings();broadcast(settings);return settings;@@ -98,12 +80,9 @@ export function registerAppearanceSettingsIpc(): void {ipcMain.handle('appearance-settings:remove-wallpaper', async (event) => {assertTrustedAppRendererEvent(event);- const assertOwner = captureWallpaperOwner();try {const { removeCustomWallpaper } = await import('./custom-wallpaper.js');- assertOwner();await removeCustomWallpaper();- assertOwner();const settings = readAppearanceSettings();broadcast(settings);return settings;@@ -157,7 +136,7 @@ export async function updatePersistedWindowZoom(delta: number | null): Promise<Areturn settings;}-// A font/theme reader is not a grant to the owner's private media capability.+// A font/theme reader is not a grant to the client's custom media capability.function appearanceForWindow(settings: AppearanceSettings, win: BrowserWindow | null): AppearanceSettings {if (isAppContentWindow(win)) return settings;const { customWallpaperUrl: _privateUrl, ...publicSettings } = settings;diff --git a/apps/desktop/src/main/cindy-media/__tests__/clientWallpaperMedia.test.ts b/apps/desktop/src/main/cindy-media/__tests__/clientWallpaperMedia.test.tsnew file mode 100644index 0000000000..65e4214eaa--- /dev/null+++ b/apps/desktop/src/main/cindy-media/__tests__/clientWallpaperMedia.test.ts@@ -0,0 +1,134 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ dir: '',+ handle: vi.fn(),+ touch: vi.fn(),+ record: vi.fn(),+ ref: vi.fn(),+}));+vi.mock('electron', () => ({ app: { getPath: () => h.dir }, protocol: { handle: h.handle } }));+vi.mock('../ledger', () => ({ touchBlob: h.touch, recordBlob: h.record, addRef: h.ref }));+import * as store from '../blobStore';+import { ingestClientWallpaper } from '../ingest';+import { recycleClientWallpapers } from '../recycler';+import { registerCindyMediaProtocolHandler } from '../cindyMediaProtocol';++beforeEach(() => {+ h.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'client-wallpaper-media-'));+ vi.clearAllMocks();+});+afterEach(() => fs.rmSync(h.dir, { recursive: true, force: true }));++describe('client wallpaper media scope', () => {+ it('isolates deletion and deduplication from identical account-owned blobs', async () => {+ const params = { buffer: Buffer.from('image-content'), mimeType: 'image/webp' as const };+ const account = await store.writeBlob(params);+ const client = await ingestClientWallpaper(params);+ expect(client.hash).toBe(account.hash);+ expect(client.url).not.toBe(account.url);+ expect(client.deduplicated).toBe(false);+ expect((await ingestClientWallpaper(params)).deduplicated).toBe(true);+ expect(h.record).not.toHaveBeenCalled();+ expect(h.ref).not.toHaveBeenCalled();+ await store.deleteBlobFile(account.hash, account.ext);+ expect((await store.readClientWallpaperFile(client.url)).buffer).toEqual(params.buffer);+ await store.writeBlob(params);+ await recycleClientWallpapers([], '.webp');+ await expect(store.readClientWallpaperFile(client.url)).rejects.toThrow();+ expect((await store.readFile(account.url)).buffer).toEqual(params.buffer);+ });++ it('retains the selected image and current catalog videos while removing unused client files', async () => {+ const old = await ingestClientWallpaper({ buffer: Buffer.from('old'), mimeType: 'image/webp' });+ const selected = await ingestClientWallpaper({+ buffer: Buffer.from('new'),+ mimeType: 'image/webp',+ });+ const video = await ingestClientWallpaper({+ buffer: Buffer.from('video'),+ mimeType: 'video/mp4',+ });+ const oldVideo = await ingestClientWallpaper({+ buffer: Buffer.from('old-video'),+ mimeType: 'video/mp4',+ });+ await recycleClientWallpapers([selected.url], '.webp');+ await recycleClientWallpapers([video.url], '.mp4');+ await expect(store.readClientWallpaperFile(old.url)).rejects.toThrow();+ await expect(store.readClientWallpaperFile(oldVideo.url)).rejects.toThrow();+ await expect(store.readClientWallpaperFile(selected.url)).resolves.toBeDefined();+ await expect(store.readClientWallpaperFile(video.url)).resolves.toBeDefined();+ });++ it('serves images and video ranges through the existing protocol without touching an account ledger', async () => {+ const media = await ingestClientWallpaper({+ buffer: Buffer.from('0123456789'),+ mimeType: 'video/mp4',+ });+ registerCindyMediaProtocolHandler();+ const handler = h.handle.mock.calls[0][1];+ const response: Response = await handler(+ new Request(media.url, { headers: { Range: 'bytes=2-5' } }),+ );+ expect(response.status).toBe(206);+ expect(await response.text()).toBe('2345');+ expect(h.touch).not.toHaveBeenCalled();+ const image = await ingestClientWallpaper({+ buffer: Buffer.from('webp'),+ mimeType: 'image/webp',+ });+ const picture: Response = await handler(new Request(image.url));+ expect(picture.status).toBe(200);+ expect(picture.headers.get('content-type')).toContain('image/webp');+ });++ it('keeps account URL parsers strict and rejects noncanonical client paths and other media types', async () => {+ const url = `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp`;+ expect(store.parseBlobUrl(url)).toBeNull();+ expect(() => store.resolveSafe(url)).toThrow('invalid url');+ for (const bad of [+ url + '?a=1',+ url + '#x',+ url.replace('/client-wallpaper/', '/client-wallpaper/../'),+ url.replace('.webp', '.png'),+ url.replace('client-wallpaper', 'other'),+ url.replace('://', '://user@'),+ ]) {+ expect(store.parseClientWallpaperUrl(bad)).toBeNull();+ await expect(store.readClientWallpaperFile(bad)).rejects.toThrow();+ }+ await expect(+ ingestClientWallpaper({ buffer: Buffer.from('x'), mimeType: 'image/png' as never }),+ ).rejects.toThrow();+ expect(() => store.getBlobsRoot('../outside' as never)).toThrow();+ });++ it('rejects symlinked client roots without reading or deleting the target', async () => {+ const external = path.join(h.dir, 'outside');+ const mediaRoot = path.join(h.dir, 'cindy-media');+ fs.mkdirSync(external);+ fs.mkdirSync(mediaRoot);+ const hash = 'a'.repeat(64);+ fs.mkdirSync(path.join(external, 'aa'));+ const file = path.join(external, 'aa', hash + '.webp');+ fs.writeFileSync(file, 'private');+ fs.symlinkSync(+ external,+ path.join(mediaRoot, 'client-wallpaper'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ const url = `cindy-media://client-wallpaper/${hash}.webp`;+ await expect(store.readClientWallpaperFile(url)).rejects.toThrow('symlink');+ await expect(store.deleteBlobFile(hash, '.webp', 'client-wallpaper')).rejects.toThrow(+ 'symlink',+ );+ await expect(+ ingestClientWallpaper({ buffer: Buffer.from('new'), mimeType: 'image/webp' }),+ ).rejects.toThrow('symlink');+ expect(fs.readFileSync(file, 'utf8')).toBe('private');+ });+});diff --git a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.tsindex 8e3f9cc771..391dca5da3 100644--- a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts@@ -64,25 +64,6 @@ async function seedSession(id: string, status: 'active' | 'archived' | 'deleted'}describe('recordBlob(幂等入账)', () => {- it('retains the newly published wallpaper pin and unrelated owners when deduplicating refs', async () => {- await seedBlob(HASH_A);- await seedBlob(HASH_B);- const owner = { refKind: 'import' as const, refId: 'desktop-custom-wallpaper' };- await ledger.addRef({ ...owner, hash: HASH_A, id: 'older' }, db);- await ledger.addRef({ ...owner, hash: HASH_B, id: 'duplicate' }, db);- await ledger.addRef({ ...owner, hash: HASH_B, id: 'keep' }, db);- await ledger.addRef({ ...owner, refId: 'unrelated', hash: HASH_A, id: 'other' }, db);- expect(await ledger.removeRefsExceptId({ ...owner, keepId: 'keep' }, db)).toBe(2);- expect(- db- .select()- .from(schema.mediaRefs)- .all()- .map((row) => row.id)- .sort(),- ).toEqual(['keep', 'other']);- expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(2);- });it('首次入账写全量字段,重复入账不炸只刷 lastAccess', async () => {await seedBlob(HASH_A);await expect(seedBlob(HASH_A)).resolves.toBeUndefined();diff --git a/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts b/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.tsindex 211482e809..9963083f34 100644--- a/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts@@ -55,7 +55,6 @@ afterAll(() => {beforeEach(() => {db = freshDb();- fs.writeFileSync(path.join(tmpUserData, 'custom-wallpaper.json'), JSON.stringify({ url: '' }));fs.rmSync(path.join(tmpUserData, 'cindy-media'), { recursive: true, force: true });legacyRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-storage-legacy-'));});@@ -192,32 +191,6 @@ describe('scan(清理预检:三个暂存区保护贯通)', () => {});describe('cleanup(执行:全类别 + 执行时重新取证)', () => {- it.each([false, true])('protects the shared wallpaper without any owner-local ref (cache=%s)', async (isCache) => {- const image = await seedBlob('shared-wallpaper', { aged: true, isCache, mimeType: 'image/webp' });- const handlers = makeHandlers();- // Another account selected this blob after the cleanup preview. Its pin is- // absent from this account's ledger; the host preference must protect it.- await handlers.scan({ draftUrls: [] });- fs.writeFileSync(path.join(tmpUserData, 'custom-wallpaper.json'), JSON.stringify({ url: image.url }));- const result = await handlers.cleanup({- draftUrls: [], zeroRefHashes: [image.hash], evictCacheHashes: [image.hash],- deadDirNames: [], cleanTmpFiles: false,- });- expect(result.freedBytes).toBe(0);- const scan = await handlers.scan({ draftUrls: [] });- expect(scan.zeroRef.hashes).not.toContain(image.hash);- expect(scan.cache.evictable.map((item) => item.hash)).not.toContain(image.hash);- expect((await handlers.stats()).blobs.totalCount).toBe(1);- // Verify the bytes as well as the ledger, then explicitly forget the image.- expect(fs.existsSync(blobStore.resolveSafe(image.url).absPath)).toBe(true);- fs.writeFileSync(path.join(tmpUserData, 'custom-wallpaper.json'), JSON.stringify({ url: '' }));- const removed = await handlers.cleanup({- draftUrls: [], zeroRefHashes: [image.hash], evictCacheHashes: [image.hash],- deadDirNames: [], cleanTmpFiles: false,- });- expect(removed.freedBytes).toBe(image.bytes);- });-it('零引用/缓存逐出/死目录/tmp 一次执行,汇总释放量', async () => {const doomed = await seedBlob('clean-doomed', { aged: true });const cacheBlob = await seedBlob('clean-cache', { isCache: true });diff --git a/apps/desktop/src/main/cindy-media/blobStore.ts b/apps/desktop/src/main/cindy-media/blobStore.tsindex 95128c83f2..f69906cfd7 100644--- a/apps/desktop/src/main/cindy-media/blobStore.ts+++ b/apps/desktop/src/main/cindy-media/blobStore.ts@@ -22,6 +22,8 @@ import fs from 'node:fs/promises';const SCHEME = 'cindy-media';const HOST_BLOBS = 'blobs';+/** Client-owned wallpaper bytes never share deletion ownership with account-ledger blobs. */+export type BlobScope = 'blobs' | 'client-wallpaper';const destLocks = new Map<string, Promise<unknown>>();/** 指纹形状:SHA-256 十六进制,恰 64 位小写。 */@@ -75,12 +77,13 @@ export interface WrittenBlob {deduplicated: boolean;}-export function getBlobsRoot(): string {- return path.join(app.getPath('userData'), 'cindy-media', 'blobs');+export function getBlobsRoot(scope: BlobScope = 'blobs'): string {+ if (scope !== 'blobs' && scope !== 'client-wallpaper') throw new Error('cindy-media: invalid scope');+ return path.join(app.getPath('userData'), 'cindy-media', scope);}-export function blobUrl(hash: string, ext: string): string {- return `${SCHEME}://${HOST_BLOBS}/${hash}${ext}`;+export function blobUrl(hash: string, ext: string, scope: BlobScope = 'blobs'): string {+ return `${SCHEME}://${scope}/${hash}${ext}`;}/** Canonical extension used both when planning and writing a content-addressed file. */@@ -106,6 +109,7 @@ export type BlobSource =export async function writeBlob(params: BlobSource & {mimeType: string;assertStillValid?: () => void;+ scope?: BlobScope;}): Promise<WrittenBlob> {const { mimeType } = params;const ext = EXT_BY_MIME[mimeType];@@ -127,7 +131,7 @@ export async function writeBlob(params: BlobSource & {}if (bytes === 0) throw new Error('cindy-media: empty buffer');const hash = hasher.digest('hex');- const { dir, dest } = await prepareBlobDestination(hash, ext);+ const { dir, dest } = await prepareBlobDestination(hash, ext, params.scope);return await withDestLock(dest, async () => {// 同目录 tmp + link/rename 发布:终点不以半截内容出现;已存在分支@@ -181,13 +185,13 @@ export async function writeBlob(params: BlobSource & {? existingBlobError(finalState): new Error('cindy-media: blob destination did not match input hash');}- await assertBlobPathContained(dest);+ await assertBlobPathContained(dest, params.scope);return {hash,ext,mimeType,bytes,- url: blobUrl(hash, ext),+ url: blobUrl(hash, ext, params.scope),deduplicated,};} finally {@@ -267,11 +271,12 @@ async function ensureChildDir(parent: string, name: string): Promise<string> {return child;}-async function prepareBlobDestination(hash: string, ext: string): Promise<{ dir: string; dest: string }> {+async function prepareBlobDestination(hash: string, ext: string, scope: BlobScope = 'blobs'): Promise<{ dir: string; dest: string }> {+ getBlobsRoot(scope); // Validate before using the scope as a directory name.const userData = path.resolve(app.getPath('userData'));await lstatRegularDir(userData);const mediaRoot = await ensureChildDir(userData, 'cindy-media');- const root = await ensureChildDir(mediaRoot, 'blobs');+ const root = await ensureChildDir(mediaRoot, scope);const dir = await ensureChildDir(root, hash.slice(0, 2));const dest = path.join(dir, `${hash}${ext}`);if (!path.resolve(dest).startsWith(root + path.sep)) {@@ -280,9 +285,9 @@ async function prepareBlobDestination(hash: string, ext: string): Promise<{ dir:return { dir, dest };}-async function assertBlobPathContained(absPath: string): Promise<void> {+async function assertBlobPathContained(absPath: string, scope: BlobScope = 'blobs'): Promise<void> {const userData = path.resolve(app.getPath('userData'));- const root = path.resolve(getBlobsRoot());+ const root = path.resolve(getBlobsRoot(scope));if (!path.resolve(absPath).startsWith(root + path.sep)) {throw new Error('cindy-media: blob path out of bounds');}@@ -451,7 +456,7 @@ export function resolveSafe(url: string): { absPath: string; mimeType: string; h* 指纹 + 扩展名 → 磁盘位置(供 cindy-ghost:// 供图分支等"手里已是指纹"的* 调用方使用,复用同一套校验与双保险)。*/-export function resolveHashRef(hash: string, ext: string): {+export function resolveHashRef(hash: string, ext: string, scope: BlobScope = 'blobs'): {absPath: string;mimeType: string;hash: string;@@ -463,7 +468,7 @@ export function resolveHashRef(hash: string, ext: string): {if (!mimeType) {throw new Error('cindy-media: unsupported ext');}- const root = path.resolve(getBlobsRoot());+ const root = path.resolve(getBlobsRoot(scope));const absPath = path.resolve(root, hash.slice(0, 2), `${hash}${ext}`);if (!absPath.startsWith(root + path.sep)) {throw new Error('cindy-media: path out of bounds');@@ -510,6 +515,21 @@ export async function readFile(url: string): Promise<{ buffer: Buffer; mimeType:return { buffer, mimeType };}+// UI-owned assets have a separate lifetime from account attachments. Generic+// parseBlobUrl/resolveSafe intentionally do not accept this Host-only namespace.+export function parseClientWallpaperUrl(url: string): { hash: string; ext: string } | null {+ const match = new RegExp('^cindy-media://client-wallpaper/([0-9a-f]{64})([.]webp|[.]mp4)$').exec(url);+ return match ? { hash: match[1], ext: match[2] } : null;+}++export async function readClientWallpaperFile(url: string): Promise<{ buffer: Buffer; mimeType: string }> {+ const parsed = parseClientWallpaperUrl(url);+ if (!parsed) throw new Error('cindy-media: invalid client wallpaper url');+ const { absPath, mimeType } = resolveHashRef(parsed.hash, parsed.ext, 'client-wallpaper');+ await assertBlobPathContained(absPath, 'client-wallpaper');+ return { buffer: await fs.readFile(absPath), mimeType };+}+// ── 回收器 / 对账底层能力(第 5 步)──────────────────────────────────────// 本模块仍然只管字节:下面的枚举与删除不看账本,"该不该删"由 recycler.ts// 按账本判定后才调用这里。@@ -534,8 +554,8 @@ export interface BlobDirListing {const BUCKET_RE = /^[0-9a-f]{2}$/;/** 遍历 256 个分桶,枚举字节仓全量文件(stat 失败的条目跳过,当作已消失)。 */-export async function listBlobFiles(): Promise<BlobDirListing> {- const root = getBlobsRoot();+export async function listBlobFiles(scope: BlobScope = 'blobs'): Promise<BlobDirListing> {+ const root = getBlobsRoot(scope);const listing: BlobDirListing = { entries: [], strayPaths: [], tmpFiles: [] };let buckets: string[];try {@@ -570,6 +590,7 @@ export async function listBlobFiles(): Promise<BlobDirListing> {continue;}try {+ if (scope !== 'blobs') await assertBlobPathContained(abs, scope);const st = await fs.stat(abs);listing.entries.push({ hash, ext, bytes: st.size, mtimeMs: st.mtimeMs, absPath: abs });} catch {@@ -581,8 +602,12 @@ export async function listBlobFiles(): Promise<BlobDirListing> {}/** 删除单个 blob 文件(recycler 在账删成功且复查无重录后才调用);不存在视为成功。 */-export async function deleteBlobFile(hash: string, ext: string): Promise<void> {- const { absPath } = resolveHashRef(hash, ext);+export async function deleteBlobFile(hash: string, ext: string, scope: BlobScope = 'blobs'): Promise<void> {+ const { absPath } = resolveHashRef(hash, ext, scope);+ if (scope !== 'blobs') {+ try { await assertBlobPathContained(absPath, scope); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error; }+ }await fs.rm(absPath, { force: true });}@@ -591,8 +616,8 @@ export async function deleteBlobFile(hash: string, ext: string): Promise<void> {* maxAgeMs 的——正在进行的 writeBlob 临时文件寿命是毫秒级,年龄门槛防* 误杀在途写入。*/-export async function listStaleTmpFiles(maxAgeMs: number): Promise<string[]> {- const { tmpFiles } = await listBlobFiles();+export async function listStaleTmpFiles(maxAgeMs: number, scope: BlobScope = 'blobs'): Promise<string[]> {+ const { tmpFiles } = await listBlobFiles(scope);const cutoff = Date.now() - maxAgeMs;const stale: string[] = [];for (const abs of tmpFiles) {@@ -607,10 +632,11 @@ export async function listStaleTmpFiles(maxAgeMs: number): Promise<string[]> {}/** 清理写入中途崩溃残留的超龄 `.tmp-*` 文件,返回删除数。 */-export async function cleanupTmpFiles(maxAgeMs: number): Promise<number> {+export async function cleanupTmpFiles(maxAgeMs: number, scope: BlobScope = 'blobs'): Promise<number> {let removed = 0;- for (const abs of await listStaleTmpFiles(maxAgeMs)) {+ for (const abs of await listStaleTmpFiles(maxAgeMs, scope)) {try {+ if (scope !== 'blobs') await assertBlobPathContained(abs, scope);await fs.rm(abs, { force: true });removed++;} catch {diff --git a/apps/desktop/src/main/cindy-media/cindyMediaProtocol.ts b/apps/desktop/src/main/cindy-media/cindyMediaProtocol.tsindex 8b8025adb1..161dc4529d 100644--- a/apps/desktop/src/main/cindy-media/cindyMediaProtocol.ts+++ b/apps/desktop/src/main/cindy-media/cindyMediaProtocol.ts@@ -42,7 +42,9 @@ export const cindyMediaSchemePrivilege: CustomScheme = {export function registerCindyMediaProtocolHandler(): void {protocol.handle(SCHEME, async (request) => {try {- const { buffer, mimeType } = await blobStore.readFile(request.url);+ const { buffer, mimeType } = blobStore.parseClientWallpaperUrl(request.url)+ ? await blobStore.readClientWallpaperFile(request.url)+ : await blobStore.readFile(request.url);// 惰性刷 lastAccess(cache LRU 依据);解析成功才有合法 hash。const parsed = blobStore.parseBlobUrl(request.url);if (parsed) void ledger.touchBlob(parsed.hash);diff --git a/apps/desktop/src/main/cindy-media/clientWallpaperLock.ts b/apps/desktop/src/main/cindy-media/clientWallpaperLock.tsnew file mode 100644index 0000000000..15b41648db--- /dev/null+++ b/apps/desktop/src/main/cindy-media/clientWallpaperLock.ts@@ -0,0 +1,15 @@+import { app } from 'electron';+import path from 'node:path';+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';++/** Only publication/recycling hold this client-wide lock, never native pickers. */+export async function withClientWallpaperLock<T>(action: () => Promise<T>): Promise<T> {+ return withCrossProcessLock(+ path.join(app.getPath('userData'), 'client-wallpaper-operation.lock'),+ { label: 'client-wallpaper', waitMs: 12_000 },+ async (status) => {+ if (!status.held) throw new Error('Client wallpaper is being changed in another process');+ return action();+ },+ );+}diff --git a/apps/desktop/src/main/cindy-media/ingest.ts b/apps/desktop/src/main/cindy-media/ingest.tsindex 14f67481f8..5ee0e33bfe 100644--- a/apps/desktop/src/main/cindy-media/ingest.ts+++ b/apps/desktop/src/main/cindy-media/ingest.ts@@ -95,7 +95,7 @@ export async function ingestMedia(}params.assertStillValid?.();// writeBlob 只在最终实际内容 hash 正确时返回;损坏/symlink/目录不会被当成去重。- const written = await blobStore.writeBlob(params);+ const written = await blobStore.writeBlob({ ...params, scope: 'blobs' });params.assertStillValid?.();await ledger.recordBlob({@@ -151,3 +151,17 @@ export async function ingestMedia(/** 调用方可先判"这类字节进不进仓"(白名单外走 xdt-file 等直读通道,规则 25 边界)。 */export const supportedMime = blobStore.supportedMime;++/**+ * Client UI media has no account owner. Its reference is the client appearance+ * setting (custom WebP) or bundled catalog (optional CDN MP4), not an account DB.+ * Reuse the same atomic byte store in an isolated deletion scope; callers must+ * serialize publication and recycling with the client wallpaper operation lock.+ */+export async function ingestClientWallpaper(+ params: { buffer: Uint8Array; mimeType: 'image/webp' | 'video/mp4' },+): Promise<blobStore.WrittenBlob> {+ if (params.mimeType !== 'image/webp' && params.mimeType !== 'video/mp4')+ throw new Error('cindy-media: unsupported client wallpaper type');+ return blobStore.writeBlob({ ...params, scope: 'client-wallpaper' });+}diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.tsindex 7bec42690b..69c050d7d1 100644--- a/apps/desktop/src/main/cindy-media/ledger.ts+++ b/apps/desktop/src/main/cindy-media/ledger.ts@@ -338,24 +338,6 @@ export async function removeRefsExceptHash(return result.changes;}-/** Retain one newly published ref, including when importing the same hash again. */-export async function removeRefsExceptId(- params: { refKind: MediaRefKind; refId: string; keepId: string },- db: LedgerDb = defaultDb(),-): Promise<number> {- const result = await db- .delete(mediaRefs)- .where(- and(- eq(mediaRefs.refKind, params.refKind),- eq(mediaRefs.refId, params.refId),- ne(mediaRefs.id, params.keepId),- ),- )- .run();- return result.changes;-}-/** 删除某引用方名下的全部引用(删会话 / 卸载意识时由业务代码调用)。 */export async function removeRefs(params: { refKind: MediaRefKind; refId: string },diff --git a/apps/desktop/src/main/cindy-media/recycler.ts b/apps/desktop/src/main/cindy-media/recycler.tsindex 114641c1a7..f631786bc8 100644--- a/apps/desktop/src/main/cindy-media/recycler.ts+++ b/apps/desktop/src/main/cindy-media/recycler.ts@@ -31,6 +31,20 @@ import type { LedgerDb } from './ledger';const log = createLogger('cindy-media-recycler');+/** Called under the client wallpaper publication lock after saving its reference.+ * This scope cannot contain chat/attachment bytes; never delete ordinary blobs.+ * A later successful operation also retries failed cleanup or interrupted imports.+ */+export async function recycleClientWallpapers(keepUrls: string[], ext: '.webp' | '.mp4'): Promise<void> {+ const keep = new Set(keepUrls.map((url) => blobStore.parseClientWallpaperUrl(url)?.hash).filter(Boolean));+ const { entries } = await blobStore.listBlobFiles('client-wallpaper');+ for (const entry of entries) {+ if (entry.ext === ext && !keep.has(entry.hash))+ await blobStore.deleteBlobFile(entry.hash, entry.ext, 'client-wallpaper');+ }+ await blobStore.cleanupTmpFiles(TMP_FILE_MAX_AGE_MS, 'client-wallpaper');+}+/** 零引用缓冲期(内部常量,规则 20 隐藏层):入库与最后访问都早于此才候选。 */export const ZERO_REF_BUFFER_MS = 72 * 60 * 60 * 1000;/** cache 总量上限(§4 默认 512MB 量级;内部常量,规则 20 隐藏层)。 */diff --git a/apps/desktop/src/main/cindy-media/storageIpc.ts b/apps/desktop/src/main/cindy-media/storageIpc.tsindex 1268fd3fba..f3acfb289d 100644--- a/apps/desktop/src/main/cindy-media/storageIpc.ts+++ b/apps/desktop/src/main/cindy-media/storageIpc.ts@@ -20,7 +20,6 @@*/import { createLogger } from '../logger';-import { readCustomWallpaperUrl } from '../custom-wallpaper-settings';import { throwIpcError } from '../utils/ipcValidate';import * as blobStore from './blobStore';import * as ledger from './ledger';@@ -136,8 +135,7 @@ const EMPTY_CACHE: recycler.CacheScan = {async function collectLive(deps: StorageIpcDeps, draftUrls: string[]): Promise<Set<string>> {const sources: LiveHashSources = {// 发起窗口随参带的 + 全窗口登记表的并集(多窗口草稿全豁免)。- // The profile-wide wallpaper may be pinned only in a different owner's ledger.- draftUrls: [...draftUrls, ...(deps.getRegisteredDraftUrls?.() ?? []), readCustomWallpaperUrl()],+ draftUrls: [...draftUrls, ...(deps.getRegisteredDraftUrls?.() ?? [])],inMemoryQueueTexts: deps.getQueueScanTexts,snapshotPayloads: deps.loadSnapshotPayloads,};diff --git a/apps/desktop/src/main/custom-wallpaper-settings.ts b/apps/desktop/src/main/custom-wallpaper-settings.tsindex 1869eef833..e1590c08b9 100644--- a/apps/desktop/src/main/custom-wallpaper-settings.ts+++ b/apps/desktop/src/main/custom-wallpaper-settings.ts@@ -1,12 +1,6 @@import { app } from 'electron';-import fs from 'node:fs';import path from 'node:path';import { normalizeCustomWallpaperUrl } from '../shared/appearanceSettings.js';-import {- getActiveAppSession,- isAppSessionBoundaryPending,- ownerScopedUserDataPath,-} from './appSessionState.js';import { createOverrideSettingsFile } from './maker-host/override-settings-file.js';import { createLogger } from './logger.js';@@ -27,25 +21,7 @@ export const customWallpaperStore = createOverrideSettingsFile<{ url: string }>(logReadErrorDetails: false,});-function migratePreviewPreference(): void {- const target = filePath();- if (fs.existsSync(target) || !getActiveAppSession().dataOwnerId || isAppSessionBoundaryPending())- return;- // Adopt only the active account's pre-release preference; never scan other accounts.- // Exclusive creation cannot overwrite another process's shared preference.- // Removal retains an empty file so old preferences cannot reappear.- try {- const source = ownerScopedUserDataPath('custom-wallpaper.json');- if (!fs.existsSync(source) || fs.statSync(source).size > 4096) return;- const url = normalizeCustomWallpaperUrl(JSON.parse(fs.readFileSync(source, 'utf8'))?.url);- if (url) fs.writeFileSync(target, JSON.stringify({ url }), { encoding: 'utf8', flag: 'wx' });- } catch {- // Preserve unreadable legacy files and never log their private contents.- }-}-export function readCustomWallpaperUrl(): string {- migratePreviewPreference();customWallpaperStore.invalidateIfChanged();return customWallpaperStore.read().url;}diff --git a/apps/desktop/src/main/custom-wallpaper.ts b/apps/desktop/src/main/custom-wallpaper.tsindex 7363fb0503..cfa0391fcc 100644--- a/apps/desktop/src/main/custom-wallpaper.ts+++ b/apps/desktop/src/main/custom-wallpaper.ts@@ -3,54 +3,14 @@ import sharp from 'sharp';import { readBoundedFileNoFollow } from './utils/readBoundedFile.js';import { throwIpcError } from './utils/ipcValidate.js';-import { getCurrentDbClientSnapshot } from './localDb/client/current.js';-import { captureMediaRefCompensationScope } from './cindy-media/refCompensationJournal.js';-import { ingestMedia } from './cindy-media/ingest.js';-import { removeRefById, removeRefs, removeRefsExceptId } from './cindy-media/ledger.js';-import { customWallpaperStore } from './custom-wallpaper-settings.js';+import { ingestClientWallpaper } from './cindy-media/ingest.js';+import { recycleClientWallpapers } from './cindy-media/recycler.js';+import { withClientWallpaperLock } from './cindy-media/clientWallpaperLock.js';+import { customWallpaperStore, readCustomWallpaperUrl } from './custom-wallpaper-settings.js';import { createLogger } from './logger.js';-import { ownerScopedUserDataPath } from './appSessionState.js';-import { withCrossProcessLock } from './device-link/crossProcessLock.js';const log = createLogger('custom-wallpaper');-const REF = { refKind: 'import' as const, refId: 'desktop-custom-wallpaper' };const MAX_BYTES = 20 * 1024 * 1024;-const queues = new Map<string, Promise<unknown>>();--function captureScope() {- const snapshot = getCurrentDbClientSnapshot();- if (!snapshot) throwIpcError('INTERNAL', 'Wallpaper storage is not ready');- const compensation = captureMediaRefCompensationScope();- const assertValid = () => {- compensation.assertStillValid();- if (getCurrentDbClientSnapshot() !== snapshot)- throwIpcError('INTERNAL', 'Wallpaper owner changed');- };- return { db: snapshot.client.drizzle, compensation, assertValid };-}--function serialize<T>(action: () => Promise<T>): Promise<T> {- const lockPath = ownerScopedUserDataPath('custom-wallpaper-operation.lock');- const result = (queues.get(lockPath) ?? Promise.resolve())- .catch(() => undefined)- .then(() =>- withCrossProcessLock(- lockPath,- { label: 'custom-wallpaper', waitMs: 12_000 },- async (status) => {- if (!status.held)- throwIpcError('INTERNAL', 'Wallpaper is being changed in another window');- return action();- },- ),- );- queues.set(lockPath, result);- const release = () => {- if (queues.get(lockPath) === result) queues.delete(lockPath);- };- void result.then(release, release);- return result;-}/** Decode real raster bytes, apply orientation, strip metadata and retain a static 4K preview. */export async function prepareWallpaperImage(bytes: Buffer): Promise<Buffer> {@@ -73,67 +33,44 @@ export async function prepareWallpaperImage(bytes: Buffer): Promise<Buffer> {/** Paths come only from this native picker, never from the renderer or remote peers. */export async function importCustomWallpaper(parent: BrowserWindow): Promise<boolean> {- const scope = captureScope();- return serialize(async () => {- scope.assertValid();- const selected = await dialog.showOpenDialog(parent, {- properties: ['openFile'],- filters: [{ name: 'PNG / JPEG / WebP', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],+ const selected = await dialog.showOpenDialog(parent, {+ properties: ['openFile'],+ filters: [{ name: 'PNG / JPEG / WebP', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],+ });+ if (selected.canceled || !selected.filePaths[0]) return false;+ let bytes: Buffer;+ try {+ const read = await readBoundedFileNoFollow(selected.filePaths[0], MAX_BYTES, {+ nonBlocking: true,});- scope.assertValid();- if (selected.canceled || !selected.filePaths[0]) return false;- let bytes: Buffer;- try {- const read = await readBoundedFileNoFollow(selected.filePaths[0], MAX_BYTES, {- nonBlocking: true,- });- if (!read) throw new Error('Unreadable image');- bytes = read;- } catch {- throwIpcError('INVALID_PARAMS', 'Cannot read image; choose a local image up to 20 MB');- }- const buffer = await prepareWallpaperImage(bytes);- scope.assertValid();- const media = await ingestMedia(- {- buffer,- mimeType: 'image/webp',- isCache: false,- refs: [{ ...REF, originKind: 'user' }],- assertStillValid: scope.assertValid,- refCompensationScope: scope.compensation,- },- scope.db,- );- try {- scope.assertValid();- await customWallpaperStore.writePatchAtomic({ url: media.url });- } catch (error) {- await Promise.allSettled(media.refIds.map((id) => removeRefById(id, scope.db)));- throw error;- }- // Publication succeeded. Cleanup failure must retain the new selection and its pin.- try {- await removeRefsExceptId({ ...REF, keepId: media.refIds[0] }, scope.db);- } catch {- log.warn('Previous wallpaper reference cleanup deferred');- }- scope.assertValid();+ if (!read) throw new Error('Unreadable image');+ bytes = read;+ } catch {+ throwIpcError('INVALID_PARAMS', 'Cannot read image; choose a local image up to 20 MB');+ }+ const buffer = await prepareWallpaperImage(bytes);+ return withClientWallpaperLock(async () => {+ const media = await ingestClientWallpaper({ buffer, mimeType: 'image/webp' });+ await customWallpaperStore.writePatchAtomic({ url: media.url });+ // Recycle only after successful publication. Unreadable settings or a failed+ // write must not delete the previous image; a later successful operation also+ // collects bytes left by interrupted/failed imports.+ await recycleUnusedImages();return true;});}export async function removeCustomWallpaper(): Promise<void> {- const scope = captureScope();- return serialize(async () => {- scope.assertValid();- // Forget the preference before unpinning; never delete shared media bytes here.- await customWallpaperStore.writePatchAtomic({ url: '' }, { preserveDefaults: true });- try {- await removeRefs(REF, scope.db);- } catch {- log.warn('Removed wallpaper reference cleanup deferred');- }- scope.assertValid();+ return withClientWallpaperLock(async () => {+ await customWallpaperStore.resetAtomic();+ await recycleUnusedImages();});}++async function recycleUnusedImages(): Promise<void> {+ try {+ await recycleClientWallpapers([readCustomWallpaperUrl()], '.webp');+ } catch {+ log.warn('Unused client wallpaper cleanup deferred');+ }+}diff --git a/apps/desktop/src/main/wallpaper-video.ts b/apps/desktop/src/main/wallpaper-video.tsindex 637047ad63..442d011059 100644--- a/apps/desktop/src/main/wallpaper-video.ts+++ b/apps/desktop/src/main/wallpaper-video.ts@@ -1,11 +1,9 @@import { createHash } from 'node:crypto';import manifest from '../shared/wallpaper-video-manifest.json';-import { activeOwnerScopeKey, isAppSessionBoundaryPending } from './appSessionState.js';-import { getCurrentDbClientSnapshot } from './localDb/client/current.js';-import { captureMediaRefCompensationScope } from './cindy-media/refCompensationJournal.js';-import { ingestMedia } from './cindy-media/ingest.js';-import { getIntegrationCacheHash, removeRefsExceptId, touchBlob } from './cindy-media/ledger.js';-import { resolveHashRef } from './cindy-media/blobStore.js';+import { ingestClientWallpaper } from './cindy-media/ingest.js';+import { resolveHashRef, blobUrl } from './cindy-media/blobStore.js';+import { withClientWallpaperLock } from './cindy-media/clientWallpaperLock.js';+import { recycleClientWallpapers } from './cindy-media/recycler.js';import { readBoundedFileNoFollow } from './utils/readBoundedFile.js';import { getClientEndpoint } from './clientEndpointsService.js';import { guardedOutboundFetch } from './maker-host/outbound-fetch.js';@@ -14,37 +12,45 @@ import { throwIpcError } from './utils/ipcValidate.js';type Scene = keyof typeof manifest;type Asset = { sha256: string; bytes: number };const RETRY_MS = 5 * 60_000;-const states = new WeakMap<object, Map<Scene, { pending?: Promise<string | null>; retryAt: number }>>();+const states = new Map<Scene, { pending?: Promise<string | null>; retryAt: number }>();export function isWallpaperVideoScene(id: unknown): id is Scene {return typeof id === 'string' && Object.hasOwn(manifest, id);}export function matchesWallpaperVideo(bytes: Buffer, asset: Asset): boolean {- // The pinned digest identifies reviewed MP4 bytes, not server-supplied MIME claims.- return bytes.length === asset.bytes && createHash('sha256').update(bytes).digest('hex') === asset.sha256;+ return (+ bytes.length === asset.bytes &&+ createHash('sha256').update(bytes).digest('hex') === asset.sha256+ );}-async function download(asset: Asset, assertValid: () => void): Promise<Buffer> {+async function download(asset: Asset): Promise<Buffer> {const base = getClientEndpoint('cdnBaseUrl');if (!base) throw new Error('Wallpaper CDN unavailable');const url = new URL(base.replace(/\/+$/, '') + '/wallpapers/' + asset.sha256 + '.mp4');- if (url.protocol !== 'https:' || url.username || url.password) throw new Error('Invalid wallpaper CDN');- const { response, release } = await guardedOutboundFetch(url.href, {- signal: AbortSignal.timeout(30_000), credentials: 'omit', redirect: 'error',- }, assertValid);+ if (url.protocol !== 'https:' || url.username || url.password)+ throw new Error('Invalid wallpaper CDN');+ const { response, release } = await guardedOutboundFetch(+ url.href,+ {+ signal: AbortSignal.timeout(30_000),+ credentials: 'omit',+ redirect: 'error',+ },+ () => {},+ );let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;try {- assertValid();if (!response.ok || !response.body) throw new Error('Wallpaper CDN unavailable');const length = response.headers.get('content-length');- if (length !== null && Number(length) !== asset.bytes) throw new Error('Wallpaper size mismatch');+ if (length !== null && Number(length) !== asset.bytes)+ throw new Error('Wallpaper size mismatch');reader = response.body.getReader();const chunks: Buffer[] = [];let size = 0;while (true) {const { done, value } = await reader.read();- assertValid();if (done) break;size += value.byteLength;if (size > asset.bytes) throw new Error('Wallpaper exceeds expected size');@@ -60,60 +66,41 @@ async function download(asset: Asset, assertValid: () => void): Promise<Buffer>}}-/** Optional enhancement: failure never prevents the bundled video from playing. */+/** Optional CDN assets share the client's lifecycle, including before login. */export async function ensureWallpaperVideo(id: unknown): Promise<string | null> {if (!isWallpaperVideoScene(id)) throwIpcError('INVALID_PARAMS', 'Unsupported wallpaper video');- // Bundled official scenes must never contact OSS, even through a direct IPC call.if (manifest[id].delivery !== 'cdn') return null;- const snapshot = getCurrentDbClientSnapshot();- if (!snapshot || isAppSessionBoundaryPending()) return null;- let state = states.get(snapshot);- if (!state) states.set(snapshot, state = new Map());- const previous = state.get(id);+ const previous = states.get(id);if (previous?.pending) return previous.pending;if (previous && previous.retryAt > Date.now()) return null;const entry = { retryAt: 0, pending: undefined as Promise<string | null> | undefined };- state.set(id, entry);+ states.set(id, entry);entry.pending = (async () => {try {- const owner = activeOwnerScopeKey();- const compensation = captureMediaRefCompensationScope();- const assertValid = () => {- compensation.assertStillValid();- if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner || getCurrentDbClientSnapshot() !== snapshot)- throw new Error('Wallpaper owner changed');- };- assertValid();- const db = snapshot.client.drizzle;const asset = manifest[id];- const ref = { refKind: 'integration-cache' as const, refId: 'wallpaper:' + asset.sha256 };- const cached = await getIntegrationCacheHash(ref.refId, db);- assertValid();- if (cached === asset.sha256) {- const bytes = await readBoundedFileNoFollow(resolveHashRef(cached, '.mp4').absPath, asset.bytes).catch(() => null);- assertValid();- if (bytes && matchesWallpaperVideo(bytes, asset)) {- await touchBlob(cached, db);- assertValid();- return 'cindy-media://blobs/' + cached + '.mp4';- }- }- const bytes = await download(asset, assertValid);- assertValid();- const media = await ingestMedia({- buffer: bytes, mimeType: 'video/mp4', isCache: true,- refs: [{ ...ref, originKind: 'integration' }],- assertStillValid: assertValid, refCompensationScope: compensation,- }, db);- assertValid();- // Repair/retry remains idempotent; never remove another feature's references.- await removeRefsExceptId({ ...ref, keepId: media.refIds[0] }, db);- assertValid();- return media.url;+ const url = blobUrl(asset.sha256, '.mp4', 'client-wallpaper');+ const cachedPath = resolveHashRef(asset.sha256, '.mp4', 'client-wallpaper').absPath;+ const cached = await readBoundedFileNoFollow(cachedPath, asset.bytes).catch(() => null);+ if (cached && matchesWallpaperVideo(cached, asset)) return url;+ const bytes = await download(asset);+ return await withClientWallpaperLock(async () => {+ const media = await ingestClientWallpaper({ buffer: bytes, mimeType: 'video/mp4' });+ await recycleClientWallpapers(+ Object.values(manifest)+ .filter((item) => item.delivery === 'cdn')+ .map((item) => blobUrl(item.sha256, '.mp4', 'client-wallpaper')),+ '.mp4',+ ).catch(() => undefined);+ return media.url;+ });} catch {entry.retryAt = Date.now() + RETRY_MS;return null;}- })().finally(() => { entry.pending = undefined; });+ })().finally(() => {+ entry.pending = undefined;+ });return entry.pending;}++export const __testing = { reset: () => states.clear() };diff --git a/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx b/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsxindex 3fa27cc825..975e5d9aee 100644--- a/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx@@ -128,7 +128,7 @@ it.each(['sidebar', 'plugin'] as const)(expect(document.documentElement.style.getPropertyValue('--app-wallpaper-veil')).not.toBe(lightVeil,);- const url = 'cindy-media://blobs/' + 'a'.repeat(64) + '.webp';+ const url = 'cindy-media://client-wallpaper/' + 'a'.repeat(64) + '.webp';await act(async () =>changed({ ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'custom', customWallpaperUrl: url }),);diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsxindex 63dec070a1..d9c96c1c91 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx+++ b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx@@ -31,19 +31,16 @@ afterEach(() => {});describe('application wallpaper lifecycle', () => {- it('restores shared artwork and keeps it visible throughout an account switch', async () => {- const url = `cindy-media://blobs/${'b'.repeat(64)}.webp`;- let authChanged: () => void = () => {};+ it('loads client artwork without subscribing to account changes', async () => {+ const url = `cindy-media://client-wallpaper/${'b'.repeat(64)}.webp`;+ const subscribeAuth = vi.fn();const get = vi.fn().mockResolvedValue({value: { ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'custom', customWallpaperUrl: url },});vi.stubGlobal('electronAPI', {- onAuthStateChange: (fn: () => void) => {- authChanged = fn;- return () => {};- },+ onAuthStateChange: subscribeAuth,appearanceSettings: {getSync: () => DEFAULT_APPEARANCE_SETTINGS,get,@@ -61,9 +58,9 @@ describe('application wallpaper lifecycle', () => {),);expect(document.querySelector('video')).toBeNull();- act(() => authChanged());expect(document.documentElement.style.getPropertyValue('--app-wallpaper-image')).toContain(url);- await waitFor(() => expect(get).toHaveBeenCalledTimes(2));+ expect(subscribeAuth).not.toHaveBeenCalled();+ expect(get).toHaveBeenCalledOnce();expect(document.documentElement.style.getPropertyValue('--app-wallpaper-image')).toContain(url);});it('does not enable transparent surfaces for a missing custom image', () => {diff --git a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsxindex f3877958e8..c9914df12c 100644--- a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx+++ b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx@@ -132,15 +132,10 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })}).catch(() => undefined);};- const unsubscribeAuth = window.electronAPI?.onAuthStateChange?.(() => {- // Wallpaper is a profile-wide preference, like the theme. Keep it visible.- refresh();- });refresh();return () => {disposed = true;unsubscribe();- unsubscribeAuth?.();};}, []);diff --git a/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts b/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.tsindex da7d79c057..950afbd2f7 100644--- a/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts+++ b/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts@@ -3,7 +3,7 @@ import { normalizeAppearanceSettings } from '../appearanceSettings';describe('wallpaper catalog compatibility', () => {it('accepts only canonical host-owned custom artwork and never legacy paths or CSS', () => {- const url = `cindy-media://blobs/${'a'.repeat(64)}.webp`;+ const url = `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp`;expect(normalizeAppearanceSettings({ wallpaperId: 'custom', customWallpaperUrl: url }),).toMatchObject({ wallpaperId: 'custom', customWallpaperUrl: url });diff --git a/apps/desktop/src/shared/appearanceSettings.ts b/apps/desktop/src/shared/appearanceSettings.tsindex ff250fb36f..60c016bd39 100644--- a/apps/desktop/src/shared/appearanceSettings.ts+++ b/apps/desktop/src/shared/appearanceSettings.ts@@ -62,7 +62,7 @@ export const WALLPAPER_IDS = [export type WallpaperId = (typeof WALLPAPER_IDS)[number];export function normalizeCustomWallpaperUrl(value: unknown): string {- return typeof value === 'string' && /^cindy-media:\/\/blobs\/[0-9a-f]{64}\.webp$/.test(value)+ return typeof value === 'string' && /^cindy-media:\/\/client-wallpaper\/[0-9a-f]{64}\.webp$/.test(value)? value: '';}diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex b58901ec71..bff56b15e0 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -83,8 +83,10 @@ in the same section (user addition, 2026-10-01). Accept local PNG/JPEG/WebP up t20 MB and 40 megapixels, store a metadata-free static image up to 3840 pixelsin the managed media store. Wallpaper selection and the custom image referenceare shared within the Desktop profile, just like theme preferences (user decision,-2026-10-02). Switching accounts keeps the same wallpaper. Media cleanup by any-account must protect the shared image. Font-only utility renderers never receive+2026-10-02). Import, replacement, removal and recycling are client-wide as well:+no account database, account-bound operation guard or pre-release owner migration.+The media store's client wallpaper scope isolates its bytes from chat attachments;+switching accounts (or signing out) keeps the same wallpaper. Font-only utility renderers never receivecustom media URLs.Detached sidebar and plugin-panel host chrome use the same wallpaper provider;embedded plugin webviews retain their own surfaces and permission boundary.diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex 7793cc0213..54048c854a 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -37,6 +37,14 @@- 新写入优先调用 `ingestMedia` 或已有业务适配器,不新建专用媒体目录、cache store、数据表或协议,也不在调用方重复实现“写 blob、记账、挂引用”。+- 客户端共用壁纸使用统一媒体仓的 `ingestClientWallpaper` 入口与+ `client-wallpaper` 字节作用域(2026-10-02 用户裁决),复用 blobStore 的指纹、+ 原子发布和安全校验,不挂账号数据库引用。引用真相为客户端自定义图片设置或+ 官方视频清单;发布与回收共用客户端操作锁,原生选图和下载不占锁。先成功保存引用,+ 再由 recycler 回收该作用域中不再引用的文件,失败留到下次成功操作重试。+ 这是统一仓内的生命周期隔离,不另建缓存引擎、数据库或协议;即使字节内容相同,+ 也不与账号附件跨作用域去重,删除壁纸不会删除聊天引用的副本,反向清理亦然。+ 本 PR 尚未发布,不迁移中间版本的账号设置或引用。- 标准顺序是:主机核验媒体类型 → 按字节计算 SHA-256 并原子落盘 → 记录 blob → 挂业务引用。外部、插件或远端自报的指纹、扩展名和 Content-Type 不能单独作为可信依据。- 持久附件或作品必须使用符合业务生命周期的引用。业务删除时只删除自己名下的引用,@@ -47,7 +55,8 @@落库前不会被回收,并用测试覆盖成功、失败、取消和重试。- 三款官方壁纸的高清 WebP 与 2304×1440 MP4 均随包,清单标记 `delivery: bundled`,不访问 OSS/CDN,不重复打包低清视频。未来显式标记 `delivery: cdn` 的条目才启用- `integration-cache` 引用与 CDN 下载,按清单字节数与 SHA-256 校验后入仓;失败回退随包视频。+ 客户端级 CDN 下载,按清单字节数与 SHA-256 校验后入仓;当前清单保留引用,+ 下载成功后回收已不在清单的客户端视频,失败回退随包视频。发布脚本只上传 CDN 条目,始终跳过 bundled 条目。发布命令为`node --env-file=<发布配置> scripts/publish-wallpaper-videos.mjs --directory=<视频目录> --region=global`;中国大陆版显式用 `--region=cn`,发布两区时分别执行。可加 `--verify-only` 离线核验。@@ -62,6 +71,9 @@- 持久地址统一使用 `cindy-media://blobs/<sha256>.<ext>`。路径解析必须走`blobStore.resolveSafe` 或现有上层适配器,不根据 URL 字符串手工拼磁盘路径。+- 客户端壁纸地址为 `cindy-media://client-wallpaper/<sha256>.webp` 或 `.mp4`,+ 由既有协议 handler 的严格解析分支服务,不触发账号账本的访问时间更新。普通附件+ 与插件的 blob 解析器不接受该 UI 专用作用域;字体工具窗口不获得自定义图片地址。- `cindy-media://` 的 scheme privilege 和 handler 只在现有集中入口注册。不要为单一功能新增媒体协议;确需改变协议能力时,同时按 Electron 安全规则审查 CSP、fetch、Range、路径校验和 Renderer 暴露面。