Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 壁纸资源改为按需下载并跨升级复用缓存 (#6099)
DavidShenXDed15f06646ed
diff --git a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.tsindex 2b4062a1c9..e77f10ca83 100644--- a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts+++ b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts@@ -28,7 +28,10 @@ vi.mock('../custom-wallpaper.js', () => ({importCustomWallpaper: mocks.importWallpaper,removeCustomWallpaper: mocks.removeWallpaper,}));-vi.mock('../wallpaper-video.js', () => ({ ensureWallpaperVideo: mocks.ensureVideo }));+vi.mock('../wallpaper-video.js', () => ({+ ensureWallpaperVideo: mocks.ensureVideo,+ ensureWallpaperImage: mocks.ensureVideo,+}));vi.mock('electron', () => ({BrowserWindow: { getAllWindows: () => mocks.allWindows, fromWebContents: mocks.fromWebContents },@@ -53,7 +56,10 @@ vi.mock('../appearance-settings-store.js', () => ({}));import { registerAppearanceSettingsIpc, __testing } from '../appearance-settings-ipc.js';-import { normalizeAppearanceSettings } from '../../shared/appearanceSettings.js';+import {+ normalizeAppearanceSettings,+ WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL,+} from '../../shared/appearanceSettings.js';import { markAppContentWindow } from '../windowFocusClassifier.js';const persisted = {@@ -84,29 +90,54 @@ describe('appearance settings IPC authorization', () => {expect(() => __testing.parsePatch({ wallpaperVisibility })).toThrow('INVALID_PARAMS');}});- 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 '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');- });- const handler = mocks.ipcHandle.mock.calls.find(- ([name]) => name === 'appearance-settings:ensure-wallpaper-video',- )?.[1];- await expect(handler({}, 'cindy-window')).rejects.toThrow('untrusted');- expect(mocks.ensureVideo).not.toHaveBeenCalled();- });+ it.each(['video', 'image'])(+ 'authorizes the CDN %s request and keeps it valid across account switches',+ async (kind) => {+ const handler = mocks.ipcHandle.mock.calls.find(+ ([name]) => name === `appearance-settings:ensure-wallpaper-${kind}`,+ )?.[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 'client-video-url';+ });+ expect(await handler({}, 'cindy-window')).toBe('client-video-url');+ },+ );+ it.each(['video', 'image'])(+ 'rejects an untrusted CDN %s request before starting a download',+ async (kind) => {+ mocks.assertTrustedAppRendererEvent.mockImplementation(() => {+ throw new Error('untrusted');+ });+ const handler = mocks.ipcHandle.mock.calls.find(+ ([name]) => name === `appearance-settings:ensure-wallpaper-${kind}`,+ )?.[1];+ await expect(handler({}, 'cindy-window')).rejects.toThrow('untrusted');+ expect(mocks.ensureVideo).not.toHaveBeenCalled();+ },+ );+ it.each(['video', 'image'])(+ 'sends %s progress only to the authorized requesting frame',+ async (kind) => {+ const handler = mocks.ipcHandle.mock.calls.find(+ ([name]) => name === `appearance-settings:ensure-wallpaper-${kind}`,+ )?.[1];+ const send = vi.fn();+ const progress = { wallpaperId: 'cindy-window', kind, loaded: 2, total: 3 };+ mocks.ensureVideo.mockImplementationOnce(async (_id, onProgress) => {+ onProgress(progress);+ return 'cached-media-url';+ });+ await expect(handler({ senderFrame: { send } }, 'cindy-window')).resolves.toBe(+ 'cached-media-url',+ );+ expect(send).toHaveBeenCalledExactlyOnceWith(WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL, progress);+ expect(mocks.trustedReadWindow).not.toHaveBeenCalled();+ },+ );it.each(['appearance-settings:import-wallpaper', 'appearance-settings:remove-wallpaper'])('allows %s when the account changes during module loading',async (channel) => {diff --git a/apps/desktop/src/main/__tests__/customWallpaper.test.ts b/apps/desktop/src/main/__tests__/customWallpaper.test.tsindex 5f9fb85d64..beeb1e1c81 100644--- a/apps/desktop/src/main/__tests__/customWallpaper.test.ts+++ b/apps/desktop/src/main/__tests__/customWallpaper.test.ts@@ -14,6 +14,7 @@ vi.mock('../../shared/wallpaper-video-manifest.json', () => ({official: {delivery: 'cdn',sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',+ image: { sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad' },},},}));@@ -153,18 +154,21 @@ describe('client-owned custom wallpaper lifecycle', () => {await removeCustomWallpaper();expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(0);});- it('retains an official CDN video when removing custom media', async () => {- const official = await writeBlob({- buffer: Buffer.from('abc'),- mimeType: 'video/mp4',- scope: 'client-wallpaper',- });- await selectImage();- await importCustomWallpaper(parent);- await removeCustomWallpaper();- expect((await readClientWallpaperFile(official.url)).buffer).toEqual(Buffer.from('abc'));- expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(1);- });+ it.each(['video/mp4', 'image/webp'])(+ 'retains official CDN %s across custom import and removal',+ async (mimeType) => {+ const official = await writeBlob({+ buffer: Buffer.from('abc'),+ mimeType,+ scope: 'client-wallpaper',+ });+ await selectImage();+ await importCustomWallpaper(parent);+ await removeCustomWallpaper();+ expect((await readClientWallpaperFile(official.url)).buffer).toEqual(Buffer.from('abc'));+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(1);+ },+ );it('rejects oversized or fake MP4 files without replacing the current image', async () => {await selectImage();diff --git a/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts b/apps/desktop/src/main/__tests__/wallpaperVideo.test.tsindex fd8bb8cb01..2e69b756d0 100644--- a/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts+++ b/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts@@ -1,158 +1,212 @@-import { createHash } from 'node:crypto';-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 type { DownloadOptions } from '../downloader/types';const m = vi.hoisted(() => ({- snapshot: { client: { drizzle: {} } },- owner: 'one',- boundary: false,- cached: vi.fn(),- read: vi.fn(),- touch: vi.fn(),- ingest: vi.fn(),- remove: vi.fn(),- fetch: vi.fn(),- release: vi.fn(),- assert: vi.fn(),+ dir: '',+ version: '1.0.0',+ download: vi.fn(),+ endpoint: vi.fn(),+ recycle: vi.fn(),+ hash: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',}));+vi.mock('electron', () => ({ app: { getPath: () => m.dir, getVersion: () => m.version } }));vi.mock('../../shared/wallpaper-video-manifest.json', () => ({default: {'cindy-window': {delivery: 'cdn',bytes: 3,- sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',+ sha256: m.hash,+ image: { bytes: 3, sha256: m.hash },},'cindy-studio': {delivery: 'bundled',bytes: 3,- sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',+ sha256: m.hash,+ image: { bytes: 3, sha256: m.hash },},},}));-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', () => ({ 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('../downloader/index.js', () => ({ createDownloader: () => m.download }));+vi.mock('../clientEndpointsService.js', () => ({ getClientEndpoint: m.endpoint }));+vi.mock('../maker-host/outbound-fetch.js', () => ({ guardedOutboundFetch: vi.fn() }));+vi.mock('../cindy-media/ingest.js', async () => {+ const { writeBlob } = await import('../cindy-media/blobStore');+ return {+ ingestClientWallpaper: (args: { buffer: Buffer; mimeType: string }) =>+ writeBlob({ ...args, scope: 'client-wallpaper' }),+ };+});+vi.mock('../cindy-media/recycler.js', () => ({ recycleClientWallpapers: m.recycle }));vi.mock('../custom-wallpaper-settings.js', () => ({- readReferencedClientWallpaperUrls: () => [- 'cindy-media://client-wallpaper/ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.mp4',- `cindy-media://client-wallpaper/${'c'.repeat(64)}.mp4`,- ],-}));-vi.mock('../utils/readBoundedFile.js', () => ({ readBoundedFileNoFollow: m.read }));-vi.mock('../clientEndpointsService.js', () => ({- getClientEndpoint: () => 'https://cdn.example/cindy',+ readReferencedClientWallpaperUrls: () =>+ ['.mp4', '.webp'].map((ext) => `cindy-media://client-wallpaper/${m.hash}${ext}`),}));-vi.mock('../maker-host/outbound-fetch.js', () => ({ guardedOutboundFetch: m.fetch }));-import { ensureWallpaperVideo, matchesWallpaperVideo, __testing } from '../wallpaper-video';+import { ensureWallpaperVideo, ensureWallpaperImage, __testing } from '../wallpaper-video';+import { resolveHashRef, readClientWallpaperFile } from '../cindy-media/blobStore';-const hash = createHash('sha256').update('abc').digest('hex');-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 }));+ m.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wallpaper-download-test-'));+ m.version = '1.0.0';+ m.endpoint.mockReturnValue('https://cdn.example/cindy');+ m.download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {+ fs.writeFileSync(targetPath, 'abc');+ return { path: targetPath };+ });+ m.recycle.mockResolvedValue(undefined);});+afterEach(() => fs.rmSync(m.dir, { recursive: true, force: true }));-describe('optional CDN wallpaper video', () => {- it('never accesses the cache or network for bundled official scenes', async () => {- expect(await ensureWallpaperVideo('cindy-studio')).toBeNull();- expect(m.cached).not.toHaveBeenCalled();- expect(m.fetch).not.toHaveBeenCalled();- });- it('rejects arbitrary URLs, paths and prototype keys without network access', async () => {- for (const id of ['https://example/a.mp4', '../secret', 'constructor', 'none', null])- await expect(ensureWallpaperVideo(id)).rejects.toThrow('Unsupported');- expect(m.fetch).not.toHaveBeenCalled();+function url(ext: string) {+ return `cindy-media://client-wallpaper/${m.hash}${ext}`;+}++describe('official wallpaper downloads', () => {+ it('rejects arbitrary paths, URLs, prototype keys and unknown scenes before any IO', async () => {+ for (const id of ['https://example/a.mp4', '../secret', 'constructor', 'none', null]) {+ await expect(ensureWallpaperVideo(id)).rejects.toThrow('INVALID_PARAMS');+ await expect(ensureWallpaperImage(id)).rejects.toThrow('INVALID_PARAMS');+ }+ expect(m.download).not.toHaveBeenCalled();+ expect(m.endpoint).not.toHaveBeenCalled();});- it('checks exact reviewed bytes rather than accepting a MIME or size claim', () => {- expect(matchesWallpaperVideo(Buffer.from('abc'), { bytes: 3, sha256: hash })).toBe(true);- expect(matchesWallpaperVideo(Buffer.from('abd'), { bytes: 3, sha256: hash })).toBe(false);+ it('does not download bundled entries', async () => {+ expect(await ensureWallpaperVideo('cindy-studio')).toBeNull();+ expect(m.download).not.toHaveBeenCalled();});- it('downloads once for concurrent windows and publishes a client-owned video', async () => {- const result = await Promise.all([- ensureWallpaperVideo('cindy-window'),- ensureWallpaperVideo('cindy-window'),+ it.each([+ [ensureWallpaperVideo, '.mp4'],+ [ensureWallpaperImage, '.webp'],+ ] as const)('deduplicates windows and publishes verified %s media', async (ensure, ext) => {+ expect(await Promise.all([ensure('cindy-window'), ensure('cindy-window')])).toEqual([+ url(ext),+ url(ext),]);- 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({ buffer: Buffer.from('abc'), mimeType: 'video/mp4' });- expect(m.remove).toHaveBeenCalledWith(- [url, `cindy-media://client-wallpaper/${'c'.repeat(64)}.mp4`],- '.mp4',+ expect(m.download).toHaveBeenCalledOnce();+ const options = m.download.mock.calls[0][0];+ expect(options).toMatchObject({+ sha256: m.hash,+ expectedSize: 3,+ maxBytes: 3,+ redirect: 'error',+ resume: false,+ });+ expect(options.url).toBe(`https://cdn.example/cindy/wallpapers/${m.hash}${ext}`);+ expect(options.isUrlAllowed(options.url)).toBe(true);+ expect(options.isUrlAllowed(options.url + '?redirect=1')).toBe(false);+ expect(options.isUrlAllowed('http://127.0.0.1/a')).toBe(false);+ expect((await readClientWallpaperFile(url(ext))).buffer.toString()).toBe('abc');+ expect(fs.existsSync(path.dirname(options.targetPath))).toBe(false);+ expect(m.recycle).toHaveBeenCalledWith([url('.mp4'), url('.webp')], ext);+ });+ it('reuses both files after an app upgrade, module restart and loss of network configuration', async () => {+ await ensureWallpaperVideo('cindy-window');+ await ensureWallpaperImage('cindy-window');+ expect(m.download).toHaveBeenCalledTimes(2);+ const oldPaths = ['.mp4', '.webp'].map(+ (ext) => resolveHashRef(m.hash, ext, 'client-wallpaper').absPath,);- expect(m.release).toHaveBeenCalledOnce();+ vi.resetModules();+ m.version = '2.0.0';+ m.download.mockClear().mockRejectedValue(new Error('offline'));+ m.endpoint.mockClear().mockReturnValue(null);+ const upgraded = await import('../wallpaper-video');+ expect(await upgraded.ensureWallpaperVideo('cindy-window')).toBe(url('.mp4'));+ expect(await upgraded.ensureWallpaperImage('cindy-window')).toBe(url('.webp'));+ expect(m.download).not.toHaveBeenCalled();+ expect(m.endpoint).not.toHaveBeenCalled();+ expect(oldPaths.every((file) => fs.readFileSync(file, 'utf8') === 'abc')).toBe(true);});- 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).not.toHaveBeenCalled();+ it('shares actual byte progress with late requesters and resets it when a transfer restarts', async () => {+ let finish!: () => void;+ const gate = new Promise<void>((resolve) => {+ finish = resolve;+ });+ let options!: DownloadOptions;+ m.download.mockImplementationOnce(async (request: DownloadOptions) => {+ options = request;+ request.onProgress?.({ loaded: 1, total: 99, percent: 1, speedBps: 1 });+ await gate;+ fs.writeFileSync(request.targetPath, 'abc');+ });+ const first = vi.fn();+ const firstResult = ensureWallpaperVideo('cindy-window', first);+ await vi.waitFor(() =>+ expect(first).toHaveBeenLastCalledWith({+ wallpaperId: 'cindy-window',+ kind: 'video',+ loaded: 1,+ total: 3,+ }),+ );+ const second = vi.fn();+ const secondResult = ensureWallpaperVideo('cindy-window', second);+ expect(second).toHaveBeenLastCalledWith({+ wallpaperId: 'cindy-window',+ kind: 'video',+ loaded: 1,+ total: 3,+ });+ const closingResult = ensureWallpaperVideo('cindy-window', () => {+ throw new Error('closed frame');+ });+ options.onRetry?.({ attempt: 2, delayMs: 1, cause: new Error('connection reset') });+ expect(second).toHaveBeenLastCalledWith({+ wallpaperId: 'cindy-window',+ kind: 'video',+ loaded: 0,+ total: 3,+ });+ options.onProgress?.({ loaded: 5, total: 99, percent: 5, speedBps: 1 });+ expect(second).toHaveBeenLastCalledWith({+ wallpaperId: 'cindy-window',+ kind: 'video',+ loaded: 3,+ total: 3,+ });+ finish();+ expect(await Promise.all([firstResult, secondResult, closingResult])).toEqual([+ url('.mp4'),+ url('.mp4'),+ url('.mp4'),+ ]);+ expect(m.download).toHaveBeenCalledOnce();+ const callCount = second.mock.calls.length;+ options.onProgress?.({ loaded: 1, total: 3, percent: 33, speedBps: 1 });+ expect(second).toHaveBeenCalledTimes(callCount);});- it.each([null, Buffer.from('bad')])('redownloads a missing or damaged cache', async (bytes) => {- m.cached.mockResolvedValue(hash);- m.read.mockResolvedValue(bytes);- expect(await ensureWallpaperVideo('cindy-window')).toBe(url);- expect(m.fetch).toHaveBeenCalledOnce();+ it('repairs a corrupted disk cache and reuses the repair without another download', async () => {+ await ensureWallpaperVideo('cindy-window');+ fs.writeFileSync(resolveHashRef(m.hash, '.mp4', 'client-wallpaper').absPath, 'bad');+ expect(await ensureWallpaperVideo('cindy-window')).toBe(url('.mp4'));+ expect(await ensureWallpaperVideo('cindy-window')).toBe(url('.mp4'));+ expect(m.download).toHaveBeenCalledTimes(2);+ expect((await readClientWallpaperFile(url('.mp4'))).buffer.toString()).toBe('abc');});- it.each(['404', 'offline', 'oversize', 'hash', 'length'])(- 'returns fallback on %s and backs off retries',- async (reason) => {- m.fetch.mockImplementation(async () => {- if (reason === 'offline') throw new Error('offline');- return {- response:- reason === '404'- ? new Response('', { status: 404 })- : new Response(- reason === 'oversize' ? 'abcd' : 'bad',- reason === 'length' ? { headers: { 'content-length': '100' } } : undefined,- ),- release: m.release,- };+ it.each(['offline', 'size', 'hash'])(+ 'keeps the preview on %s and allows an immediate explicit retry',+ async (failure) => {+ m.download.mockImplementationOnce(async ({ targetPath }: { targetPath: string }) => {+ if (failure === 'offline') throw new Error('offline');+ fs.writeFileSync(targetPath, failure === 'size' ? 'abcd' : 'bad');});expect(await ensureWallpaperVideo('cindy-window')).toBeNull();- expect(await ensureWallpaperVideo('cindy-window')).toBeNull();- expect(m.fetch).toHaveBeenCalledOnce();- expect(m.ingest).not.toHaveBeenCalled();- if (reason !== 'offline') expect(m.release).toHaveBeenCalledOnce();+ expect(fs.existsSync(resolveHashRef(m.hash, '.mp4', 'client-wallpaper').absPath)).toBe(false);+ expect(fs.readdirSync(m.dir).some((name) => name.startsWith('cindy-wallpaper-'))).toBe(false);+ expect(await ensureWallpaperVideo('cindy-window')).toBe(url('.mp4'));+ expect(m.download).toHaveBeenCalledTimes(2);+ },+ );+ it.each(['http://cdn.example', 'https://user:[email protected]'])(+ 'rejects unsafe CDN configuration %s',+ async (base) => {+ m.endpoint.mockReturnValue(base);+ expect(await ensureWallpaperImage('cindy-window')).toBeNull();+ expect(m.download).not.toHaveBeenCalled();},);- it('shares downloads during account transitions without an account database', async () => {- m.boundary = true;- m.fetch.mockImplementation(async () => {- m.owner = 'two';- return { response: new Response('abc'), release: m.release };- });- 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 a3264bc28a..ffe04625a2 100644--- a/apps/desktop/src/main/appearance-settings-ipc.ts+++ b/apps/desktop/src/main/appearance-settings-ipc.ts@@ -4,6 +4,7 @@ import { extractIpcError } from '../shared/ipcError.js';import {APPEARANCE_LIMITS,WALLPAPER_IDS,+ WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL,clampAppearanceWallpaperOverlay,clampAppearanceWallpaperVisibility,clampAppearanceWallpaperBlur,@@ -58,10 +59,20 @@ export function registerAppearanceSettingsIpc(): void {ipcMain.handle('appearance-settings:ensure-wallpaper-video', async (event, id: unknown) => {assertTrustedAppRendererEvent(event);const { ensureWallpaperVideo } = await import('./wallpaper-video.js');- const result = await ensureWallpaperVideo(id);+ const result = await ensureWallpaperVideo(id, (progress) => {+ event.senderFrame?.send(WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL, progress);+ });return result;});+ ipcMain.handle('appearance-settings:ensure-wallpaper-image', async (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);+ const { ensureWallpaperImage } = await import('./wallpaper-video.js');+ return ensureWallpaperImage(id, (progress) => {+ event.senderFrame?.send(WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL, progress);+ });+ });+ipcMain.handle('appearance-settings:import-wallpaper', async (event) => {assertTrustedAppRendererEvent(event);const parent = BrowserWindow.fromWebContents(event.sender);diff --git a/apps/desktop/src/main/custom-wallpaper-settings.ts b/apps/desktop/src/main/custom-wallpaper-settings.tsindex 114d793e87..73edca72c0 100644--- a/apps/desktop/src/main/custom-wallpaper-settings.ts+++ b/apps/desktop/src/main/custom-wallpaper-settings.ts@@ -57,6 +57,9 @@ export function readReferencedClientWallpaperUrls(): string[] {customUrl,...Object.values(manifest).filter((item) => item.delivery === 'cdn')- .map((item) => blobUrl(item.sha256, '.mp4', 'client-wallpaper')),+ .flatMap((item) => [+ blobUrl(item.sha256, '.mp4', 'client-wallpaper'),+ ...(item.image ? [blobUrl(item.image.sha256, '.webp', 'client-wallpaper')] : []),+ ]),].filter(Boolean);}diff --git a/apps/desktop/src/main/wallpaper-video.ts b/apps/desktop/src/main/wallpaper-video.tsindex 1d63f58d95..13d31add70 100644--- a/apps/desktop/src/main/wallpaper-video.ts+++ b/apps/desktop/src/main/wallpaper-video.ts@@ -1,5 +1,9 @@+import { app } from 'electron';import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';import manifest from '../shared/wallpaper-video-manifest.json';+import type { WallpaperDownloadProgress } from '../shared/appearanceSettings.js';import { ingestClientWallpaper } from './cindy-media/ingest.js';import { resolveHashRef, blobUrl } from './cindy-media/blobStore.js';import { withClientWallpaperLock } from './cindy-media/clientWallpaperLock.js';@@ -9,11 +13,21 @@ import { getClientEndpoint } from './clientEndpointsService.js';import { guardedOutboundFetch } from './maker-host/outbound-fetch.js';import { throwIpcError } from './utils/ipcValidate.js';import { readReferencedClientWallpaperUrls } from './custom-wallpaper-settings.js';+import { createDownloader } from './downloader/index.js';+import { createLogger } from './logger.js';type Scene = keyof typeof manifest;type Asset = { sha256: string; bytes: number };-const RETRY_MS = 5 * 60_000;-const states = new Map<Scene, { pending?: Promise<string | null>; retryAt: number }>();+type ProgressBytes = Pick<WallpaperDownloadProgress, 'loaded' | 'total'>;+type Transfer = {+ promise: Promise<string | null>;+ progress: ProgressBytes;+ listeners: Set<(progress: ProgressBytes) => void>;+};+type ProgressListener = (progress: WallpaperDownloadProgress) => void;+const pending = new Map<string, Transfer>();+const download = createDownloader();+const log = createLogger('wallpaper-assets');export function isWallpaperVideoScene(id: unknown): id is Scene {return typeof id === 'string' && Object.hasOwn(manifest, id);@@ -26,79 +40,114 @@ export function matchesWallpaperVideo(bytes: Buffer, asset: Asset): boolean {);}-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',- },- () => {},- );- let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;- try {- 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');- reader = response.body.getReader();- const chunks: Buffer[] = [];- let size = 0;- while (true) {- const { done, value } = await reader.read();- if (done) break;- size += value.byteLength;- if (size > asset.bytes) throw new Error('Wallpaper exceeds expected size');- chunks.push(Buffer.from(value));- }- const bytes = Buffer.concat(chunks);- if (!matchesWallpaperVideo(bytes, asset)) throw new Error('Wallpaper integrity mismatch');- return bytes;- } finally {- if (reader) await reader.cancel().catch(() => undefined);- else await response.body?.cancel().catch(() => undefined);- await release();- }-}+/** The cache key is the content hash, never the app version or account. Upgrades reuse it offline. */+async function ensureWallpaperAsset(+ id: unknown,+ kind: 'image' | 'video',+ onProgress?: ProgressListener,+): Promise<string | null> {+ if (!isWallpaperVideoScene(id)) throwIpcError('INVALID_PARAMS', 'Unsupported wallpaper');+ const entry = manifest[id];+ if (entry.delivery !== 'cdn') return null;+ const asset = kind === 'image' ? entry.image : entry;+ const ext = kind === 'image' ? '.webp' : '.mp4';+ const key = asset.sha256 + ext;+ let transfer = pending.get(key);+ if (!transfer) {+ const progress: ProgressBytes = { loaded: 0, total: asset.bytes };+ const listeners = new Set<(progress: ProgressBytes) => void>();+ const report = (loaded: number) => {+ progress.loaded = Number.isFinite(loaded) ? Math.max(0, Math.min(loaded, asset.bytes)) : 0;+ for (const listener of listeners) listener({ ...progress });+ };+ const operation = (async () => {+ let temporaryDirectory: string | undefined;+ try {+ const url = blobUrl(asset.sha256, ext, 'client-wallpaper');+ const cachedPath = resolveHashRef(asset.sha256, ext, 'client-wallpaper').absPath;+ const cached = await readBoundedFileNoFollow(cachedPath, asset.bytes).catch(() => null);+ // Check durable media before even resolving the CDN: offline upgrades need no network config.+ if (cached && matchesWallpaperVideo(cached, asset)) {+ report(asset.bytes);+ return url;+ }-/** 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');- if (manifest[id].delivery !== 'cdn') return null;- 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 };- states.set(id, entry);- entry.pending = (async () => {+ const base = getClientEndpoint('cdnBaseUrl');+ if (!base) throw new Error('Wallpaper CDN unavailable');+ const source = new URL(base.replace(/\/+$/, '') + '/wallpapers/' + key);+ if (source.protocol !== 'https:' || source.username || source.password)+ throw new Error('Invalid wallpaper CDN');+ temporaryDirectory = await fs.mkdtemp(path.join(app.getPath('temp'), 'cindy-wallpaper-'));+ const targetPath = path.join(temporaryDirectory, key);+ await download({+ url: source.href,+ targetPath,+ sha256: asset.sha256,+ expectedSize: asset.bytes,+ maxBytes: asset.bytes,+ redirect: 'error',+ isUrlAllowed: (candidate) => candidate === source.href,+ request: (url, init) =>+ guardedOutboundFetch(url, { ...init, credentials: 'omit' }, () => {}),+ resume: false,+ retry: { maxAttempts: 3 },+ timeout: { totalMs: 120_000 },+ logger: log,+ onProgress: ({ loaded }) => report(loaded),+ // These small files restart from zero after a failed attempt; report that truthfully.+ onRetry: () => report(0),+ });+ const bytes = await readBoundedFileNoFollow(targetPath, asset.bytes);+ if (!bytes || !matchesWallpaperVideo(bytes, asset))+ throw new Error('Invalid wallpaper download');+ const published = await withClientWallpaperLock(async () => {+ const media = await ingestClientWallpaper({+ buffer: bytes,+ mimeType: kind === 'image' ? 'image/webp' : 'video/mp4',+ });+ await recycleClientWallpapers(readReferencedClientWallpaperUrls(), ext).catch(+ () => undefined,+ );+ return media.url;+ });+ report(asset.bytes);+ return published;+ } catch {+ log.warn('Wallpaper unavailable; keeping the preview');+ return null;+ } finally {+ if (temporaryDirectory)+ await fs.rm(temporaryDirectory, { recursive: true, force: true }).catch(() => undefined);+ }+ })().finally(() => pending.delete(key));+ transfer = { promise: operation, progress, listeners };+ pending.set(key, transfer);+ }+ const notify = (progress: ProgressBytes) => {try {- const asset = manifest[id];- 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(readReferencedClientWallpaperUrls(), '.mp4').catch(- () => undefined,- );- return media.url;- });+ onProgress?.({ wallpaperId: id, kind, ...progress });} catch {- entry.retryAt = Date.now() + RETRY_MS;- return null;+ // A closing requester must not interrupt the shared transfer or other windows.}- })().finally(() => {- entry.pending = undefined;- });- return entry.pending;+ };+ if (onProgress) {+ transfer.listeners.add(notify);+ notify({ ...transfer.progress });+ }+ try {+ return await transfer.promise;+ } finally {+ transfer.listeners.delete(notify);+ }}-export const __testing = { reset: () => states.clear() };+export const ensureWallpaperVideo = (+ id: unknown,+ onProgress?: ProgressListener,+): Promise<string | null> => ensureWallpaperAsset(id, 'video', onProgress);+export const ensureWallpaperImage = (+ id: unknown,+ onProgress?: ProgressListener,+): Promise<string | null> => ensureWallpaperAsset(id, 'image', onProgress);++export const __testing = { reset: () => pending.clear() };diff --git a/apps/desktop/src/preload/__tests__/appearanceSnapshot.test.ts b/apps/desktop/src/preload/__tests__/appearanceSnapshot.test.tsindex 7b9c316b75..6906379b70 100644--- a/apps/desktop/src/preload/__tests__/appearanceSnapshot.test.ts+++ b/apps/desktop/src/preload/__tests__/appearanceSnapshot.test.ts@@ -1,15 +1,22 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { DEFAULT_APPEARANCE_SETTINGS, type AppearanceSettings } from '../../shared/appearanceSettings';+import {+ DEFAULT_APPEARANCE_SETTINGS,+ type AppearanceSettings,+ type WallpaperDownloadProgress,+ WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL,+} from '../../shared/appearanceSettings';const mocks = vi.hoisted(() => ({listeners: new Map<string, Set<(event: unknown, payload: unknown) => void>>(),expose: vi.fn(),sendSync: vi.fn(),+ invoke: vi.fn(),}));vi.mock('electron', () => ({contextBridge: { exposeInMainWorld: mocks.expose },ipcRenderer: {sendSync: mocks.sendSync,+ invoke: mocks.invoke,on: (channel: string, listener: (event: unknown, payload: unknown) => void) => {if (!mocks.listeners.has(channel)) mocks.listeners.set(channel, new Set());mocks.listeners.get(channel)!.add(listener);@@ -29,11 +36,17 @@ describe.each(['sidebar', 'resource', 'ghost-panel'])('%s appearance startup', (let bridge: {getSync(): AppearanceSettings | null;onChanged(callback: (settings: AppearanceSettings) => void): () => void;+ ensureWallpaperImage?: (id: string) => Promise<string | null>;+ ensureWallpaperVideo?: (id: string) => Promise<string | null>;+ onWallpaperDownloadProgress: (+ callback: (progress: WallpaperDownloadProgress) => void,+ ) => () => void;};beforeEach(async () => {vi.resetModules();mocks.listeners.clear();mocks.expose.mockClear();+ mocks.invoke.mockReset().mockResolvedValue('cached-media-url');mocks.sendSync.mockImplementation((channel) =>channel === 'appearance-settings:get-sync' ? DEFAULT_APPEARANCE_SETTINGS : null,);@@ -50,14 +63,32 @@ describe.each(['sidebar', 'resource', 'ghost-panel'])('%s appearance startup', (emit({ ...latest, wallpaperId: 'cindy-window' });emit(latest);expect(bridge.getSync()).toEqual(latest);- // Detached hosts remain read-only, without a new invoke capability.- expect(Object.keys(bridge).sort()).toEqual(['getSync', 'onChanged']);+ // Settings remain read-only; only app-content hosts can request official media.+ expect(Object.keys(bridge).sort()).toEqual([+ 'ensureWallpaperImage',+ 'ensureWallpaperVideo',+ 'getSync',+ 'onChanged',+ 'onWallpaperDownloadProgress',+ ]);+ });++ it('exposes only fixed official-media requests to wallpaper-capable hosts', async () => {+ await expect(bridge.ensureWallpaperImage!('cindy-window')).resolves.toBe('cached-media-url');+ await expect(bridge.ensureWallpaperVideo!('cindy-dream')).resolves.toBe('cached-media-url');+ expect(mocks.invoke.mock.calls).toEqual([+ ['appearance-settings:ensure-wallpaper-image', 'cindy-window'],+ ['appearance-settings:ensure-wallpaper-video', 'cindy-dream'],+ ]);});it('replays updates between the initial render read and effect subscription', () => {bridge.getSync();- const latest = { ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'custom' as const,- customWallpaperUrl: `cindy-media://client-wallpaper/${'b'.repeat(64)}.webp` };+ const latest = {+ ...DEFAULT_APPEARANCE_SETTINGS,+ wallpaperId: 'custom' as const,+ customWallpaperUrl: `cindy-media://client-wallpaper/${'b'.repeat(64)}.webp`,+ };emit(latest);const callback = vi.fn();const off = bridge.onChanged(callback);@@ -67,6 +98,23 @@ describe.each(['sidebar', 'resource', 'ghost-panel'])('%s appearance startup', (off();});+ it('forwards only progress data and removes the listener when unsubscribed', () => {+ const callback = vi.fn();+ const unsubscribe = bridge.onWallpaperDownloadProgress(callback);+ const progress = { wallpaperId: 'cindy-window', kind: 'image', loaded: 123, total: 456 };+ const emitProgress = () => {+ for (const listener of mocks.listeners.get(WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL) ?? []) {+ listener({ sender: 'must not cross the bridge' }, progress);+ }+ };+ emitProgress();+ expect(callback.mock.calls).toEqual([[progress]]);+ unsubscribe();+ emitProgress();+ expect(callback).toHaveBeenCalledOnce();+ expect(mocks.listeners.get(WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL)?.size).toBe(0);+ });+it('keeps the cache current after unsubscribe and replays removal on remount', () => {const latest = { ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'cindy-studio' as const };emit(latest);@@ -79,3 +127,8 @@ describe.each(['sidebar', 'resource', 'ghost-panel'])('%s appearance startup', (expect(remount.mock.calls).toEqual([[DEFAULT_APPEARANCE_SETTINGS]]);});});++it('keeps the default appearance snapshot free of download or mutation capabilities', async () => {+ const { createAppearanceSnapshotBridge } = await import('../appearanceSnapshot');+ expect(Object.keys(createAppearanceSnapshotBridge()).sort()).toEqual(['getSync', 'onChanged']);+});diff --git a/apps/desktop/src/preload/appearanceSnapshot.ts b/apps/desktop/src/preload/appearanceSnapshot.tsindex 7062dff903..f2290e7e8b 100644--- a/apps/desktop/src/preload/appearanceSnapshot.ts+++ b/apps/desktop/src/preload/appearanceSnapshot.ts@@ -1,17 +1,21 @@import { ipcRenderer } from 'electron';import type { AppearanceSettings } from '../shared/appearanceSettings';+import { createWallpaperAssetsBridge } from './wallpaperAssets';/** Read-only appearance for lazy detached renderers; no settings mutation IPC. */-export function createAppearanceSnapshotBridge() {+export function createAppearanceSnapshotBridge(options: { wallpaperAssets?: boolean } = {}) {let current = ipcRenderer.sendSync('appearance-settings:get-sync') as AppearanceSettings | null;// Keep listening even with no renderer subscribers (startup, hidden or HMR).ipcRenderer.on('appearance-settings:changed', (_event, next: AppearanceSettings) => {current = next;});return {+ // Only app-content hosts opt in. Utility appearance readers keep their narrower bridge.+ ...(options.wallpaperAssets ? createWallpaperAssetsBridge() : {}),getSync: (): AppearanceSettings | null => current,onChanged: (callback: (settings: AppearanceSettings) => void): (() => void) => {- const listener = (_event: Electron.IpcRendererEvent, next: AppearanceSettings) => callback(next);+ const listener = (_event: Electron.IpcRendererEvent, next: AppearanceSettings) =>+ callback(next);ipcRenderer.on('appearance-settings:changed', listener);// Also closes the render -> effect gap after getSync has already run.if (current) callback(current);diff --git a/apps/desktop/src/preload/ghostPanelWindowPreload.ts b/apps/desktop/src/preload/ghostPanelWindowPreload.tsindex 5deaac5c95..9b918cfdb2 100644--- a/apps/desktop/src/preload/ghostPanelWindowPreload.ts+++ b/apps/desktop/src/preload/ghostPanelWindowPreload.ts@@ -115,7 +115,7 @@ function onCurrentGhostUnreadSnapshot(return () => ipcRenderer.removeListener('ghosts:unread-snapshot', listener);}-const appearanceSnapshot = createAppearanceSnapshotBridge();+const appearanceSnapshot = createAppearanceSnapshotBridge({ wallpaperAssets: true });const fanOutFullscreenChange = (cb: (isFullscreen: boolean) => void): Unsub =>onPayload('fullscreen-change', cb);diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex a02d4208a2..0e1c06e3f1 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1,4 +1,5 @@import { createAccessibilitySupportBridge } from './accessibilitySupport';+import { createWallpaperAssetsBridge } from './wallpaperAssets';import type { CompanionImportApi, CompanionImportSelection } from '@cindy/maker-shared/companion-import';import { TASK_MIGRATION_LOCAL_CHANNEL } from '@cindy/device-link';import type { WorktreeRecycleAction, WorktreeRecycleStatus } from '../shared/worktreeRecycle';@@ -1139,7 +1140,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('page-zoom:reset'),appearanceSettings: {importWallpaper: () => ipcRenderer.invoke('appearance-settings:import-wallpaper'),- ensureWallpaperVideo: (id: string) => ipcRenderer.invoke('appearance-settings:ensure-wallpaper-video', id),+ ...createWallpaperAssetsBridge(),removeWallpaper: () => ipcRenderer.invoke('appearance-settings:remove-wallpaper'),getSync: (): AppearanceSettings | null => appearanceSettingsInfo,get: (): Promise<unknown> => ipcRenderer.invoke('appearance-settings:get'),diff --git a/apps/desktop/src/preload/resourceUsagePreload.ts b/apps/desktop/src/preload/resourceUsagePreload.tsindex 3cbb5c345d..f0cef6b9b5 100644--- a/apps/desktop/src/preload/resourceUsagePreload.ts+++ b/apps/desktop/src/preload/resourceUsagePreload.ts@@ -48,7 +48,7 @@ function readPreferredSystemLocale(): ApplicationMenuLocale {}}-const appearanceSnapshot = createAppearanceSnapshotBridge();+const appearanceSnapshot = createAppearanceSnapshotBridge({ wallpaperAssets: true });const fanOutFullscreenChange = (cb: (isFullscreen: boolean) => void): (() => void) =>onPayload('fullscreen-change', cb);diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex fdc43286c1..6cdbef6fcf 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -68,7 +68,7 @@ function readPreferredSystemLocale(): ApplicationMenuLocale {}}-const appearanceSnapshot = createAppearanceSnapshotBridge();+const appearanceSnapshot = createAppearanceSnapshotBridge({ wallpaperAssets: true });const fanOutFullscreenChange = (cb: (isFullscreen: boolean) => void): (() => void) =>onPayload('fullscreen-change', cb);diff --git a/apps/desktop/src/preload/wallpaperAssets.ts b/apps/desktop/src/preload/wallpaperAssets.tsnew file mode 100644index 0000000000..c15f430e4d--- /dev/null+++ b/apps/desktop/src/preload/wallpaperAssets.ts@@ -0,0 +1,22 @@+import { ipcRenderer } from 'electron';+import {+ WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL,+ type WallpaperDownloadProgress,+ type WallpaperId,+} from '../shared/appearanceSettings';++/** Only trusted app-content hosts expose this fixed official-media capability. */+export function createWallpaperAssetsBridge() {+ return {+ ensureWallpaperImage: (id: WallpaperId): Promise<string | null> =>+ ipcRenderer.invoke('appearance-settings:ensure-wallpaper-image', id),+ ensureWallpaperVideo: (id: WallpaperId): Promise<string | null> =>+ ipcRenderer.invoke('appearance-settings:ensure-wallpaper-video', id),+ onWallpaperDownloadProgress: (callback: (progress: WallpaperDownloadProgress) => void) => {+ const listener = (_event: Electron.IpcRendererEvent, progress: WallpaperDownloadProgress) =>+ callback(progress);+ ipcRenderer.on(WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL, listener);+ return () => ipcRenderer.removeListener(WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL, listener);+ },+ };+}diff --git a/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx b/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsxindex 975e5d9aee..18cfda8981 100644--- a/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx@@ -71,6 +71,17 @@ it.each(['sidebar', 'plugin'] as const)(const play = vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue();const pause = vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {});vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {});+ vi.stubGlobal(+ 'Image',+ class {+ src = '';+ decode = vi.fn().mockResolvedValue(undefined);+ },+ );+ const imageUrl = 'cindy-media://client-wallpaper/' + 'b'.repeat(64) + '.webp';+ const videoUrl = 'cindy-media://client-wallpaper/' + 'c'.repeat(64) + '.mp4';+ const ensureImage = vi.fn().mockResolvedValue(imageUrl);+ const ensureVideo = vi.fn().mockResolvedValue(videoUrl);document.body.innerHTML = '<div id="root"></div>';let changed!: (settings: AppearanceSettings) => void;let hiddenChanged!: (hidden: boolean) => void;@@ -85,6 +96,8 @@ it.each(['sidebar', 'plugin'] as const)(return () => {};},appearanceSettings: {+ ensureWallpaperImage: ensureImage,+ ensureWallpaperVideo: ensureVideo,getSync: () => ({...DEFAULT_APPEARANCE_SETTINGS,wallpaperId: 'cindy-window',@@ -105,6 +118,12 @@ it.each(['sidebar', 'plugin'] as const)();expect(document.documentElement.dataset.wallpaperActive).toBe('true');expect(document.querySelectorAll('video')).toHaveLength(1);+ expect(document.querySelector('video')?.getAttribute('src')).toBe(videoUrl);+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-image')).toContain(+ imageUrl,+ );+ expect(ensureImage).toHaveBeenCalledWith('cindy-window');+ expect(ensureVideo).toHaveBeenCalledWith('cindy-window');if (kind === 'sidebar') {expect(play).not.toHaveBeenCalled();expect(pause).toHaveBeenCalled();diff --git a/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-dream.webp b/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-dream.webpnew file mode 100644index 0000000000..3155ccf7bdBinary files /dev/null and b/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-dream.webp differdiff --git a/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-studio.webp b/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-studio.webpnew file mode 100644index 0000000000..ca00c9848fBinary files /dev/null and b/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-studio.webp differdiff --git a/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-window.webp b/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-window.webpnew file mode 100644index 0000000000..31783c4c71Binary files /dev/null and b/apps/desktop/src/renderer/assets/wallpapers/previews/cindy-window.webp differdiff --git a/apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx b/apps/desktop/src/renderer/components/layout/WallpaperVideo.tsxindex 027de7497b..30f8b3f1b9 100644--- a/apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx+++ b/apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx@@ -6,21 +6,22 @@ import {normalizeCustomWallpaperUrl,} from '@/../shared/appearanceSettings';import { useReducedMotion } from '@/hooks/useReducedMotion';-import { useWallpaperVideoTier } from '@/hooks/useWallpaperVideoTier';import { HIDDEN_ANIMATION_ATTR } from '@/lib/hiddenAnimationGate';-import { getWallpaperVideo, usesCdnWallpaperVideo } from '@/lib/wallpaper';+import { isSceneWallpaper } from '@/lib/wallpaper';/** One decoder and one viewport canvas. Custom videos retain a paused frame in static mode. */export function WallpaperVideo({wallpaperId,motion,customWallpaperUrl,+ officialVideoUrl,onFailure,onReady,}: {wallpaperId: WallpaperId;motion: WallpaperMotion;customWallpaperUrl?: string;+ officialVideoUrl?: string | null;onFailure?: () => void;onReady?: () => void;}) {@@ -38,62 +39,19 @@ export function WallpaperVideo({/>);}- const src = getWallpaperVideo(wallpaperId);- if (reducedMotion || !src) return null;- return (- <WallpaperPlayback key={wallpaperId} wallpaperId={wallpaperId} active={motion === 'dynamic'} />- );+ const src = officialVideoUrl;+ if (reducedMotion || !isSceneWallpaper(wallpaperId) || !src) return null;+ return <WallpaperPlayback key={wallpaperId} src={src} active={motion === 'dynamic'} />;}-type PlaybackProps = { active: boolean; onExited: () => void };--function WallpaperPlayback({ wallpaperId, active }: { wallpaperId: WallpaperId; active: boolean }) {+function WallpaperPlayback({ src, active }: { src: string; active: boolean }) {const [retained, setRetained] = useState(active);const onExited = useCallback(() => setRetained(false), []);useEffect(() => {if (active) setRetained(true);}, [active]);if (!active && !retained) return null;- const src = getWallpaperVideo(wallpaperId)!;- return usesCdnWallpaperVideo(wallpaperId) ? (- <AdaptiveWallpaper wallpaperId={wallpaperId} active={active} onExited={onExited} />- ) : (- <PlayingWallpaper src={src} active={active} onExited={onExited} />- );-}--function AdaptiveWallpaper({- wallpaperId,- active,- onExited,-}: { wallpaperId: WallpaperId } & PlaybackProps) {- const tier = useWallpaperVideoTier();- const [hdFailed, setHdFailed] = useState(false);- const [hdSrc, setHdSrc] = useState<string | null>(null);- useEffect(() => {- if (!active || tier !== 'hd' || hdFailed || hdSrc) return;- let current = true;- void window.electronAPI?.appearanceSettings- ?.ensureWallpaperVideo?.(wallpaperId)- .then((url) => {- if (current) setHdSrc(url);- })- .catch(() => undefined);- return () => {- current = false;- };- }, [wallpaperId, tier, hdFailed, hdSrc, active]);- const useHd = tier === 'hd' && !hdFailed && !!hdSrc;- const src = useHd ? hdSrc : getWallpaperVideo(wallpaperId);- return src ? (- <PlayingWallpaper- key={src}- src={src}- active={active}- onExited={onExited}- onFailure={useHd ? () => setHdFailed(true) : undefined}- />- ) : null;+ return <PlayingWallpaper key={src} src={src} active={active} onExited={onExited} />;}function PlayingWallpaper({diff --git a/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsxindex d5baf26ad8..7e3547104b 100644--- a/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx+++ b/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx@@ -9,15 +9,10 @@ import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import '@/styles/globals.css';-const state = vi.hoisted(() => ({ reduced: false, tier: 'standard', cdn: true }));+const state = vi.hoisted(() => ({ reduced: false }));const ensureVideo = vi.fn();vi.mock('@/hooks/useReducedMotion', () => ({ useReducedMotion: () => state.reduced }));-vi.mock('@/hooks/useWallpaperVideoTier', () => ({ useWallpaperVideoTier: () => state.tier }));-vi.mock('@/lib/wallpaper', () => ({- usesCdnWallpaperVideo: () => state.cdn,- getWallpaperVideo: (id: string, tier = 'standard') =>- id.startsWith('cindy-') ? `/${id}${tier === 'hd' ? '-hd' : ''}.mp4` : undefined,-}));+vi.mock('@/lib/wallpaper', () => ({ isSceneWallpaper: (id: string) => id.startsWith('cindy-') }));describe('dynamic wallpaper lifecycle', () => {it('keeps visibility on the video over an opaque theme backing without an independent veil', () => {@@ -48,8 +43,6 @@ describe('dynamic wallpaper lifecycle', () => {});beforeEach(() => {state.reduced = false;- state.tier = 'standard';- state.cdn = true;ensureVideo.mockReset().mockResolvedValue('/cindy-window-hd.mp4');vi.stubGlobal('electronAPI', { appearanceSettings: { ensureWallpaperVideo: ensureVideo } });vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue();@@ -64,13 +57,24 @@ describe('dynamic wallpaper lifecycle', () => {vi.useRealTimers();});it('does not create a decoder for static, reduced motion or unsupported artwork', () => {- state.cdn = false;- const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="static" />);+ const { rerender } = render(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="static"+ />,+ );expect(document.querySelector('video')).toBeNull();rerender(<WallpaperVideo wallpaperId="none" motion="dynamic" />);expect(document.querySelector('video')).toBeNull();state.reduced = true;- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ rerender(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );expect(document.querySelector('video')).toBeNull();expect(ensureVideo).not.toHaveBeenCalled();});@@ -118,8 +122,13 @@ describe('dynamic wallpaper lifecycle', () => {});it('shows only decoded frames, pauses with the shared hidden gate, and releases on static', async () => {vi.useFakeTimers();- state.cdn = false;- const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ const { rerender } = render(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );const video = document.querySelector('video')!;video.parentElement!.style.transitionDuration = '200ms';expect(video.muted && video.loop).toBe(true);@@ -130,7 +139,13 @@ describe('dynamic wallpaper lifecycle', () => {expect(video.pause).toHaveBeenCalled();await act(async () => document.documentElement.removeAttribute(HIDDEN_ANIMATION_ATTR));expect(video.play).toHaveBeenCalledTimes(2);- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="static" />);+ rerender(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="static"+ />,+ );expect(document.querySelector('video')).toBe(video);expect(video.getAttribute('src')).not.toBeNull();// DOM removal precedes passive decoder cleanup. Flush the exit timer and@@ -145,15 +160,26 @@ describe('dynamic wallpaper lifecycle', () => {});it('fades decoded video over the still, retaining it only until the exit finishes', () => {vi.useFakeTimers();- state.cdn = false;- const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ const { rerender } = render(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );const video = document.querySelector('video')!;const layer = video.parentElement!;layer.style.transitionDuration = '0.2s';expect(layer.style.opacity).toBe('0');fireEvent.playing(video);expect(layer.style.opacity).toBe('1');- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="static" />);+ rerender(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="static"+ />,+ );expect(layer.style.opacity).toBe('0');expect(document.querySelector('video')).toBe(video);expect(document.documentElement.dataset.wallpaperMotion).toBe('dynamic');@@ -166,142 +192,127 @@ describe('dynamic wallpaper lifecycle', () => {});it('reverses a rapid toggle without replacing the decoder or leaving a stale exit timer', () => {vi.useFakeTimers();- state.cdn = false;- const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ const { rerender } = render(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );const video = document.querySelector('video')!;video.parentElement!.style.transitionDuration = '200ms';fireEvent.playing(video);- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="static" />);+ rerender(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="static"+ />,+ );act(() => vi.advanceTimersByTime(100));- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ rerender(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );act(() => vi.advanceTimersByTime(250));expect(document.querySelector('video')).toBe(video);expect(video.parentElement!.style.opacity).toBe('1');- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="static" />);+ rerender(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="static"+ />,+ );act(() => vi.advanceTimersByTime(200));expect(document.querySelector('video')).toBeNull();expect(video.getAttribute('src')).toBeNull();});it('releases immediately if reduced motion is enabled during a fade', () => {- state.cdn = false;- const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ const { rerender } = render(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );const video = document.querySelector('video')!;fireEvent.playing(video);state.reduced = true;- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ rerender(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );expect(document.querySelector('video')).toBeNull();expect(video.getAttribute('src')).toBeNull();});it('keeps the still fallback when decode or playback fails', async () => {- state.cdn = false;vi.mocked(HTMLMediaElement.prototype.play).mockRejectedValueOnce(new Error('decode failed'));- render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ render(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );await waitFor(() => expect(document.querySelector('video')).toBeNull());expect(document.documentElement.dataset.wallpaperMotion).toBeUndefined();});it('switches scenes without retaining a second decoder', () => {- state.cdn = false;- const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);+ const { rerender } = render(+ <WallpaperVideo+ officialVideoUrl="/cindy-window.mp4"+ wallpaperId="cindy-window"+ motion="dynamic"+ />,+ );const old = document.querySelector('video')!;fireEvent.playing(old);- rerender(<WallpaperVideo wallpaperId="cindy-dream" motion="dynamic" />);+ rerender(+ <WallpaperVideo+ officialVideoUrl="/cindy-dream.mp4"+ wallpaperId="cindy-dream"+ motion="dynamic"+ />,+ );expect(document.querySelectorAll('video')).toHaveLength(1);expect(old.getAttribute('src')).toBeNull();expect(document.documentElement.dataset.wallpaperMotion).toBeUndefined();});- it('releases the previous tier and keeps the still visible until the new video plays', async () => {+ it('keeps the static background until the downloaded video is available', () => {const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);- const standard = document.querySelector('video')!;- fireEvent.playing(standard);- state.tier = 'hd';- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);- // A new DOM node can precede passive cleanup of the old decoder. Wait for- // both lifecycle obligations, not just the mutation observer's DOM signal.- await waitFor(() => {- expect(document.querySelector('video')!.src).toContain('-hd.mp4');- expect(standard.getAttribute('src')).toBeNull();- });- const hd = document.querySelector('video')!;- expect(hd.src).toContain('cindy-window-hd.mp4');- expect(document.querySelectorAll('video')).toHaveLength(1);- expect(standard.getAttribute('src')).toBeNull();- expect(document.documentElement.dataset.wallpaperMotion).toBeUndefined();- fireEvent.playing(hd);- expect(document.documentElement.dataset.wallpaperMotion).toBe('dynamic');- state.tier = 'standard';- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);- expect(hd.getAttribute('src')).toBeNull();- expect(document.querySelector('video')!.src).not.toContain('-hd');- });- it.each(['cindy-window', 'cindy-studio', 'cindy-dream'] as const)(- 'plays bundled %s without requesting CDN or reloading on resize',- async (id) => {- state.cdn = false;- const { rerender } = render(<WallpaperVideo wallpaperId={id} motion="dynamic" />);- const original = document.querySelector('video');- state.tier = 'hd';- rerender(<WallpaperVideo wallpaperId={id} motion="dynamic" />);- await act(async () => {});- expect(document.querySelector('video')).toBe(original);- expect(ensureVideo).not.toHaveBeenCalled();- },- );- it.each(['error', 'rejection'])(- 'falls back from HD once on %s, then to a still if standard fails',- async (failure) => {- state.tier = 'hd';- ensureVideo.mockImplementation(async () => {- if (failure === 'rejection')- vi.mocked(HTMLMediaElement.prototype.play).mockRejectedValueOnce(- new Error('unsupported HD'),- );- return '/cindy-dream-hd.mp4';- });- const { rerender } = render(<WallpaperVideo wallpaperId="cindy-dream" motion="dynamic" />);- if (failure === 'error') {- await waitFor(() => expect(document.querySelector('video')!.src).toContain('-hd.mp4'));- fireEvent.error(document.querySelector('video')!);- }- await act(async () => {});- await waitFor(() =>- expect(document.querySelector('video')!.src).toContain('/cindy-dream.mp4'),- );- const standard = document.querySelector('video')!;- state.tier = 'standard';- rerender(<WallpaperVideo wallpaperId="cindy-dream" motion="dynamic" />);- state.tier = 'hd';- rerender(<WallpaperVideo wallpaperId="cindy-dream" motion="dynamic" />);- expect(document.querySelector('video')).toBe(standard);- fireEvent.error(standard);- expect(document.querySelector('video')).toBeNull();- expect(document.documentElement.dataset.wallpaperMotion).toBeUndefined();- },- );- it.each(['missing', 'offline'])('keeps playing standard when CDN is %s', async (reason) => {- state.tier = 'hd';- if (reason === 'missing') ensureVideo.mockResolvedValue(null);- else ensureVideo.mockRejectedValue(new Error('offline'));- render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);- const standard = document.querySelector('video');- await act(async () => {});- expect(document.querySelector('video')).toBe(standard);- expect(ensureVideo).toHaveBeenCalledOnce();- });- it('ignores a completed download after switching to static or another scene', async () => {- state.tier = 'hd';- let finish!: (url: string) => void;- ensureVideo.mockReturnValue(- new Promise<string>((resolve) => {- finish = resolve;- }),+ expect(document.querySelector('video')).toBeNull();+ rerender(+ <WallpaperVideo wallpaperId="cindy-window" motion="dynamic" officialVideoUrl="/cached.mp4" />,);+ const video = document.querySelector('video')!;+ expect(video.parentElement!.style.opacity).toBe('0');+ fireEvent.playing(video);+ expect(video.parentElement!.style.opacity).toBe('1');+ });+ it('does not create a decoder when a download completes after motion is disabled', () => {const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);- rerender(<WallpaperVideo wallpaperId="cindy-window" motion="static" />);- await act(async () => finish('/old-hd.mp4'));+ rerender(+ <WallpaperVideo wallpaperId="cindy-window" motion="static" officialVideoUrl="/cached.mp4" />,+ );expect(document.querySelector('video')).toBeNull();- ensureVideo.mockResolvedValue(null);- rerender(<WallpaperVideo wallpaperId="cindy-dream" motion="dynamic" />);- await act(async () => {});- expect(document.querySelector('video')!.src).toContain('/cindy-dream.mp4');+ });+ it('keeps the same downloaded decoder when the window changes size', () => {+ const { rerender } = render(+ <WallpaperVideo wallpaperId="cindy-window" motion="dynamic" officialVideoUrl="/cached.mp4" />,+ );+ const video = document.querySelector('video');+ fireEvent(window, new Event('resize'));+ rerender(+ <WallpaperVideo wallpaperId="cindy-window" motion="dynamic" officialVideoUrl="/cached.mp4" />,+ );+ expect(document.querySelector('video')).toBe(video);+ expect(ensureVideo).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx b/apps/desktop/src/renderer/components/settings/WallpaperSection.tsxindex 45c5a45c67..6f8334bd82 100644--- a/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx+++ b/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx@@ -1,6 +1,6 @@import { useTranslation } from 'react-i18next';import { RotateCcw, ImagePlus, Film } from 'lucide-react';-import { useEffect, useCallback, useState } from 'react';+import { useEffect, useCallback, useId, useState } from 'react';import { extractIpcError } from '@/utils/ipcError';import { Button } from '@/components/ui/button';@@ -27,6 +27,7 @@ export function WallpaperSection() {const { t } = useTranslation();const [busy, setBusy] = useState(false);const [error, setError] = useState('');+ const downloadStatusId = useId();const {wallpaperId,wallpaperOverlay,@@ -36,6 +37,10 @@ export function WallpaperSection() {wallpaperMotion,customWallpaperUrl,playbackFailed,+ downloadPending,+ downloadFailed,+ downloadProgress,+ retryDownload,setWallpaper,setVisibility,setBlur,@@ -131,6 +136,9 @@ export function WallpaperSection() {>{[...WALLPAPER_OPTIONS, { id: 'custom' as const }].map((option) => {const selected = wallpaperId === option.id;+ const downloading = selected && isSceneWallpaper(option.id) && downloadPending;+ const retryable =+ selected && isSceneWallpaper(option.id) && downloadFailed && !downloadPending;const background =option.id === 'custom' && customWallpaperUrl && !customVideo? `url("${customWallpaperUrl}")`@@ -142,12 +150,15 @@ export function WallpaperSection() {role="radio"aria-checked={selected}aria-label={t('settings.appearance.wallpaper.options.' + option.id)}+ aria-busy={downloading || undefined}+ aria-describedby={downloading || retryable ? downloadStatusId : undefined}+ title={retryable ? t('settings.appearance.wallpaper.retryDownload') : undefined}disabled={busy}- onClick={() =>- option.id === 'custom' && !customWallpaperUrl- ? void chooseWallpaper()- : setWallpaper(option.id)- }+ onClick={() => {+ if (retryable) retryDownload();+ else if (option.id === 'custom' && !customWallpaperUrl) void chooseWallpaper();+ else setWallpaper(option.id);+ }}className={cn('flex min-w-0 flex-col gap-2 rounded-xl text-left transition-colors','focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--settings-theme-icon-active)]',@@ -182,6 +193,36 @@ export function WallpaperSection() {{t('settings.appearance.wallpaper.nonePreview')}</span>) : null}+ {downloading && (+ <span+ role="progressbar"+ aria-label={t('settings.appearance.wallpaper.downloading')}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.round(downloadProgress * 100)}+ className="absolute inset-0"+ >+ <span+ aria-hidden="true"+ className="absolute inset-0 origin-bottom bg-[color-mix(in_srgb,var(--settings-input-bg)_75%,transparent)] transition-transform duration-[var(--motion-fast)] ease-[var(--motion-ease-out)] motion-reduce:transition-none"+ style={{ transform: `scaleY(${downloadProgress})` }}+ />+ <span id={downloadStatusId} className="sr-only">+ {t('settings.appearance.wallpaper.downloading')}+ </span>+ </span>+ )}+ {retryable && (+ <span+ role="status"+ className="absolute inset-0 flex items-center justify-center bg-[color-mix(in_srgb,var(--settings-input-bg)_75%,transparent)] text-[var(--text-primary)]"+ >+ <RotateCcw size={24} aria-hidden="true" />+ <span id={downloadStatusId} className="sr-only">+ {`${t('settings.appearance.wallpaper.downloadFailed')} ${t('settings.appearance.wallpaper.retryDownload')}`}+ </span>+ </span>+ )}</span><spanclassName={cn(diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WallpaperSection.download.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WallpaperSection.download.test.tsxnew file mode 100644index 0000000000..0cc28fc0b2--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/WallpaperSection.download.test.tsx@@ -0,0 +1,124 @@+// @vitest-environment jsdom+import React from 'react';+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { WallpaperSection } from '../WallpaperSection';+import { DEFAULT_APPEARANCE_SETTINGS } from '@/../shared/appearanceSettings';++const state = vi.hoisted(() => ({+ pending: false,+ failed: false,+ progress: 0,+ retry: vi.fn(),+ select: vi.fn(),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/hooks/useWallpaperSettings', () => ({+ useWallpaperSettings: () => ({+ ...DEFAULT_APPEARANCE_SETTINGS,+ wallpaperId: 'cindy-window',+ visibility: 1,+ downloadPending: state.pending,+ downloadFailed: state.failed,+ downloadProgress: state.progress,+ retryDownload: state.retry,+ setWallpaper: state.select,+ setVisibility: vi.fn(),+ setBlur: vi.fn(),+ previewBlur: vi.fn(),+ setMotion: vi.fn(),+ resetWallpaper: vi.fn(),+ }),+}));+beforeEach(() => {+ state.pending = false;+ state.failed = false;+ state.progress = 0;+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+});+afterEach(() => {+ cleanup();+ state.retry.mockReset();+ state.select.mockReset();+ vi.unstubAllGlobals();+});++describe('wallpaper download feedback', () => {+ it('shows pending work only over the selected thumbnail, then removes it on completion', () => {+ state.pending = true;+ const { rerender } = render(<WallpaperSection />);+ const selected = screen.getByRole('radio', {+ name: 'settings.appearance.wallpaper.options.cindy-window',+ });+ const status = within(selected).getByRole('progressbar');+ expect(screen.getAllByRole('progressbar')).toEqual([status]);+ expect(status.getAttribute('aria-valuenow')).toBe('0');+ expect(selected.getAttribute('aria-busy')).toBe('true');+ // The status remains available to assistive technology without a visible text row.+ const description = within(status).getByText('settings.appearance.wallpaper.downloading');+ expect(description.classList.contains('sr-only')).toBe(true);+ expect(selected.getAttribute('aria-describedby')).toBe(description.id);+ expect(+ within(+ screen.getByRole('radio', {+ name: 'settings.appearance.wallpaper.options.cindy-studio',+ }),+ ).queryByRole('progressbar'),+ ).toBeNull();+ for (const progress of [0.25, 0.75, 1]) {+ state.progress = progress;+ rerender(<WallpaperSection />);+ expect(status.getAttribute('aria-valuenow')).toBe(String(progress * 100));+ const fill = status.querySelector<HTMLElement>('[aria-hidden="true"]')!;+ expect(fill.classList.contains('origin-bottom')).toBe(true);+ expect(fill.style.transform).toBe(`scaleY(${progress})`);+ }+ state.pending = false;+ rerender(<WallpaperSection />);+ expect(screen.queryByRole('status')).toBeNull();+ expect(screen.queryByRole('progressbar')).toBeNull();+ expect(selected.hasAttribute('aria-busy')).toBe(false);+ expect(selected.hasAttribute('aria-describedby')).toBe(false);+ });++ it('retries from the failed thumbnail while other thumbnails still change the selection', () => {+ state.failed = true;+ const { rerender } = render(<WallpaperSection />);+ const selected = screen.getByRole('radio', {+ name: 'settings.appearance.wallpaper.options.cindy-window',+ });+ expect(within(selected).getByRole('status').textContent).toContain('wallpaper.downloadFailed');+ expect(selected.title).toBe('settings.appearance.wallpaper.retryDownload');+ expect(+ screen.queryByRole('button', { name: 'settings.appearance.wallpaper.retryDownload' }),+ ).toBeNull();+ fireEvent.click(selected);+ expect(state.retry).toHaveBeenCalledOnce();+ expect(state.select).not.toHaveBeenCalled();+ fireEvent.click(+ screen.getByRole('radio', {+ name: 'settings.appearance.wallpaper.options.cindy-studio',+ }),+ );+ expect(state.select).toHaveBeenCalledWith('cindy-studio');+ expect(state.retry).toHaveBeenCalledOnce();++ state.pending = true;+ rerender(<WallpaperSection />);+ expect(selected.hasAttribute('title')).toBe(false);+ expect(selected.getAttribute('aria-busy')).toBe('true');+ fireEvent.click(selected);+ expect(state.retry).toHaveBeenCalledOnce();+ state.pending = false;+ state.failed = false;+ rerender(<WallpaperSection />);+ expect(screen.queryByRole('status')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperAsset.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperAsset.test.tsxnew file mode 100644index 0000000000..e2e0672da2--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperAsset.test.tsx@@ -0,0 +1,166 @@+// @vitest-environment jsdom+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { useWallpaperAsset } from '../useWallpaperAsset';+import type { WallpaperId, WallpaperDownloadProgress } from '@/../shared/appearanceSettings';+import manifest from '@/../shared/wallpaper-video-manifest.json';++const image = vi.fn();+const video = vi.fn();+const decode = vi.fn();+const progressListeners = new Set<(progress: WallpaperDownloadProgress) => void>();+const emit = (progress: WallpaperDownloadProgress) => {+ for (const listener of progressListeners) listener(progress);+};+beforeEach(() => {+ progressListeners.clear();+ image.mockReset().mockResolvedValue('cindy-media://client-wallpaper/image.webp');+ video.mockReset().mockResolvedValue('cindy-media://client-wallpaper/video.mp4');+ decode.mockReset().mockResolvedValue(undefined);+ vi.stubGlobal('electronAPI', {+ appearanceSettings: {+ ensureWallpaperImage: image,+ ensureWallpaperVideo: video,+ onWallpaperDownloadProgress: (callback: (progress: WallpaperDownloadProgress) => void) => {+ progressListeners.add(callback);+ return () => progressListeners.delete(callback);+ },+ },+ });+ vi.stubGlobal(+ 'Image',+ class {+ src = '';+ decode = decode;+ },+ );+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('on-demand wallpaper assets', () => {+ it('tracks only the selected asset bytes, accepts retry resets and unsubscribes after completion', async () => {+ let finish!: (url: string) => void;+ image.mockReturnValueOnce(+ new Promise<string>((resolve) => {+ finish = resolve;+ }),+ );+ const total = manifest['cindy-window'].image.bytes;+ const { result, rerender, unmount } = renderHook(+ ({ enabled }) => useWallpaperAsset('cindy-window', 'image', enabled),+ { initialProps: { enabled: true } },+ );+ const progress = {+ wallpaperId: 'cindy-window' as const,+ kind: 'image' as const,+ loaded: total / 2,+ total,+ };+ act(() => {+ emit({ ...progress, wallpaperId: 'cindy-dream' });+ emit({ ...progress, kind: 'video' });+ emit({ ...progress, total: 123 });+ emit({ ...progress, loaded: Number.NaN });+ });+ expect(result.current.loaded).toBe(0);+ act(() => emit(progress));+ expect(result.current.loaded).toBe(total / 2);+ expect(result.current.total).toBe(total);+ act(() => emit({ ...progress, loaded: 0 }));+ expect(result.current.loaded).toBe(0);+ await act(async () => finish('cindy-media://client-wallpaper/image.webp'));+ expect(result.current.loaded).toBe(total);+ expect(progressListeners.size).toBe(0);+ rerender({ enabled: false });+ expect(result.current.total).toBe(0);+ expect(result.current.loaded).toBe(0);+ unmount();+ expect(progressListeners.size).toBe(0);+ });+ it('does not fetch absent/custom scenes or disabled video, and requests only the selected image', async () => {+ const { rerender } = renderHook(+ ({ id, enabled }: { id: WallpaperId; enabled: boolean }) => {+ useWallpaperAsset(id, 'image', true);+ return useWallpaperAsset(id, 'video', enabled);+ },+ { initialProps: { id: 'none' as WallpaperId, enabled: false } },+ );+ rerender({ id: 'custom', enabled: false });+ expect(image).not.toHaveBeenCalled();+ expect(video).not.toHaveBeenCalled();+ rerender({ id: 'cindy-window', enabled: false });+ await waitFor(() => expect(decode).toHaveBeenCalledOnce());+ expect(image).toHaveBeenCalledWith('cindy-window');+ expect(video).not.toHaveBeenCalled();+ rerender({ id: 'cindy-window', enabled: true });+ await waitFor(() => expect(video).toHaveBeenCalledOnce());+ });+ it('downloads video even in a small window and reuses the resolved source when toggled', async () => {+ const { result, rerender } = renderHook(+ ({ enabled }) => useWallpaperAsset('cindy-window', 'video', enabled),+ { initialProps: { enabled: true } },+ );+ await waitFor(() => expect(result.current.url).toContain('video.mp4'));+ rerender({ enabled: false });+ rerender({ enabled: true });+ expect(video).toHaveBeenCalledOnce();+ });+ it('never displays a late result belonging to another selection', async () => {+ let finish!: (url: string) => void;+ image.mockReturnValueOnce(+ new Promise<string>((resolve) => {+ finish = resolve;+ }),+ );+ const { result, rerender } = renderHook(+ ({ id }: { id: WallpaperId }) => useWallpaperAsset(id, 'image', true),+ { initialProps: { id: 'cindy-window' as WallpaperId } },+ );+ rerender({ id: 'cindy-dream' });+ await waitFor(() => expect(result.current.url).toContain('image.webp'));+ await act(async () => finish('cindy-media://client-wallpaper/old.webp'));+ expect(result.current.url).toContain('image.webp');+ });+ it('keeps the preview until an image has decoded and permits retry after a decode failure', async () => {+ decode.mockRejectedValueOnce(new Error('decode'));+ const { result } = renderHook(() => useWallpaperAsset('cindy-window', 'image', true));+ await waitFor(() => expect(result.current.failed).toBe(true));+ expect(result.current.url).toBeNull();+ act(() => result.current.retry());+ await waitFor(() => expect(result.current.url).toContain('image.webp'));+ expect(result.current.failed).toBe(false);+ });+ it('retries after network recovery, caps automatic attempts and keeps manual retry available', async () => {+ vi.useFakeTimers();+ video.mockResolvedValue(null);+ const { result } = renderHook(() => useWallpaperAsset('cindy-window', 'video', true));+ await act(async () => {});+ expect(result.current.failed).toBe(true);+ await act(async () => window.dispatchEvent(new Event('online')));+ await act(async () => vi.advanceTimersByTimeAsync(30_000));+ await act(async () => vi.advanceTimersByTimeAsync(120_000));+ await act(async () => window.dispatchEvent(new Event('online')));+ expect(video).toHaveBeenCalledTimes(3);+ video.mockResolvedValue('cindy-media://client-wallpaper/video.mp4');+ await act(async () => result.current.retry());+ expect(video).toHaveBeenCalledTimes(4);+ expect(result.current.url).toContain('video.mp4');+ });+ it('stops automatic retries when the user disables the wallpaper', async () => {+ vi.useFakeTimers();+ video.mockResolvedValue(null);+ const { result, rerender } = renderHook(+ ({ enabled }) => useWallpaperAsset('cindy-window', 'video', enabled),+ { initialProps: { enabled: true } },+ );+ await act(async () => {});+ rerender({ enabled: false });+ await act(async () => vi.advanceTimersByTimeAsync(60_000));+ expect(video).toHaveBeenCalledOnce();+ expect(result.current.failed).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsxindex 24d4251124..8d53cc0f61 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx+++ b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx@@ -4,6 +4,8 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libraimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { WallpaperSettingsProvider, useWallpaperSettings } from '../useWallpaperSettings';import { DEFAULT_APPEARANCE_SETTINGS } from '@/../shared/appearanceSettings';+import type { WallpaperDownloadProgress } from '@/../shared/appearanceSettings';+import manifest from '@/../shared/wallpaper-video-manifest.json';function Controls() {const settings = useWallpaperSettings();@@ -12,12 +14,14 @@ function Controls() {<button onClick={() => settings.setWallpaper('cindy-window')}>Choose</button><button onClick={settings.resetWallpaper}>Reset</button><button onClick={() => settings.setMotion('dynamic')}>Animate</button>+ <button onClick={() => settings.setMotion('static')}>Static</button><button onClick={() => settings.setVisibility(1)}>Show Fully</button><button onClick={() => settings.setVisibility(0)}>Hide</button><button onClick={() => settings.setBlur(12)}>Blur</button><button onClick={() => settings.setBlur(0)}>Clear Blur</button><span data-testid="visibility">{settings.visibility}</span><span data-testid="motion">{settings.wallpaperMotion}</span>+ <span data-testid="download-progress">{settings.downloadProgress}</span></>);}@@ -36,6 +40,54 @@ afterEach(() => {});describe('application wallpaper lifecycle', () => {+ it('weights required image and video progress by bytes, excluding video in static mode', async () => {+ const listeners = new Set<(progress: WallpaperDownloadProgress) => void>();+ vi.stubGlobal('electronAPI', {+ appearanceSettings: {+ getSync: () => ({+ ...DEFAULT_APPEARANCE_SETTINGS,+ wallpaperId: 'cindy-window',+ wallpaperMotion: 'dynamic',+ }),+ onChanged: () => () => {},+ setPatch: vi.fn().mockResolvedValue(undefined),+ ensureWallpaperImage: () => new Promise(() => {}),+ ensureWallpaperVideo: () => new Promise(() => {}),+ onWallpaperDownloadProgress: (fn: (progress: WallpaperDownloadProgress) => void) => {+ listeners.add(fn);+ return () => listeners.delete(fn);+ },+ },+ });+ render(+ <WallpaperSettingsProvider>+ <Controls />+ </WallpaperSettingsProvider>,+ );+ const imageTotal = manifest['cindy-window'].image.bytes;+ const videoTotal = manifest['cindy-window'].bytes;+ act(() => {+ for (const listener of listeners) {+ listener({+ wallpaperId: 'cindy-window',+ kind: 'image',+ loaded: imageTotal / 2,+ total: imageTotal,+ });+ listener({+ wallpaperId: 'cindy-window',+ kind: 'video',+ loaded: videoTotal / 4,+ total: videoTotal,+ });+ }+ });+ expect(Number(screen.getByTestId('download-progress').textContent)).toBeCloseTo(+ (imageTotal / 2 + videoTotal / 4) / (imageTotal + videoTotal),+ );+ fireEvent.click(screen.getByText('Static'));+ expect(Number(screen.getByTestId('download-progress').textContent)).toBe(0.5);+ });it.each(['webp', 'mp4'])('applies blur to %s, follows window updates and clears on hide/reset',async (ext) => {diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperVideoTier.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperVideoTier.test.tsdeleted file mode 100644index b148dc3dd4..0000000000--- a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperVideoTier.test.ts+++ /dev/null@@ -1,65 +0,0 @@-// @vitest-environment jsdom-import { act, cleanup, renderHook } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { chooseWallpaperVideoTier, useWallpaperVideoTier } from '../useWallpaperVideoTier';--afterEach(() => {- cleanup();- vi.unstubAllGlobals();- vi.useRealTimers();-});--describe('wallpaper video resolution', () => {- it('uses cover-fit physical pixels, including portrait windows and OS scaling', () => {- expect(chooseWallpaperVideoTier(1440, 900, 1)).toBe('standard');- expect(chooseWallpaperVideoTier(1920, 1080, 2)).toBe('hd');- expect(chooseWallpaperVideoTier(2560, 1440, 1)).toBe('hd');- expect(chooseWallpaperVideoTier(800, 1300, 1)).toBe('hd');- expect(chooseWallpaperVideoTier(1000, 700, 1.5)).toBe('standard');- });- it('retains the current tier near the boundary', () => {- expect(chooseWallpaperVideoTier(1800, 900, 1, 'hd')).toBe('hd');- expect(chooseWallpaperVideoTier(1800, 900, 1, 'standard')).toBe('standard');- expect(chooseWallpaperVideoTier(1600, 900, 1, 'hd')).toBe('standard');- });- it('waits for resizing to settle and observes monitor DPI changes without a resize', () => {- vi.useFakeTimers();- vi.stubGlobal('innerWidth', 1440);- vi.stubGlobal('innerHeight', 900);- vi.stubGlobal('devicePixelRatio', 1);- const queries: Array<EventTarget & { media: string }> = [];- vi.stubGlobal('matchMedia', vi.fn((media: string) => {- const query = Object.assign(new EventTarget(), { media });- queries.push(query);- return query;- }));- const { result, unmount } = renderHook(() => useWallpaperVideoTier());- expect(result.current).toBe('standard');- act(() => {- vi.stubGlobal('innerWidth', 2560);- window.dispatchEvent(new Event('resize'));- vi.advanceTimersByTime(200);- vi.stubGlobal('innerWidth', 1440);- window.dispatchEvent(new Event('resize'));- vi.advanceTimersByTime(350);- });- expect(result.current).toBe('standard');- act(() => {- vi.stubGlobal('devicePixelRatio', 2);- queries[0].dispatchEvent(new Event('change'));- vi.advanceTimersByTime(349);- });- expect(result.current).toBe('standard');- act(() => vi.advanceTimersByTime(1));- expect(result.current).toBe('hd');- expect(queries[1].media).toContain('2dppx');- act(() => {- vi.stubGlobal('devicePixelRatio', 1);- queries[1].dispatchEvent(new Event('change'));- vi.advanceTimersByTime(350);- });- expect(result.current).toBe('standard');- unmount();- expect(vi.getTimerCount()).toBe(0);- });-});diff --git a/apps/desktop/src/renderer/hooks/useWallpaperAsset.ts b/apps/desktop/src/renderer/hooks/useWallpaperAsset.tsnew file mode 100644index 0000000000..98f9d3908a--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useWallpaperAsset.ts@@ -0,0 +1,92 @@+import { useCallback, useEffect, useState } from 'react';+import type { WallpaperId } from '@/../shared/appearanceSettings';+import { isSceneWallpaper } from '@/lib/wallpaper';+import manifest from '@/../shared/wallpaper-video-manifest.json';++type AssetState = {+ key: string;+ url: string | null;+ status: 'loading' | 'ready' | 'failed';+ loaded: number;+};++/** Only selected media is requested. Main owns durable caching and cross-window deduplication. */+export function useWallpaperAsset(id: WallpaperId, kind: 'image' | 'video', enabled: boolean) {+ const key = `${id}:${kind}`;+ const [state, setState] = useState<AssetState | null>(null);+ const [attempt, setAttempt] = useState(0);+ const retry = useCallback(() => setAttempt((value) => value + 1), []);+ const active = enabled && isSceneWallpaper(id);+ const entry = isSceneWallpaper(id) ? manifest[id] : null;+ const total = entry ? (kind === 'image' ? entry.image.bytes : entry.bytes) : 0;+ const url = state?.key === key ? state.url : null;++ useEffect(() => {+ if (!active || url) return;+ const bridge = window.electronAPI?.appearanceSettings;+ const ensure = kind === 'image' ? bridge?.ensureWallpaperImage : bridge?.ensureWallpaperVideo;+ if (!ensure) return;+ let current = true;+ let running = false;+ let automaticRetries = 0;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const unsubscribe = bridge?.onWallpaperDownloadProgress?.((progress) => {+ if (!current || !running || progress.wallpaperId !== id || progress.kind !== kind) return;+ if (!Number.isFinite(progress.loaded) || progress.total !== total) return;+ setState((previous) =>+ previous?.key === key && previous.status === 'loading'+ ? { ...previous, loaded: Math.max(0, Math.min(total, progress.loaded)) }+ : previous,+ );+ });+ const run = async () => {+ if (!current || running) return;+ running = true;+ clearTimeout(timer);+ setState({ key, url: null, status: 'loading', loaded: 0 });+ let downloaded: string | null = null;+ try {+ downloaded = await ensure(id);+ if (downloaded && kind === 'image') {+ const image = new Image();+ image.src = downloaded;+ await image.decode();+ }+ } catch {+ downloaded = null;+ }+ running = false;+ if (!current) return;+ setState((previous) => ({+ key,+ url: downloaded,+ status: downloaded ? 'ready' : 'failed',+ loaded: downloaded ? total : previous?.key === key ? previous.loaded : 0,+ }));+ if (!downloaded && automaticRetries < 2) timer = setTimeout(retryAutomatically, 30_000);+ };+ const retryAutomatically = () => {+ if (!current || running || automaticRetries >= 2) return;+ automaticRetries++;+ void run();+ };+ window.addEventListener('online', retryAutomatically);+ void run();+ return () => {+ current = false;+ clearTimeout(timer);+ unsubscribe?.();+ window.removeEventListener('online', retryAutomatically);+ // Small transfers can finish into the shared cache; never cancel another window's request.+ };+ }, [active, id, key, kind, attempt, url, total]);++ return {+ url,+ loading: active && !url && state?.key === key && state.status === 'loading',+ failed: active && state?.key === key && state.status === 'failed',+ loaded: active ? (url ? total : state?.key === key ? state.loaded : 0) : 0,+ total: active ? total : 0,+ retry,+ };+}diff --git a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsxindex bcb6dadbe1..8754468afb 100644--- a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx+++ b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx@@ -26,6 +26,8 @@ import {import { getBuiltinWallpaperBackground } from '@/lib/wallpaper';import { useIsDarkMode } from '@/components/markdown/useIsDarkMode';import { WallpaperVideo } from '@/components/layout/WallpaperVideo';+import { useWallpaperAsset } from './useWallpaperAsset';+import { useReducedMotion } from './useReducedMotion';export interface WallpaperSettings {wallpaperId: WallpaperId;@@ -38,6 +40,10 @@ export interface WallpaperSettings {interface WallpaperSettingsContextValue extends WallpaperSettings {playbackFailed: boolean;+ downloadPending: boolean;+ downloadFailed: boolean;+ downloadProgress: number;+ retryDownload: () => void;visibility: number;setWallpaper: (id: WallpaperId) => void;setVisibility: (value: number) => void;@@ -84,6 +90,22 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })const onPlaybackReady = useCallback(() => setFailedUrl(''), []);const isDark = useIsDarkMode();const visibility = getWallpaperVisibility(settings, isDark);+ const reducedMotion = useReducedMotion();+ const imageAsset = useWallpaperAsset(settings.wallpaperId, 'image', visibility > 0);+ const videoAsset = useWallpaperAsset(+ settings.wallpaperId,+ 'video',+ visibility > 0 && settings.wallpaperMotion === 'dynamic' && !reducedMotion,+ );+ const downloadPending = imageAsset.loading || videoAsset.loading;+ const downloadFailed = imageAsset.failed || videoAsset.failed;+ const downloadBytes = imageAsset.total + videoAsset.total;+ const downloadProgress =+ downloadBytes > 0 ? (imageAsset.loaded + videoAsset.loaded) / downloadBytes : 0;+ const retryDownload = useCallback(() => {+ imageAsset.retry();+ videoAsset.retry();+ }, [imageAsset.retry, videoAsset.retry]);// Document-level surface also covers settings, split panes, portals and detached// app windows, without changing the layout tree or stacking order of its panes.useLayoutEffect(() => {@@ -96,7 +118,9 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })? 'none': `url("${customUrl}")`: undefined- : getBuiltinWallpaperBackground(settings.wallpaperId);+ : imageAsset.url+ ? `url("${imageAsset.url}")`+ : getBuiltinWallpaperBackground(settings.wallpaperId);const active = Boolean(background);if (active) {root.dataset.wallpaperActive = 'true';@@ -116,7 +140,7 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })for (const name of ['--app-wallpaper-image', '--app-wallpaper-veil', '--app-wallpaper-blur'])root.style.removeProperty(name);};- }, [settings, visibility, blurPreview]);+ }, [settings, visibility, blurPreview, imageAsset.url]);const settingsRef = useRef(settings);const confirmedRef = useRef(settings);const pendingRef = useRef<Array<{ id: number; patch: Partial<WallpaperSettings> }>>([]);@@ -237,6 +261,10 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })wallpaperBlur: blurPreview ?? settings.wallpaperBlur,visibility,playbackFailed: !!failedUrl && failedUrl === settings.customWallpaperUrl,+ downloadPending,+ downloadFailed,+ downloadProgress,+ retryDownload,setWallpaper,setVisibility,setBlur,@@ -255,6 +283,10 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })settings,failedUrl,visibility,+ downloadPending,+ downloadFailed,+ downloadProgress,+ retryDownload,],);@@ -265,6 +297,7 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })wallpaperId={settings.wallpaperId}motion={settings.wallpaperMotion}customWallpaperUrl={settings.customWallpaperUrl}+ officialVideoUrl={videoAsset.url}onFailure={onPlaybackFailure}onReady={onPlaybackReady}/>diff --git a/apps/desktop/src/renderer/hooks/useWallpaperVideoTier.ts b/apps/desktop/src/renderer/hooks/useWallpaperVideoTier.tsdeleted file mode 100644index ca5e8a409f..0000000000--- a/apps/desktop/src/renderer/hooks/useWallpaperVideoTier.ts+++ /dev/null@@ -1,51 +0,0 @@-import { useEffect, useState } from 'react';--export type WallpaperVideoTier = 'standard' | 'hd';--/** Cover-fit demand, expressed as the required width of a 16:10 source. */-export function chooseWallpaperVideoTier(- width: number,- height: number,- pixelRatio: number,- previous: WallpaperVideoTier = 'standard',-): WallpaperVideoTier {- const demand = Math.max(width, height * 1.6) * pixelRatio;- // Hysteresis prevents repeated decoder reloads near the size boundary.- return demand > (previous === 'hd' ? 1680 : 1920) ? 'hd' : 'standard';-}--function readTier(previous?: WallpaperVideoTier): WallpaperVideoTier {- return chooseWallpaperVideoTier(- window.innerWidth, window.innerHeight, window.devicePixelRatio || 1, previous,- );-}--export function useWallpaperVideoTier(): WallpaperVideoTier {- const [tier, setTier] = useState(() => readTier());- useEffect(() => {- let timer: ReturnType<typeof setTimeout> | undefined;- let query: MediaQueryList | undefined;- const update = () => {- clearTimeout(timer);- timer = setTimeout(() => setTier(previous => readTier(previous)), 350);- };- const watchPixelRatio = () => {- query?.removeEventListener('change', onPixelRatioChange);- query = window.matchMedia?.(`(resolution: ${window.devicePixelRatio || 1}dppx)`);- query?.addEventListener('change', onPixelRatioChange);- };- const onPixelRatioChange = () => {- watchPixelRatio();- update();- };- watchPixelRatio();- window.addEventListener('resize', update);- update();- return () => {- clearTimeout(timer);- window.removeEventListener('resize', update);- query?.removeEventListener('change', onPixelRatioChange);- };- }, []);- return tier;-}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex c9ad78590a..6063d3f2f9 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1637,7 +1637,10 @@"customPlaybackFailed": "This video could not be played. Choose an MP4 video encoded with H.264.","customHint": "PNG, JPEG or WebP up to 20 MB; MP4 video up to 100 MB. Stored on this device. Videos loop silently in Dynamic mode.","customInvalid": "Choose a valid PNG, JPEG or WebP image (up to 20 MB and 40 megapixels), or an MP4 video up to 100 MB.",- "customFailed": "Could not save the wallpaper. Please try again."+ "customFailed": "Could not save the wallpaper. Please try again.",+ "downloading": "Downloading wallpaper…",+ "downloadFailed": "Some wallpaper assets are unavailable. Using the available background.",+ "retryDownload": "Retry Download"},"layout": {"label": "Panel layout",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 35a0086850..8a3753f2a8 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1614,7 +1614,10 @@"customPlaybackFailed": "この動画を再生できません。H.264 でエンコードされた MP4 動画を選択してください。","customHint": "PNG・JPEG・WebP 画像は最大 20 MB、MP4 動画は最大 100 MB。この端末にのみ保存します。動画モードでは無音で繰り返し再生します。","customInvalid": "有効な PNG・JPEG・WebP 画像(最大 20 MB・4000 万画素)、または最大 100 MB の MP4 動画を選択してください。",- "customFailed": "壁紙を保存できませんでした。もう一度お試しください。"+ "customFailed": "壁紙を保存できませんでした。もう一度お試しください。",+ "downloading": "壁紙をダウンロード中…",+ "downloadFailed": "一部の壁紙素材を取得できません。利用可能な背景を表示しています。",+ "retryDownload": "再ダウンロード"},"layout": {"label": "パネルレイアウト",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 88df306355..de433011b8 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1614,7 +1614,10 @@"customPlaybackFailed": "이 동영상을 재생할 수 없습니다. H.264로 인코딩된 MP4 동영상을 선택하세요.","customHint": "PNG, JPEG, WebP 이미지는 최대 20 MB, MP4 동영상은 최대 100 MB. 이 기기에만 저장됩니다. 동적 모드에서는 소리 없이 반복 재생됩니다.","customInvalid": "올바른 PNG, JPEG 또는 WebP 이미지(최대 20 MB, 4천만 화소)나 최대 100 MB의 MP4 동영상을 선택하세요.",- "customFailed": "배경화면을 저장하지 못했습니다. 다시 시도하세요."+ "customFailed": "배경화면을 저장하지 못했습니다. 다시 시도하세요.",+ "downloading": "배경화면 다운로드 중…",+ "downloadFailed": "일부 배경화면 파일을 받지 못해 사용 가능한 배경을 표시합니다.",+ "retryDownload": "다시 다운로드"},"layout": {"label": "패널 레이아웃",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex f3efac230f..05ec077263 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1614,7 +1614,10 @@"customPlaybackFailed": "无法播放此视频,请选择使用 H.264 编码的 MP4 视频。","customHint": "PNG、JPEG、WebP 图片最大 20 MB,MP4 视频最大 100 MB。仅保存在此设备,视频在动态模式下静音循环播放。","customInvalid": "请选择有效的 PNG、JPEG 或 WebP 图片(不超过 20 MB、4000 万像素),或不超过 100 MB 的 MP4 视频。",- "customFailed": "未能保存壁纸,请重试。"+ "customFailed": "未能保存壁纸,请重试。",+ "downloading": "正在下载壁纸…",+ "downloadFailed": "部分壁纸资源未下载,暂用可用背景",+ "retryDownload": "重试下载"},"layout": {"label": "面板布局",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex defb2d4823..fce83553d6 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1614,7 +1614,10 @@"customPlaybackFailed": "無法播放此影片,請選擇使用 H.264 編碼的 MP4 影片。","customHint": "PNG、JPEG、WebP 圖片最大 20 MB,MP4 影片最大 100 MB。僅儲存在此裝置,影片在動態模式下靜音循環播放。","customInvalid": "請選擇有效的 PNG、JPEG 或 WebP 圖片(不超過 20 MB、4000 萬像素),或不超過 100 MB 的 MP4 影片。",- "customFailed": "無法儲存桌布,請重試。"+ "customFailed": "無法儲存桌布,請重試。",+ "downloading": "正在下載桌布…",+ "downloadFailed": "部分桌布資源未下載,暫用可用背景",+ "retryDownload": "重試下載"},"layout": {"label": "面板佈局",diff --git a/apps/desktop/src/renderer/lib/wallpaper.ts b/apps/desktop/src/renderer/lib/wallpaper.tsindex ef30b21428..0f19e786c9 100644--- a/apps/desktop/src/renderer/lib/wallpaper.ts+++ b/apps/desktop/src/renderer/lib/wallpaper.ts@@ -1,29 +1,9 @@import type { WallpaperId } from '@/../shared/appearanceSettings';-import videoManifest from '@/../shared/wallpaper-video-manifest.json';-import cindyWindow from '@/assets/wallpapers/cindy-window.webp';-import cindyStudio from '@/assets/wallpapers/cindy-studio.webp';-import cindyDream from '@/assets/wallpapers/cindy-dream.webp';-import cindyWindowVideo from '@/assets/wallpapers/cindy-window.mp4';-import cindyStudioVideo from '@/assets/wallpapers/cindy-studio.mp4';-import cindyDreamVideo from '@/assets/wallpapers/cindy-dream.mp4';+import cindyWindow from '@/assets/wallpapers/previews/cindy-window.webp';+import cindyStudio from '@/assets/wallpapers/previews/cindy-studio.webp';+import cindyDream from '@/assets/wallpapers/previews/cindy-dream.webp';-const SCENE_VIDEOS: Partial<Record<WallpaperId, string>> = {- 'cindy-window': cindyWindowVideo,- 'cindy-studio': cindyStudioVideo,- 'cindy-dream': cindyDreamVideo,-};--export function getWallpaperVideo(id: WallpaperId): string | undefined {- return SCENE_VIDEOS[id];-}--/** Official scenes are fully offline; CDN delivery is opt-in for future catalog entries. */-export function usesCdnWallpaperVideo(id: WallpaperId): boolean {- return Object.hasOwn(videoManifest, id) &&- videoManifest[id as keyof typeof videoManifest].delivery === 'cdn';-}--export function isSceneWallpaper(id: WallpaperId): boolean {+export function isSceneWallpaper(id: WallpaperId): id is Exclude<WallpaperId, 'none' | 'custom'> {return id === 'cindy-window' || id === 'cindy-studio' || id === 'cindy-dream';}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex ba118c3967..7969365138 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1207,6 +1207,8 @@ interface ElectronAPI {appearanceSettings: {importWallpaper: () => Promise<import('../shared/appearanceSettings').AppearanceSettings | null>;ensureWallpaperVideo?: (id: import('../shared/appearanceSettings').WallpaperId) => Promise<string | null>;+ ensureWallpaperImage?: (id: import('../shared/appearanceSettings').WallpaperId) => Promise<string | null>;+ onWallpaperDownloadProgress?: (callback: (progress: import('../shared/appearanceSettings').WallpaperDownloadProgress) => void) => () => void;removeWallpaper: () => Promise<import('../shared/appearanceSettings').AppearanceSettings>;getSync: () => import('../shared/appearanceSettings').AppearanceSettings | null;get: () => Promise<unknown>;diff --git a/apps/desktop/src/shared/appearanceSettings.ts b/apps/desktop/src/shared/appearanceSettings.tsindex 6416d2cc03..6162e65c10 100644--- a/apps/desktop/src/shared/appearanceSettings.ts+++ b/apps/desktop/src/shared/appearanceSettings.ts@@ -24,6 +24,17 @@ export interface AppearanceOverrides {export type WallpaperMotion = 'static' | 'dynamic';+export const WALLPAPER_DOWNLOAD_PROGRESS_CHANNEL =+ 'appearance-settings:wallpaper-download-progress';++/** Local Desktop transfer telemetry; never persisted or sent through device-link. */+export interface WallpaperDownloadProgress {+ wallpaperId: WallpaperId;+ kind: 'image' | 'video';+ loaded: number;+ total: number;+}+export interface AppearanceSettings {uiFamily: string;codeFamily: string;diff --git a/apps/desktop/src/shared/wallpaper-video-manifest.json b/apps/desktop/src/shared/wallpaper-video-manifest.jsonindex 8c32796823..3288322465 100644--- a/apps/desktop/src/shared/wallpaper-video-manifest.json+++ b/apps/desktop/src/shared/wallpaper-video-manifest.json@@ -1,29 +1,41 @@{"cindy-window": {- "delivery": "bundled",+ "delivery": "cdn","sha256": "10d72d8ab0f39a5ceec6f8746396c36bb6d7dd345ac18af209069678a90d010d","bytes": 6091872,"width": 2304,"height": 1440,"fps": 24,- "duration": 12.041666666666666+ "duration": 12.041666666666666,+ "image": {+ "sha256": "bfbb37f4a710e110d39596943bc5d68dfaf88d6989c1bc4e5adfbb2e48612d00",+ "bytes": 1101332+ }},"cindy-studio": {- "delivery": "bundled",+ "delivery": "cdn","sha256": "b33f9b527584ae8c8b085536a0823a346e4879fa845e62e5ac41ae1b7b0097b1","bytes": 3606656,"width": 2304,"height": 1440,"fps": 24,- "duration": 12.041666666666666+ "duration": 12.041666666666666,+ "image": {+ "sha256": "7d2af2acb2df6b7fcbb40030299b3518c8de81e138f638b95ca563521f374319",+ "bytes": 1649522+ }},"cindy-dream": {- "delivery": "bundled",+ "delivery": "cdn","sha256": "de9e0dc2235310bdbee30f1bf951d94ce8299b18ba674463df407b76bb162def","bytes": 6312719,"width": 2304,"height": 1440,"fps": 24,- "duration": 12.041666666666666+ "duration": 12.041666666666666,+ "image": {+ "sha256": "2a2043b9207c7dfaaed5951b567eba1eb24aeb192c3eb78a3c0ee9a46a732361",+ "bytes": 1790734+ }}}diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex 69e8f2f30c..1ff2e03290 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -75,14 +75,24 @@不可再生用户内容,必须沿用现有 pin/引用流程转为不可按缓存回收。- 零引用入仓只适用于已有草稿或生成结果提交链路。新增零引用窗口时,必须证明内容在消息落库前不会被回收,并用测试覆盖成功、失败、取消和重试。-- 三款官方壁纸的高清 WebP 与 2304×1440 MP4 均随包,清单标记 `delivery: bundled`,- 不访问 OSS/CDN,不重复打包低清视频。未来显式标记 `delivery: cdn` 的条目才启用- 客户端级 CDN 下载,按清单字节数与 SHA-256 校验后入仓;当前清单保留引用,- 下载成功后回收已不在清单的客户端视频,失败回退随包视频。- 发布脚本只上传 CDN 条目,始终跳过 bundled 条目。发布命令为- `node --env-file=<发布配置> scripts/publish-wallpaper-videos.mjs --directory=<视频目录> --region=global`;- 中国大陆版显式用 `--region=cn`,发布两区时分别执行。可加 `--verify-only` 离线核验。- CDN 文件名为 `<壁纸编号>-hd.mp4`;`--verify-only` 同时校验仓内内置视频。+- 三款官方壁纸改为 OSS/CDN 按需分发(2026-10-15 用户裁决,替代此前全部随包的决定)。+ 包内仅保留 `renderer/assets/wallpapers/previews/` 中的 640×400 WebP;原始高清图和+ 2304×1440 MP4 保留为发布输入,不进入 Renderer 资源依赖图。默认无壁纸和浏览设置列表不下载,+ 选中且可见时下载对应高清图,动态模式且未启用减少动态效果时再下载视频;下载或解码失败保留可用背景。+ 传输复用统一下载器并保留 guardedOutboundFetch 的来源校验,清单大小及 SHA-256 校验后入仓。+ 缓存位于既有 `userData/cindy-media/client-wallpaper/`,仅以内容哈希和扩展名寻址,+ **不含应用版本或账号**;启动与升级先核对本地文件,有效即返回,不请求 CDN。+ 只有文件缺失、损坏或素材哈希变化才重新下载。+ 官方 WebP、MP4 与自定义媒体的引用合并保留;切换壁纸及常规升级不删除当前清单内已下载素材。+ 回归见 `main/__tests__/wallpaperVideo.test.ts` 的升级离线复用及损坏修复测试,+ `customWallpaper.test.ts` 覆盖自定义媒体操作不误删官方图片和视频。+ 发布脚本默认核验仓内原始素材,`--directory` 也接受按 hash 命名的导出目录或旧 `-hd.mp4` 输入。+ `node scripts/publish-wallpaper-videos.mjs --verify-only` 离线核验;+ `node scripts/publish-wallpaper-videos.mjs --check-cdn --region=global` 只读校验线上六个文件;+ 实际发布使用 `node --env-file=<发布配置> scripts/publish-wallpaper-videos.mjs --region=global`。+ 中国大陆版显式用 `--region=cn`,两区分别发布并校验,资源先于客户端上线。+ 对象名为 `wallpapers/<sha256>.webp` / `.mp4`;缩略图可用+ `node scripts/prepare-wallpaper-previews.mjs` 从原始图片重建,总预算 300 KiB。清单见 Desktop 的 `src/shared/wallpaper-video-manifest.json`。- 可再生 HTML 临时快照缓存是独立副本的例外:仅在快照已物化自己的文件、HTTP 服务不依赖媒体仓 blob、且该缓存不作为持久附件提交时,使用 `isCache: true` 和空引用入仓。diff --git a/docs/wallpaper-on-demand-plan.md b/docs/wallpaper-on-demand-plan.mdnew file mode 100644index 0000000000..2f3f1d7ef5--- /dev/null+++ b/docs/wallpaper-on-demand-plan.md@@ -0,0 +1,201 @@+# 官方壁纸 OSS 按需下载方案++状态:客户端实现已完成,资源已由用户上传,两区文件完整性校验通过。日期:2026-10-15。++实施结果:三张 640×400 缩略图合计 169,078 bytes;生产 Renderer 构建确认六个原始高清+素材均未进入产物,壁纸资产减少 20,383,757 bytes(约 19.44 MiB)。缓存沿用+`userData/cindy-media/client-wallpaper/`,地址只含素材哈希及扩展名;升级不清缓存,也不按+应用版本生成新地址。已有自动测试覆盖下载后更换应用版本、重载模块并断网,图片与视频均+直接复用磁盘文件且下载调用为零。以下保留设计依据;末尾记录当前验证范围。++基于 [Issue #6088](https://github.com/makecindy/cindy/issues/6088),用户希望减少安装体积,+将动态桌面相关资产改为使用时下载。本次盘点基于本 worktree 的+`3f4ec18ec53a604651320a76db6cfb463afebd90`,只统计三套官方壁纸的媒体文件。++## 1. 当前体积++文件位于 `apps/desktop/src/renderer/assets/wallpapers/`。以下是文件逻辑字节,+不是压缩安装包大小,也不是文件系统分配空间;MiB = 1,048,576 bytes。++| 壁纸 | MP4 字节 / MiB | WebP 字节 / MiB | 合计 MiB |+| --- | ---: | ---: | ---: |+| 窗边陪伴 `cindy-window` | 6,091,872 / 5.81 | 1,101,332 / 1.05 | 6.86 |+| 未来工作室 `cindy-studio` | 3,606,656 / 3.44 | 1,649,522 / 1.57 | 5.01 |+| 梦境漫游 `cindy-dream` | 6,312,719 / 6.02 | 1,790,734 / 1.71 | 7.73 |+| **总计** | **16,011,247 / 15.27** | **4,541,588 / 4.33** | **19.60** |++六个文件合计 **20,552,835 bytes(20.55 MB / 19.60 MiB)**。+三段视频的清单规格均为 2304×1440、24 fps、约 12 秒。++当前 `renderer/lib/wallpaper.ts` 直接 import 六个文件;视频清单均为 `delivery: bundled`。+执行现有发布脚本的 `--verify-only` 已确认三段视频的大小及 SHA-256 与清单一致,+其输出为 `CDN upload total: 0 bytes`。++此项可以独立减少随包资产,但不能据此解释或解决 issue 中超过 1 GB 的全部占用。+真实收益须用同平台、同架构、同依赖基线的构建产物对比;压缩下载量单独测量。++## 2. 推荐交付方式++**高清 WebP 与 MP4 均放 OSS,经现有 CDN 分发;包内保留轻量预览图和资源清单。**++| 范围 | 可移出原始素材 | 保留能力与代价 |+| --- | ---: | --- |+| 只迁视频 | 15.27 MiB | 高清静态壁纸离线即用;首次启用动态时下载视频 |+| 图片、视频都迁出(推荐) | 19.60 MiB,须扣除新预览图 | 列表和离线首用显示预览;选中后下载高清图,启用动态再下载视频 |++预览图同时供设置列表和下载前背景使用,沿用同一场景与裁切。三张合计以不超过+300 KiB 为初步预算,须实际制作并目检后确认;预算不是已测结果。+若达到该预算,资产净减少至少约 19.31 MiB,尚未计入新增代码、清单及打包差异。++用户实际使用过的高清资源仍占本地存储。全部使用后,本地资源总占用会接近原素材体积;+收益主要是降低安装包与初装占用,避免所有用户都下载三套素材,也避免每次完整更新重复携带。++### 使用时机++1. 默认无壁纸、打开设置列表或浏览缩略图:不下载高清资源。+2. 选中一套壁纸:立即显示内置预览,优先读取该壁纸已校验缓存;未命中则下载该套高清 WebP。+3. 动态模式且未开启系统减少动态效果:再下载该套 MP4。小窗口和大窗口规则相同。+ 图与视频分别完成,图失败不阻止可用视频播放;视频失败不阻止静态图显示。+4. 下载完成后,在图片解码或视频首帧可用时平滑替换。失败继续显示已有图或预览,设置内显示+ 下载状态与重试入口,不阻塞其他页面。手动重试立即生效;网络恢复后的自动重试有次数上限,+ 只针对仍被选中且需要的资源。+5. 下载后重启或离线再次选中,直接使用缓存。切换到静态、关闭壁纸或切换场景后,+ 不应用迟到结果,也不继续自动重试。已经开始的小文件下载允许完成并留存缓存,+ 避免一个窗口关闭中断其他窗口的共用请求;下载有总超时和有限重试。+6. 沿用现有隐藏窗口暂停播放、减少动态效果、单画布和整窗连续背景行为。++下载状态放在当前选中壁纸的缩略图上:半透明遮罩按实际下载字节从底部向上填充,+0% 为空、100% 铺满,完成后移除。所需图片与视频按字节加权,已缓存的资源计为完成;+下载停顿时进度保持不变,中断后从头重下时如实回退,而非按时间模拟进度。+失败改为重试图标,点击同一缩略图或聚焦后按 Enter 即可重试。按 2026-10-15 用户要求,+不增加可见的下载状态文字或独立重试按钮;读屏说明保留,并支持减少动态效果。+进度只使用底部为原点的 transform 与语义 token,同时实现 Light/Dark,依据+[DESIGN.md](design-rules/DESIGN.md) 的可选壁纸、双模式及内容规范。++## 3. 已有实现可以复用什么++| 现有入口 | 已有能力 | 本次需要调整 |+| --- | --- | --- |+| `shared/wallpaper-video-manifest.json` | 视频大小、SHA-256、规格与分发方式 | 增加静态图描述,保留稳定壁纸 ID;正式资源显式标记 CDN |+| `main/wallpaper-video.ts` | 固定清单选择、HTTPS、字节数/哈希校验、并发合并、缓存读取、失败退避 | 扩展图片,接入统一下载器,提供可恢复的加载状态 |+| `main/appearance-settings-ipc.ts` / preload | 受信本机 Renderer 的 ensure 接口,只接收壁纸 ID | 扩展受限资源类型和状态;继续拒绝任意 URL、路径及远程调用 |+| `renderer/components/layout/WallpaperVideo.tsx` | 本地播放、首帧显示、失败回退、暂停与释放解码器 | 改为资源就绪后播放,不依赖内置 MP4,也不再只在 HD 档请求 |+| `renderer/hooks/useWallpaperSettings.tsx` / `renderer/lib/wallpaper.ts` | 全窗背景、选择与模式 | 使用内置预览及下载后的静态图;去掉高清媒体的打包 import |+| `main/cindy-media/` | `client-wallpaper` 作用域、原子落盘、Range 播放、发布锁与回收 | 继续复用;扩展官方 WebP 的保留引用 |+| `scripts/publish-wallpaper-videos.mjs` | 按清单校验、按区域上传 OSS、CDN 下载后复核 | 支持 WebP,统一发布源文件命名;增加发布前只读远端核验 |++### 不能只切换 delivery 的原因++- `WallpaperVideo` 先调用 `getWallpaperVideo()`,没有内置地址就直接返回。+ 只删 MP4 import 会导致 CDN 下载入口也不执行。+- `AdaptiveWallpaper` 仅在显示需求超过 HD 阈值时下载,小窗口仍依赖内置视频。+ 当前三套也没有另一份独立的低清视频可保留。+- 目前所有失败都返回 `null`,主进程设置五分钟退避;Renderer 没有定时或联网重试,+ 同一场景持续显示时不保证恢复。需要显式重试状态与触发机制。+- 高清 WebP 目前始终由 import 提供,现有 CDN 清单、发布脚本与引用保留只覆盖 MP4。+ 扩展图片时须同步修改自定义壁纸与官方下载两条回收入口,避免误删官方图或自定义图。+- 当前下载将整段视频读入内存。按+ [统一下载约定](dev-rules/verified-downloads.md),新增实现应使用 `main/downloader/index.ts`+ 的公共入口,复用流式写盘、超时、进度、重试与校验,不再扩写独立 HTTP 下载器。++## 4. 下载、缓存及升级约定++- 清单随客户端发布,记录资源类型、大小、SHA-256 和格式;不增加运行时远程目录服务。+ 来源由客户端 `cdnBaseUrl` 和清单决定,Renderer 只选择已知 ID 与资源类型。+- 延续 `wallpapers/<sha256>.mp4`,图片使用 `wallpapers/<sha256>.webp`。+ OSS 保存原文件;内容变化生成新 hash 地址,不覆盖旧对象。+- 下载使用统一下载器的完整性检查及来源限制,保留 HTTPS、禁止 URL 凭证和重定向的约束。+ 受控临时文件完成验证后通过 `ingestClientWallpaper` 发布;当前素材很小,可复用其有界+ buffer 入仓接口。临时文件在下载结束及入仓结束后按成功、失败、取消分别收尾。+ 下载不占媒体发布锁,只有入仓和回收持锁。+- 成品继续使用 `cindy-media://client-wallpaper/<hash>.<ext>`,由现有协议读取。+ 不新增媒体目录、数据库或协议,不直接从 Renderer 播放远端 URL。+- 按资源合并多窗口请求,窗口离开只取消显示订阅,不中断其他窗口仍需要的下载。+ 图片与视频独立记录状态,关闭动态模式不影响静态图;失败结果不永久记作已完成。+ 同一下载的后来请求者立即收到当前字节快照;进度只回送已经通过授权的请求 frame,+ 不向所有窗口广播。preload 只暴露固定订阅并剥离 Electron event,结束时取消订阅。+ 此项属于本机 Desktop 外观,不读 SSH 工作目录、不增加 device-link 白名单或 Mobile 入口。+- 所有当前清单内的已下载资源保留,不因切换壁纸删除重下。自定义媒体引用与官方图片/视频+ 引用合并后,由既有 recycler 回收已失去引用的旧资源;暂不引入 LRU 或自动容量配额。+- 缓存及设置沿用客户端 profile 共用范围,登录前、切账号后都可使用。+ 不同步到另一设备,不随账号附件清理。现有壁纸 ID、动态设置、可见度、模糊设置不变。+- 升级后若原来选中了官方壁纸,只请求当前所需资源,不预下载其他两套。+ 旧安装包的内置媒体不一定能跨升级保留,因此首次离线升级可能暂时只有预览;+ 保留原选择,联网后恢复高清及动态效果,不重置用户设置。++## 5. 发布顺序与当前远端状态++2026-10-15 初次盘点时,清单三段视频的预期地址在两个区域共六个 HEAD 请求均返回 **404**。+用户完成上传后,再实际下载两区共 12 个图片/视频对象:全部 **200**,大小、SHA-256 与+Content-Type 均匹配。响应暂未设置 Cache-Control;本地持久缓存不依赖 HTTP 缓存头。++- `global`:`https://hotfix.cindy.app/cindy/wallpapers/<sha256>.mp4`+- `cn`:`https://hotfix.cindy.com.cn/cindy/wallpapers/<sha256>.mp4`++两区使用相同内容哈希,已核验的 URL 不需要改动。++实施顺序:++1. 制作轻量预览、补齐图片清单与发布脚本,离线核验全部原始素材。+ 原文件保留为发布输入,移出 Renderer 依赖图;本轮目标是发行包体积,不改写 Git 历史。+2. 分别显式选择 `global`、`cn` 发布到现有公开资源渠道,按+ [区域规则](product-rules/region-and-editions.md) 禁止相互回落。+ 下载每个 CDN 成品并复核字节数、SHA-256、Content-Type 和长期缓存响应头。+3. 在隔离 Desktop 中完成按需加载和失败恢复验证,再切换客户端清单并移除高清资源 import。+ 为发布版本添加只读资源检查;任一必需对象缺失或不匹配,都不发布该区域的新客户端。+4. 构建产物确认不含六个原始高清素材,只含预览和清单。记录 Windows/macOS/Linux+ 实际验证范围,分别比较压缩包、安装文件字节与首次使用后的缓存增量。++资产先发布、客户端后切换。新资源部署失败时继续发行原行为;回退客户端时旧资源对象保留,+不能因为新版本已发布就删除仍被旧客户端清单引用的 CDN 对象。+此方案无需修改服务端仓库;OSS/CDN 的公开资源发布属于单独的发布步骤。++已同步更新 [媒体存储规则](dev-rules/media-storage-and-protocols.md) 中“三款全部随包”的旧约定,+以 2026-10-15 用户确认的新方向为准。上述发布步骤保留为后续更新素材时的操作约定。++## 6. 验收++- 未选中壁纸、只浏览设置列表:高清资源网络请求为零。+- 首次静态使用只下载一张图;启用动态才下载对应视频,普通窗口与高 DPI 窗口均有效。+- 多窗口只产生一份同资源下载;切换场景、模式或关闭窗口不应用过期结果。+- 断网、404、超时、磁盘不足、错误大小或哈希均保留可用背景;手动重试、网络恢复和损坏缓存重下有效。+- 已下载后离线重启、切账号可复用;自定义壁纸导入、替换、删除不误删官方资源,反向亦然。+- 旧设置升级保持原选择;离线升级显示预览且不丢设置。+- 在真实客户端检查 Light/Dark 下主界面、设置各分区、展开工具栏及独立窗口的连续背景,+ 下载前后无黑屏闪烁;隐藏窗口及减少动态效果继续生效,记录未验证的平台或模式。+- 定向覆盖下载、引用回收、渲染触发和发布校验;运行 Desktop 类型检查,检查最终产物资源清单。++已完成:资源盘点、预览图、客户端与发布校验脚本、两区 CDN 实际文件核验、14 个测试文件+共 150 项定向测试、Desktop 类型检查、多语言及文档检查、生产 Renderer 构建和媒体排除验证。+Windows 隔离客户端实测了首次静态下载、三款视频播放(2304 像素宽,readyState=4,无播放错误)、+Light/Dark 设置界面;重启并切换三款场景后,六个本地文件的修改时间及 SHA-256 均保持不变。+独立侧栏与资源窗口实测从共享缓存取用、隐藏时视频暂停;插件面板宿主由入口与 preload 测试覆盖,+未做插件面板实机目检。三者只新增固定场景资源请求方法,不开放设置写入或任意路径、URL。+完整签名安装包前后对比及 macOS/Linux 实机验收尚未执行;Renderer 资产差值不代表压缩安装包差值。++### 2026-10-15 弱网与缩略图进度实测(Windows)++在独立 profile 中通过本机 CONNECT 代理限制真实 Global CDN 的响应速度并注入断流,+不解密 TLS、不替换文件响应、不修改系统网络设置。限速场景另外加入 800 ms 初始延迟。++| 场景 | 结果 |+| --- | --- |+| 静态图,64 KiB/s | 约 20.15 秒完成,仅下载图片;校验完成前保留内置预览 |+| 视频,128 KiB/s | 约 54.91 秒完成,等待期间保留高清静态图 |+| 视频约 256 KiB 时断流一次 | 自动重试,约 37.98 秒完成,文件哈希正确,无半成品媒体 |+| 离线首次请求 | 图片约 3.19 秒、视频约 4.12 秒进入失败状态,保留可用背景 |+| 恢复网络后手动重试 | 图片约 17.31 秒完成,恢复高清图 |+| 恢复网络后不操作 | 包含 30 秒等待和下载,约 62.20 秒自动恢复视频 |+| 已缓存资源离线再选中 | 约 215 ms 就绪,代理记录的 CDN 连接为零 |+| 连接保持但停止传输 | 三次真实空闲超时后约 103.75 秒进入失败状态,键盘激活缩略图可重试 |++按用户最终指定的填充方向重新实测:静态图约 20.46 秒完成,在真实 25% 和 70% 下载点+分别核实 Light/Dark,遮罩以缩略图底边为固定原点向上增长。视频传输被暂停时,合并进度+保持 44% 不动;随后断线显示缩略图重试图标,恢复网络后按 Enter 重试约 16.93 秒完成。+完成后的图片与视频 SHA-256 均匹配,再次离线选择的 CDN 连接仍为零。++进度改动另完成 8 个文件共 90 项定向测试、Desktop 类型检查、定向 ESLint 与设计颜色检查。+覆盖多窗口共享进度、后来请求者的快照、重试归零、关闭 frame 不影响下载、preload 取消订阅、+图片/视频字节加权、静态模式排除视频,以及缩略图进度与重试交互。弱网代理与测试实例在+验收结束后关闭,原验收沙盒恢复正常网络;真实截图和原始测量记录留在本地忽略的 artifacts,+不把测试截图加入工程文件。diff --git a/scripts/prepare-wallpaper-previews.mjs b/scripts/prepare-wallpaper-previews.mjsnew file mode 100644index 0000000000..c5707a4edd--- /dev/null+++ b/scripts/prepare-wallpaper-previews.mjs@@ -0,0 +1,33 @@+#!/usr/bin/env node+// Reproducible resize of the original artwork; only these previews enter the renderer bundle.+import fs from "node:fs/promises";+import path from "node:path";+import { createRequire } from "node:module";+import { fileURLToPath } from "node:url";++const require = createRequire(+ new URL("../apps/desktop/package.json", import.meta.url),+);+const sharp = require("sharp");+const source = fileURLToPath(+ new URL("../apps/desktop/src/renderer/assets/wallpapers/", import.meta.url),+);+const output = path.join(source, "previews");+await fs.mkdir(output, { recursive: true });+let total = 0;+for (const id of ["cindy-window", "cindy-studio", "cindy-dream"]) {+ const result = await sharp(path.join(source, id + ".webp"))+ .resize({+ width: 640,+ height: 400,+ fit: "inside",+ withoutEnlargement: true,+ })+ .webp({ quality: 70 })+ .toFile(path.join(output, id + ".webp"));+ total += result.size;+ console.log(`${id}: ${result.width}x${result.height}, ${result.size} bytes`);+}+if (total > 300 * 1024)+ throw new Error("Wallpaper previews exceed the 300 KiB bundle budget");+console.log(`Preview total: ${total} bytes`);diff --git a/scripts/publish-wallpaper-videos.mjs b/scripts/publish-wallpaper-videos.mjsindex 6625935e10..4b4a4df9b9 100644--- a/scripts/publish-wallpaper-videos.mjs+++ b/scripts/publish-wallpaper-videos.mjs@@ -1,48 +1,128 @@#!/usr/bin/env node-// Verify bundled assets; only opt-in CDN entries are published as reviewed bytes.-import fs from 'node:fs/promises';-import path from 'node:path';-import { createHash } from 'node:crypto';-import { fileURLToPath } from 'node:url';-import { createOSSClient, resolveOssConfig, uploadToOSS } from './shared/oss.mjs';+// Verify/publish original wallpaper images and videos; only small previews are bundled.+import fs from "node:fs/promises";+import path from "node:path";+import { createHash } from "node:crypto";+import { fileURLToPath } from "node:url";+import {+ createOSSClient,+ resolveOssConfig,+ uploadToOSS,+} from "./shared/oss.mjs";const args = process.argv.slice(2);-const region = args.find(arg => arg.startsWith('--region='))?.slice(9) ?? 'global';-const directory = args.find(arg => arg.startsWith('--directory='))?.slice(12);-const verifyOnly = args.includes('--verify-only');-if (!['global', 'cn'].includes(region)) {- throw new Error('Usage: node [--env-file=...] scripts/publish-wallpaper-videos.mjs --directory=<videos> --region=global|cn [--verify-only]');+const region =+ args.find((arg) => arg.startsWith("--region="))?.slice(9) ?? "global";+const directory = args.find((arg) => arg.startsWith("--directory="))?.slice(12);+const verifyOnly = args.includes("--verify-only");+const checkCdn = args.includes("--check-cdn");+if (!["global", "cn"].includes(region)) {+ throw new Error(+ "Usage: node scripts/publish-wallpaper-videos.mjs [--directory=<originals>] --region=global|cn [--verify-only | --check-cdn]",+ );}-const manifest = JSON.parse(await fs.readFile(new URL('../apps/desktop/src/shared/wallpaper-video-manifest.json', import.meta.url), 'utf8'));+const source =+ directory ??+ fileURLToPath(+ new URL("../apps/desktop/src/renderer/assets/wallpapers/", import.meta.url),+ );+const manifest = JSON.parse(+ await fs.readFile(+ new URL(+ "../apps/desktop/src/shared/wallpaper-video-manifest.json",+ import.meta.url,+ ),+ "utf8",+ ),+);const assets = [];-for (const [id, asset] of Object.entries(manifest)) {- if (!['bundled', 'cdn'].includes(asset.delivery)) throw new Error('Unknown wallpaper delivery: ' + id);- if (asset.delivery === 'cdn' && !directory) throw new Error('CDN entries require --directory=<videos>');- const file = asset.delivery === 'bundled'- ? fileURLToPath(new URL('../apps/desktop/src/renderer/assets/wallpapers/' + id + '.mp4', import.meta.url))- : path.resolve(directory, id + '-hd.mp4');- const bytes = await fs.readFile(file);- if (bytes.length !== asset.bytes || createHash('sha256').update(bytes).digest('hex') !== asset.sha256) {- throw new Error('Video differs from reviewed manifest: ' + id);+for (const [id, entry] of Object.entries(manifest)) {+ if (!["bundled", "cdn"].includes(entry.delivery))+ throw new Error("Unknown wallpaper delivery: " + id);+ for (const [asset, ext, mime] of [+ [entry, ".mp4", "video/mp4"],+ [entry.image, ".webp", "image/webp"],+ ]) {+ if (!asset) continue;+ let file = path.resolve(source, id + ext);+ // Accept both the prepared hash-named upload folder and the old external HD input layout.+ if (directory) {+ const candidates = [file, path.resolve(source, asset.sha256 + ext)];+ if (ext === ".mp4") candidates.push(path.resolve(source, id + "-hd.mp4"));+ file = undefined;+ for (const candidate of candidates) {+ if (+ await fs.stat(candidate).then(+ (s) => s.isFile(),+ () => false,+ )+ ) {+ file = candidate;+ break;+ }+ }+ if (!file) throw new Error("Missing wallpaper source: " + id + ext);+ }+ const bytes = await fs.readFile(file);+ if (+ bytes.length !== asset.bytes ||+ createHash("sha256").update(bytes).digest("hex") !== asset.sha256+ )+ throw new Error("Asset differs from reviewed manifest: " + id + ext);+ if (entry.delivery === "cdn") assets.push({ file, ...asset, ext, mime });+ console.log(id + ext + ": " + asset.bytes + " bytes");}- if (asset.delivery === 'cdn') assets.push({ file, ...asset });- console.log(id + ': ' + asset.width + 'x' + asset.height + ', ' + asset.bytes + ' bytes');}-console.log('CDN upload total: ' + assets.reduce((sum, asset) => sum + asset.bytes, 0) + ' bytes');-if (!verifyOnly && assets.length > 0) {- // Missing publication configuration must never redirect to another region.- const config = resolveOssConfig(region);- const client = createOSSClient(region);+console.log(+ "CDN upload total: " ++ assets.reduce((sum, asset) => sum + asset.bytes, 0) ++ " bytes",+);+if (checkCdn || !verifyOnly) {+ // Read-only verification needs no OSS credentials and never uploads.+ const endpointFile =+ region === "global" ? "endpoint.global.json" : "endpoint.json";+ const endpoint = JSON.parse(+ await fs.readFile(+ new URL("../config/" + endpointFile, import.meta.url),+ "utf8",+ ),+ );+ const config = checkCdn+ ? { cdnBase: endpoint.cdnBaseUrl }+ : resolveOssConfig(region);+ const client = checkCdn ? null : createOSSClient(region);for (const asset of assets) {- const relative = 'wallpapers/' + asset.sha256 + '.mp4';- await uploadToOSS(client, config.prefix.replace(/\/+$/, '') + '/' + relative, asset.file, {- headers: { 'Content-Type': 'video/mp4', 'Cache-Control': 'public, max-age=31536000, immutable' },- });- const response = await fetch(config.cdnBase + '/' + relative, { signal: AbortSignal.timeout(60_000) });- if (!response.ok) throw new Error('Published CDN resource is not readable: ' + response.status);+ const relative = "wallpapers/" + asset.sha256 + asset.ext;+ if (client)+ await uploadToOSS(+ client,+ config.prefix.replace(/\/+$/, "") + "/" + relative,+ asset.file,+ {+ headers: {+ "Content-Type": asset.mime,+ "Cache-Control": "public, max-age=31536000, immutable",+ },+ },+ );+ const response = await fetch(+ config.cdnBase.replace(/\/+$/, "") + "/" + relative,+ {+ redirect: "error",+ signal: AbortSignal.timeout(60_000),+ },+ );+ if (!response.ok)+ throw new Error("CDN resource is not readable: " + response.status);const bytes = Buffer.from(await response.arrayBuffer());- if (bytes.length !== asset.bytes || createHash('sha256').update(bytes).digest('hex') !== asset.sha256)- throw new Error('CDN resource integrity mismatch');- console.log('Verified ' + relative);+ if (+ bytes.length !== asset.bytes ||+ createHash("sha256").update(bytes).digest("hex") !== asset.sha256+ )+ throw new Error("CDN resource integrity mismatch");+ if (response.headers.get("content-type")?.split(";")[0] !== asset.mime)+ throw new Error("CDN content type mismatch");+ console.log("Verified " + region + ": " + relative);}}