Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 支持自定义动态壁纸并修复 HDR 下的视频亮度异常 (#5514)

DavidShenXD2f8ed15f1cc7
diff --git a/apps/desktop/scripts/check-wallpaper-video-compositing.mjs b/apps/desktop/scripts/check-wallpaper-video-compositing.mjs
new file mode 100644
index 0000000000..d29d264de8
--- /dev/null
+++ b/apps/desktop/scripts/check-wallpaper-video-compositing.mjs
@@ -0,0 +1,106 @@
+#!/usr/bin/env node
+// Run: node apps/desktop/scripts/check-wallpaper-video-compositing.mjs [Chromium executable]
+// Uses production CSS and a deterministic video poster in an isolated browser.
+// The companion WallpaperVideo.test.tsx checks the CSS contract in normal unit/CI runs.
+// Requires an installed Chromium executable argument or a Playwright Chromium cache.
+// playwright-core does not download a browser; this script does not install one.
+// Guards blending/visibility without relying on codec availability. HDR/driver behavior still
+// requires the Windows FP16 screen-capture regression described in the test output.
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { chromium } from 'playwright-core';
+import sharp from 'sharp';
+
+const css = readFileSync(
+ new URL('../src/renderer/styles/globals.css', import.meta.url),
+ 'utf8',
+).replace(/^@import.*$/gm, '');
+const mediaColor = [64, 128, 192];
+const poster = `data:image/svg+xml,${encodeURIComponent(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path fill="#4080c0" d="M0 0h32v32H0z"/></svg>',
+)}`;
+const browser = await chromium.launch({
+ headless: true,
+ ...(process.argv[2] ? { executablePath: process.argv[2] } : {}),
+});
+try {
+ const page = await browser.newPage({ viewport: { width: 320, height: 240 } });
+ await page.setContent(`<!doctype html><html data-wallpaper-active="true">
+ <style>${css}</style><style>body{margin:0} :root{
+ --motion-base:0ms;--motion-ease-move:linear;
+ --app-wallpaper-image:linear-gradient(red,red);
+ }</style><body><div class="app-wallpaper-video" style="opacity:1">
+ <video poster="${poster}"></video></div></body></html>`);
+ await page.evaluate(async (src) => {
+ const image = new Image();
+ image.src = src;
+ await image.decode();
+ }, poster);
+ let checked = 0;
+ // The bright red still fallback deliberately differs from the video. It must
+ // never bleed through a ready, partially transparent video canvas.
+ for (const [theme, surface] of [
+ ['dark', [24, 24, 24]],
+ ['light', [242, 242, 237]],
+ ]) {
+ for (const visibility of [0, 0.01, 0.14, 0.5, 0.99, 1]) {
+ const styles = await page.evaluate(
+ ({ surface, visibility }) => {
+ const root = document.documentElement;
+ root.style.setProperty('--surface', `rgb(${surface.join(',')})`);
+ root.style.setProperty('--app-wallpaper-veil', `${100 - visibility * 100}%`);
+ const layer = document.querySelector('.app-wallpaper-video');
+ return {
+ opacity: Number(getComputedStyle(layer.querySelector('video')).opacity),
+ layerOpacity: Number(getComputedStyle(layer).opacity),
+ veil: getComputedStyle(layer, '::after').content,
+ };
+ },
+ { surface, visibility },
+ );
+ assert.ok(
+ Math.abs(styles.opacity - visibility) < 0.00001,
+ `${theme} ${visibility}: visibility must apply to the video before UI composition`,
+ );
+ assert.equal(styles.layerOpacity, 1, 'visibility must not fade the theme backing');
+ assert.ok(['none', 'normal'].includes(styles.veil), 'no separate translucent video veil');
+ const { data } = await sharp(
+ await page.screenshot({
+ clip: { x: 160, y: 120, width: 1, height: 1 },
+ }),
+ )
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ for (let channel = 0; channel < 3; channel++) {
+ const expected = surface[channel] * (1 - visibility) + mediaColor[channel] * visibility;
+ assert.ok(
+ Math.abs(data[channel] - expected) <= 2,
+ `${theme} ${visibility}: channel ${channel}=${data[channel]}, expected ${expected}`,
+ );
+ }
+ checked++;
+ }
+ }
+ // Loading and exit still expose the underlying still canvas, rather than
+ // leaving an opaque theme-colored rectangle behind.
+ await page.evaluate(() => {
+ document.documentElement.style.setProperty('--app-wallpaper-veil', '0%');
+ document.querySelector('.app-wallpaper-video').style.opacity = '0';
+ });
+ const hidden = await sharp(
+ await page.screenshot({
+ clip: { x: 160, y: 120, width: 1, height: 1 },
+ }),
+ )
+ .raw()
+ .toBuffer();
+ assert.deepEqual([...hidden.subarray(0, 3)], [255, 0, 0]);
+ console.log(
+ `PASS: ${checked} light/dark visibility cases, opaque backing, and loading/exit fallback.`,
+ );
+ console.log(
+ 'HDR acceptance: toggle P3/sRGB content with a fixed video frame; compare FP16 scRGB screen captures, not GDI/PNG screenshots.',
+ );
+} finally {
+ await browser.close();
+}
diff --git a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
index 9544dcacc5..20f55e8308 100644
--- a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
+++ b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
@@ -65,17 +65,36 @@ const persisted = {
};
describe('appearance settings IPC authorization', () => {
+ it('validates literal visibility and accepts null only to reset its override', () => {
+ for (const wallpaperVisibility of [0, 0.37, 1, null]) {
+ expect(__testing.parsePatch({ wallpaperVisibility })).toEqual({ wallpaperVisibility });
+ }
+ expect(__testing.parsePatch({ wallpaperVisibility: 2 })).toEqual({ wallpaperVisibility: 1 });
+ expect(__testing.parsePatch({ wallpaperVisibility: -1 })).toEqual({ wallpaperVisibility: 0 });
+ for (const wallpaperVisibility of ['0.5', true, NaN, Infinity, {}]) {
+ 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];
+ 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'; });
+ 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];
+ 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();
});
@@ -86,7 +105,9 @@ describe('appearance settings IPC authorization', () => {
const pending = handler({ sender: {} });
mocks.owner = 'owner-b:2';
await expect(pending).resolves.not.toBeUndefined();
- expect(channel.endsWith('import-wallpaper') ? mocks.importWallpaper : mocks.removeWallpaper).toHaveBeenCalledOnce();
+ expect(
+ channel.endsWith('import-wallpaper') ? mocks.importWallpaper : mocks.removeWallpaper,
+ ).toHaveBeenCalledOnce();
},
);
it.each(['appearance-settings:import-wallpaper', 'appearance-settings:remove-wallpaper'])(
@@ -96,13 +117,17 @@ describe('appearance settings IPC authorization', () => {
const pending = handler({ sender: {} });
mocks.boundaryPending = true;
await expect(pending).resolves.not.toBeUndefined();
- expect(channel.endsWith('import-wallpaper') ? mocks.importWallpaper : mocks.removeWallpaper).toHaveBeenCalledOnce();
+ expect(
+ channel.endsWith('import-wallpaper') ? mocks.importWallpaper : mocks.removeWallpaper,
+ ).toHaveBeenCalledOnce();
},
);
it('does not let a renderer inject a path or media URL through the generic preference channel', () => {
expect(__testing.parsePatch({ wallpaperId: 'custom' })).toEqual({ wallpaperId: 'custom' });
expect(() =>
- __testing.parsePatch({ customWallpaperUrl: `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp` }),
+ __testing.parsePatch({
+ customWallpaperUrl: `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp`,
+ }),
).toThrow('unknown appearance field');
expect(() => __testing.parsePatch({ wallpaperPath: '/private.png' })).toThrow(
'unknown appearance field',
@@ -195,12 +220,20 @@ describe('appearance settings IPC authorization', () => {
wallpaperId: 'custom',
customWallpaperUrl: `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp`,
});
- const utility = { isDestroyed: () => false, webContents: { isDestroyed: () => false, send: vi.fn() } };
- const content = { isDestroyed: () => false, webContents: { isDestroyed: () => false, send: vi.fn(), setZoomFactor: vi.fn() } };
+ const utility = {
+ isDestroyed: () => false,
+ webContents: { isDestroyed: () => false, send: vi.fn() },
+ };
+ const content = {
+ isDestroyed: () => false,
+ webContents: { isDestroyed: () => false, send: vi.fn(), setZoomFactor: vi.fn() },
+ };
markAppContentWindow(content as never);
mocks.trustedRead.mockReturnValue(true);
mocks.readAppearanceSettings.mockReturnValue(settings);
- const sync = mocks.ipcOn.mock.calls.find(([name]) => name === 'appearance-settings:get-sync')![1];
+ const sync = mocks.ipcOn.mock.calls.find(
+ ([name]) => name === 'appearance-settings:get-sync',
+ )![1];
const event = { sender: {}, returnValue: undefined as unknown };
mocks.fromWebContents.mockReturnValue(utility);
sync(event);
@@ -213,7 +246,9 @@ describe('appearance settings IPC authorization', () => {
mocks.allWindows.push(utility, content);
mocks.trustedReadWindow.mockReturnValue(true);
mocks.writeAppearanceSettingsPatch.mockResolvedValue(settings);
- const set = mocks.ipcHandle.mock.calls.find(([name]) => name === 'appearance-settings:set-patch')![1];
+ const set = mocks.ipcHandle.mock.calls.find(
+ ([name]) => name === 'appearance-settings:set-patch',
+ )![1];
await set({}, { uiSize: 15 });
expect(utility.webContents.send.mock.calls[0][1]).not.toHaveProperty('customWallpaperUrl');
expect(content.webContents.send).toHaveBeenCalledWith('appearance-settings:changed', settings);
diff --git a/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts b/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts
index ad30b905d4..7184b5ea53 100644
--- a/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts
+++ b/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts
@@ -35,6 +35,24 @@ beforeEach(() => {
afterEach(() => fs.rmSync(h.dir, { recursive: true, force: true }));
describe('profile-wide wallpaper preference', () => {
+ it('keeps old preferences untouched, persists zero visibility, and removes its override on reset', async () => {
+ const file = path.join(h.dir, 'appearance-settings.json');
+ const original = JSON.stringify({ wallpaperOverlay: 0.35, uiSize: 18 });
+ fs.writeFileSync(file, original);
+ expect(readAppearanceSettings()).toMatchObject({ wallpaperOverlay: 0.35, uiSize: 18 });
+ expect(readAppearanceSettings()).not.toHaveProperty('wallpaperVisibility');
+ expect(fs.readFileSync(file, 'utf8')).toBe(original);
+ await writeAppearanceSettingsPatch({ wallpaperVisibility: 0 });
+ expect(readAppearanceSettings().wallpaperVisibility).toBe(0);
+ expect(JSON.parse(fs.readFileSync(file, 'utf8')).wallpaperVisibility).toBe(0);
+ await writeAppearanceSettingsPatch({ wallpaperVisibility: 1 });
+ expect(readAppearanceSettings().wallpaperVisibility).toBe(1);
+ await writeAppearanceSettingsPatch({ wallpaperVisibility: null, wallpaperOverlay: 0.2 });
+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
+ expect(saved).not.toHaveProperty('wallpaperVisibility');
+ expect(saved).not.toHaveProperty('wallpaperOverlay');
+ expect(saved.uiSize).toBe(18);
+ });
it('shares selection, replacement and reset across accounts, including sign-out', async () => {
await customWallpaperStore.writePatchAtomic({ url: urlA });
await writeAppearanceSettingsPatch({ wallpaperId: 'custom' });
diff --git a/apps/desktop/src/main/__tests__/customWallpaper.test.ts b/apps/desktop/src/main/__tests__/customWallpaper.test.ts
index b34b27d426..5f9fb85d64 100644
--- a/apps/desktop/src/main/__tests__/customWallpaper.test.ts
+++ b/apps/desktop/src/main/__tests__/customWallpaper.test.ts
@@ -9,6 +9,14 @@ vi.mock('electron', () => ({
app: { getPath: () => h.dir },
dialog: { showOpenDialog: h.picker },
}));
+vi.mock('../../shared/wallpaper-video-manifest.json', () => ({
+ default: {
+ official: {
+ delivery: 'cdn',
+ sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
+ },
+ },
+}));
vi.mock('../localDb/client/current.js', () => ({
getDbClient: h.db,
getCurrentDbClientSnapshot: h.db,
@@ -26,7 +34,11 @@ import {
removeCustomWallpaper,
prepareWallpaperImage,
} from '../custom-wallpaper';
-import { customWallpaperStore, readCustomWallpaperUrl } from '../custom-wallpaper-settings';
+import {
+ customWallpaperStore,
+ readCustomWallpaperUrl,
+ readReferencedClientWallpaperUrls,
+} from '../custom-wallpaper-settings';
import {
writeBlob,
readFile,
@@ -61,6 +73,156 @@ async function selectImage(color = 'blue') {
const parent = {} as never;
describe('client-owned custom wallpaper lifecycle', () => {
+ it('rejects a 20–100 MB image after only the header, even with an MP4 filename', async () => {
+ const png = await selectImage();
+ const file = path.join(h.dir, 'oversized.mp4');
+ fs.writeFileSync(file, png);
+ fs.truncateSync(file, 50 * 1024 * 1024);
+ h.picker.mockResolvedValue({ canceled: false, filePaths: [file] });
+ const realOpen = fs.promises.open;
+ const lengths: number[] = [];
+ vi.spyOn(fs.promises, 'open').mockImplementation(async (...args) => {
+ const handle = await realOpen(...args);
+ if (args[0] === file) {
+ const realRead = handle.read.bind(handle);
+ vi.spyOn(handle, 'read').mockImplementation((async (...readArgs: unknown[]) => {
+ lengths.push((readArgs[0] as Buffer).length);
+ return realRead(
+ readArgs[0] as Buffer,
+ readArgs[1] as number,
+ readArgs[2] as number,
+ readArgs[3] as number,
+ );
+ }) as typeof handle.read);
+ }
+ return handle;
+ });
+ await expect(importCustomWallpaper(parent)).rejects.toThrow('INVALID_PARAMS');
+ expect(lengths).toEqual([4096]);
+ });
+
+ it.each([false, true])(
+ 'cleans failed imports from durable references (published=%s)',
+ async (published) => {
+ await selectImage();
+ await importCustomWallpaper(parent);
+ const official = await writeBlob({
+ buffer: Buffer.from('abc'),
+ mimeType: 'video/mp4',
+ scope: 'client-wallpaper',
+ });
+ const oldUrl = readCustomWallpaperUrl();
+ const video = Buffer.from('000000186674797069736f6d0000000069736f6d6d703432', 'hex');
+ const file = path.join(h.dir, 'replacement.mp4');
+ fs.writeFileSync(file, video);
+ h.picker.mockResolvedValue({ canceled: false, filePaths: [file] });
+ const write = customWallpaperStore.writePatchAtomic.bind(customWallpaperStore);
+ vi.spyOn(customWallpaperStore, 'writePatchAtomic').mockImplementationOnce(async (patch) => {
+ if (published) await write(patch);
+ throw new Error('save failed');
+ });
+ await expect(importCustomWallpaper(parent)).rejects.toThrow('save failed');
+ const current = readCustomWallpaperUrl();
+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(2);
+ await expect(readClientWallpaperFile(official.url)).resolves.toBeDefined();
+ if (published) {
+ expect(current).not.toBe(oldUrl);
+ expect((await readClientWallpaperFile(current)).buffer).toEqual(video);
+ } else {
+ expect(current).toBe(oldUrl);
+ await expect(readClientWallpaperFile(oldUrl)).resolves.toBeDefined();
+ }
+ expect(fs.readFileSync(file)).toEqual(video);
+ },
+ );
+
+ it('preserves the original save error if compensating cleanup also fails', async () => {
+ await selectImage();
+ await importCustomWallpaper(parent);
+ const oldUrl = readCustomWallpaperUrl();
+ await selectImage('red');
+ vi.spyOn(customWallpaperStore, 'writePatchAtomic').mockRejectedValueOnce(
+ new Error('save failed'),
+ );
+ vi.spyOn(recycler, 'recycleClientWallpapers').mockRejectedValueOnce(
+ new Error('cleanup failed'),
+ );
+ await expect(importCustomWallpaper(parent)).rejects.toThrow('save failed');
+ await expect(readClientWallpaperFile(oldUrl)).resolves.toBeDefined();
+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(2);
+ 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('rejects oversized or fake MP4 files without replacing the current image', async () => {
+ await selectImage();
+ await importCustomWallpaper(parent);
+ const current = readCustomWallpaperUrl();
+ const file = path.join(h.dir, 'invalid.mp4');
+ fs.writeFileSync(file, 'not a video');
+ h.picker.mockResolvedValue({ canceled: false, filePaths: [file] });
+ await expect(importCustomWallpaper(parent)).rejects.toThrow('INVALID_PARAMS');
+ fs.truncateSync(file, 100 * 1024 * 1024 + 1);
+ await expect(importCustomWallpaper(parent)).rejects.toThrow('INVALID_PARAMS');
+ expect(readCustomWallpaperUrl()).toBe(current);
+ await expect(readClientWallpaperFile(current)).resolves.toBeDefined();
+ });
+ it('imports a video by its real bytes and recycles it when replaced by an image', async () => {
+ await selectImage();
+ await importCustomWallpaper(parent);
+ const previousImage = readCustomWallpaperUrl();
+ // A small ISO BMFF container fixture, independent of the selected filename.
+ const video = Buffer.from('000000186674797069736f6d0000000069736f6d6d703432', 'hex');
+ const file = path.join(h.dir, 'wallpaper.bin');
+ fs.writeFileSync(file, video);
+ h.picker.mockResolvedValue({ canceled: false, filePaths: [file] });
+ await importCustomWallpaper(parent);
+ const url = readCustomWallpaperUrl();
+ await expect(readClientWallpaperFile(previousImage)).rejects.toThrow();
+ expect(url).toMatch(/\.mp4$/);
+ expect((await readClientWallpaperFile(url)).buffer).toEqual(video);
+ expect(h.picker.mock.calls[0][1].filters[0].extensions).toContain('mp4');
+ await selectImage();
+ await importCustomWallpaper(parent);
+ await expect(readClientWallpaperFile(url)).rejects.toThrow();
+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(1);
+ });
+
+ it('refuses recycling when custom references are unreadable or invalid instead of dropping the video', () => {
+ const file = path.join(h.dir, 'custom-wallpaper.json');
+ for (const content of ['{broken', '[]', 'null', '{"url":"file:///private.mp4"}']) {
+ fs.writeFileSync(file, content);
+ expect(() => readReferencedClientWallpaperUrls()).toThrow();
+ }
+ });
+
+ it('keeps the old video when replacement fails, and removes it only after a successful save', async () => {
+ const file = path.join(h.dir, 'wallpaper.mp4');
+ fs.writeFileSync(file, Buffer.from('000000186674797069736f6d0000000069736f6d6d703432', 'hex'));
+ h.picker.mockResolvedValue({ canceled: false, filePaths: [file] });
+ await importCustomWallpaper(parent);
+ const url = readCustomWallpaperUrl();
+ await selectImage();
+ vi.spyOn(customWallpaperStore, 'writePatchAtomic').mockRejectedValueOnce(new Error('disk'));
+ await expect(importCustomWallpaper(parent)).rejects.toThrow('disk');
+ expect(readCustomWallpaperUrl()).toBe(url);
+ await expect(readClientWallpaperFile(url)).resolves.toBeDefined();
+ await removeCustomWallpaper();
+ expect((await listBlobFiles('client-wallpaper')).entries).toHaveLength(0);
+ expect(fs.existsSync(file)).toBe(true);
+ });
it('imports without a database, then replaces and removes across account switches without touching identical chat bytes', async () => {
const original = await selectImage();
const chat = await writeBlob({
@@ -121,7 +283,7 @@ describe('client-owned custom wallpaper lifecycle', () => {
expect((await readClientWallpaperFile(current)).buffer.length).toBeGreaterThan(0);
});
- it('keeps the published image after save failure and collects the unused bytes on the next successful operation', async () => {
+ it('keeps the published image after save failure and allows subsequent removal', async () => {
await selectImage();
await importCustomWallpaper(parent);
const first = readCustomWallpaperUrl();
diff --git a/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts b/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts
index 25b568273c..fd8bb8cb01 100644
--- a/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts
+++ b/apps/desktop/src/main/__tests__/wallpaperVideo.test.ts
@@ -2,27 +2,63 @@ import { createHash } from 'node:crypto';
import { beforeEach, describe, expect, it, vi } from 'vitest';
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(),
+ 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(),
+}));
+vi.mock('../../shared/wallpaper-video-manifest.json', () => ({
+ default: {
+ 'cindy-window': {
+ delivery: 'cdn',
+ bytes: 3,
+ sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
+ },
+ 'cindy-studio': {
+ delivery: 'bundled',
+ bytes: 3,
+ sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
+ },
+ },
+}));
+vi.mock('../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => m.owner,
+ isAppSessionBoundaryPending: () => m.boundary,
}));
-vi.mock('../../shared/wallpaper-video-manifest.json', () => ({ default: {
- 'cindy-window': { delivery: 'cdn', bytes: 3, sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad' },
- 'cindy-studio': { delivery: 'bundled', bytes: 3, sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad' },
-} }));
-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/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/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/clientWallpaperLock.js', () => ({
+ withClientWallpaperLock: (action: () => Promise<unknown>) => action(),
+}));
vi.mock('../cindy-media/recycler.js', () => ({ recycleClientWallpapers: m.remove }));
+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' }));
+vi.mock('../clientEndpointsService.js', () => ({
+ getClientEndpoint: () => 'https://cdn.example/cindy',
+}));
vi.mock('../maker-host/outbound-fetch.js', () => ({ guardedOutboundFetch: m.fetch }));
import { ensureWallpaperVideo, matchesWallpaperVideo, __testing } from '../wallpaper-video';
@@ -32,8 +68,10 @@ beforeEach(() => {
vi.clearAllMocks();
__testing.reset();
m.snapshot = { client: { drizzle: {} } };
- m.owner = 'one'; m.boundary = false;
- m.cached.mockResolvedValue(null); m.read.mockResolvedValue(null);
+ 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 }));
@@ -55,36 +93,57 @@ describe('optional CDN wallpaper video', () => {
expect(matchesWallpaperVideo(Buffer.from('abd'), { bytes: 3, sha256: hash })).toBe(false);
});
it('downloads once for concurrent windows and publishes a client-owned video', async () => {
- const result = await Promise.all([ensureWallpaperVideo('cindy-window'), ensureWallpaperVideo('cindy-window')]);
+ const result = await Promise.all([
+ ensureWallpaperVideo('cindy-window'),
+ ensureWallpaperVideo('cindy-window'),
+ ]);
expect(result).toEqual([url, url]);
expect(m.fetch).toHaveBeenCalledOnce();
expect(m.fetch.mock.calls[0][0]).toBe('https://cdn.example/cindy/wallpapers/' + hash + '.mp4');
expect(m.ingest).toHaveBeenCalledWith({ buffer: Buffer.from('abc'), mimeType: 'video/mp4' });
- expect(m.remove).toHaveBeenCalledWith([url], '.mp4');
+ expect(m.remove).toHaveBeenCalledWith(
+ [url, `cindy-media://client-wallpaper/${'c'.repeat(64)}.mp4`],
+ '.mp4',
+ );
expect(m.release).toHaveBeenCalledOnce();
});
it('validates and reuses cached media offline without adding references', async () => {
- m.cached.mockResolvedValue(hash); m.read.mockResolvedValue(Buffer.from('abc'));
+ 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.fetch).not.toHaveBeenCalled();
+ expect(m.ingest).not.toHaveBeenCalled();
expect(m.touch).not.toHaveBeenCalled();
});
- it.each([null, Buffer.from('bad')])('redownloads a missing or damaged cache', async bytes => {
- m.cached.mockResolvedValue(hash); m.read.mockResolvedValue(bytes);
+ 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.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 };
- });
- 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();
- });
+ 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,
+ };
+ });
+ 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();
+ },
+ );
it('shares downloads during account transitions without an account database', async () => {
m.boundary = true;
m.fetch.mockImplementation(async () => {
diff --git a/apps/desktop/src/main/appearance-settings-ipc.ts b/apps/desktop/src/main/appearance-settings-ipc.ts
index cc90ced83a..1d55a8afbe 100644
--- a/apps/desktop/src/main/appearance-settings-ipc.ts
+++ b/apps/desktop/src/main/appearance-settings-ipc.ts
@@ -5,6 +5,7 @@ import {
APPEARANCE_LIMITS,
WALLPAPER_IDS,
clampAppearanceWallpaperOverlay,
+ clampAppearanceWallpaperVisibility,
clampAppearanceCodeSize,
clampAppearanceUiSize,
clampAppearanceWindowZoom,
@@ -137,7 +138,10 @@ export async function updatePersistedWindowZoom(delta: number | null): Promise<A
}
// A font/theme reader is not a grant to the client's custom media capability.
-function appearanceForWindow(settings: AppearanceSettings, win: BrowserWindow | null): AppearanceSettings {
+function appearanceForWindow(
+ settings: AppearanceSettings,
+ win: BrowserWindow | null,
+): AppearanceSettings {
if (isAppContentWindow(win)) return settings;
const { customWallpaperUrl: _privateUrl, ...publicSettings } = settings;
return {
@@ -170,6 +174,7 @@ function parsePatch(rawPatch: unknown): AppearanceOverrides {
'windowZoom',
'wallpaperId',
'wallpaperOverlay',
+ 'wallpaperVisibility',
'wallpaperMotion',
]);
for (const key of Object.keys(raw)) {
@@ -223,6 +228,17 @@ function parsePatch(rawPatch: unknown): AppearanceOverrides {
}
patch.wallpaperMotion = raw.wallpaperMotion;
}
+ if ('wallpaperVisibility' in raw) {
+ patch.wallpaperVisibility =
+ raw.wallpaperVisibility === null
+ ? null
+ : parseNumber(
+ raw.wallpaperVisibility,
+ 'wallpaperVisibility',
+ clampAppearanceWallpaperVisibility,
+ APPEARANCE_LIMITS.wallpaperVisibility,
+ );
+ }
return patch;
}
diff --git a/apps/desktop/src/main/cindy-media/__tests__/clientWallpaperVideoRange.test.ts b/apps/desktop/src/main/cindy-media/__tests__/clientWallpaperVideoRange.test.ts
new file mode 100644
index 0000000000..772dd08cf9
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/__tests__/clientWallpaperVideoRange.test.ts
@@ -0,0 +1,170 @@
+import fs from 'node:fs';
+import fsp, { type FileHandle } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({ dir: '', handle: vi.fn(), touch: vi.fn() }));
+vi.mock('electron', () => ({ app: { getPath: () => h.dir }, protocol: { handle: h.handle } }));
+vi.mock('../ledger', () => ({ touchBlob: h.touch }));
+import { registerCindyMediaProtocolHandler } from '../cindyMediaProtocol';
+import { openClientWallpaperVideo } from '../blobStore';
+
+const hash = 'a'.repeat(64);
+const url = `cindy-media://client-wallpaper/${hash}.mp4`;
+let filePath: string;
+let handler: (request: Request) => Promise<Response>;
+let files: FileHandle[];
+let streams: fs.ReadStream[];
+
+beforeEach(() => {
+ h.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wallpaper-range-'));
+ filePath = path.join(h.dir, 'cindy-media', 'client-wallpaper', 'aa', `${hash}.mp4`);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, '0123456789');
+ vi.clearAllMocks();
+ files = [];
+ streams = [];
+ const open = fsp.open.bind(fsp);
+ vi.spyOn(fsp, 'open').mockImplementation(async (...args) => {
+ const file = await open(...args);
+ files.push(file);
+ const create = file.createReadStream.bind(file);
+ vi.spyOn(file, 'createReadStream').mockImplementation((options) => {
+ const stream = create(options);
+ streams.push(stream);
+ return stream;
+ });
+ return file;
+ });
+ registerCindyMediaProtocolHandler();
+ handler = h.handle.mock.calls[0][1];
+});
+
+afterEach(async () => {
+ for (const stream of streams) stream.destroy();
+ for (const file of files) await file.close();
+ vi.restoreAllMocks();
+ fs.rmSync(h.dir, { recursive: true, force: true });
+});
+
+describe('client wallpaper video protocol streaming', () => {
+ it.each([
+ [null, 200, '0123456789', null],
+ ['bytes=2-5', 206, '2345', 'bytes 2-5/10'],
+ ['bytes=8-', 206, '89', 'bytes 8-9/10'],
+ ['bytes=-3', 206, '789', 'bytes 7-9/10'],
+ ['bytes=99-', 416, '', 'bytes */10'],
+ ['bytes=abc', 200, '0123456789', null],
+ ['bytes=0-1,4-5', 200, '0123456789', null],
+ ])('preserves response semantics for %s', async (range, status, body, contentRange) => {
+ const response = await handler(new Request(url, { headers: range ? { Range: range } : {} }));
+ expect(response.status).toBe(status);
+ expect(response.headers.get('Content-Type')).toBe('video/mp4');
+ expect(response.headers.get('Accept-Ranges')).toBe('bytes');
+ expect(response.headers.get('Cache-Control')).toBe('public, max-age=31536000, immutable');
+ expect(response.headers.get('Content-Range')).toBe(contentRange);
+ if (status !== 416) expect(response.headers.get('Content-Length')).toBe(String(body.length));
+ expect(await response.text()).toBe(body);
+ await vi.waitFor(() => expect(files.every((file) => file.fd === -1)).toBe(true));
+ expect(h.touch).not.toHaveBeenCalled();
+ if (status === 416) expect(streams).toHaveLength(0);
+ });
+
+ it('reads only requested bytes for concurrent ranges of a 100 MiB video', async () => {
+ fs.truncateSync(filePath, 100 * 1024 * 1024);
+ const readFile = vi.spyOn(fsp, 'readFile');
+ const starts = [0, 50 * 1024 * 1024, 100 * 1024 * 1024 - 1024];
+ await Promise.all(
+ starts.map(async (start) => {
+ const response = await handler(
+ new Request(url, { headers: { Range: `bytes=${start}-${start + 1023}` } }),
+ );
+ expect(response.status).toBe(206);
+ const bytes = Buffer.from(await response.arrayBuffer());
+ expect(bytes.byteLength).toBe(1024);
+ expect(bytes.subarray(0, 10)).toEqual(
+ start === 0 ? Buffer.from('0123456789') : Buffer.alloc(10),
+ );
+ }),
+ );
+ expect(readFile).not.toHaveBeenCalled();
+ expect(streams.map((stream) => stream.bytesRead)).toEqual([1024, 1024, 1024]);
+ await vi.waitFor(() => expect(files.every((file) => file.fd === -1)).toBe(true));
+ });
+
+ it.each([null, 'bytes=0-'])(
+ 'bounds prefetch and closes a cancelled %s response',
+ async (range) => {
+ fs.truncateSync(filePath, 100 * 1024 * 1024);
+ const response = await handler(new Request(url, { headers: range ? { Range: range } : {} }));
+ // Let the queues fill without consuming: an open range must not preload 100 MiB.
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(streams[0].bytesRead).toBeLessThanOrEqual(3 * 64 * 1024);
+ await response.body!.cancel();
+ await vi.waitFor(() => expect(files[0].fd).toBe(-1));
+ },
+ );
+
+ it.each([false, true])('closes an aborted request (already aborted=%s)', async (already) => {
+ fs.truncateSync(filePath, 100 * 1024 * 1024);
+ const controller = new AbortController();
+ if (already) controller.abort();
+ const response = await handler(new Request(url, { signal: controller.signal }));
+ if (!already) controller.abort();
+ await expect(response.arrayBuffer()).rejects.toThrow();
+ await vi.waitFor(() => expect(files[0].fd).toBe(-1));
+ });
+
+ it('propagates stream errors and closes the descriptor', async () => {
+ const response = await handler(new Request(url));
+ streams[0].destroy(new Error('read failed'));
+ await expect(response.arrayBuffer()).rejects.toThrow('read failed');
+ await vi.waitFor(() => expect(files[0].fd).toBe(-1));
+ });
+
+ it('closes an empty file and handles missing or invalid URLs', async () => {
+ fs.truncateSync(filePath, 0);
+ const empty = await handler(new Request(url));
+ expect(empty.status).toBe(200);
+ expect(empty.headers.get('Content-Length')).toBe('0');
+ expect(await empty.text()).toBe('');
+ expect(files[0].fd).toBe(-1);
+ expect(streams).toHaveLength(0);
+ fs.unlinkSync(filePath);
+ expect((await handler(new Request(url))).status).toBe(404);
+ expect(await handler(new Request(url + '?x=1'))).toHaveProperty('status', 403);
+ await expect(openClientWallpaperVideo(url.replace('.mp4', '.webp'))).rejects.toThrow('invalid');
+ });
+
+ it('rejects a symlinked bucket and a non-file without streaming bytes', async () => {
+ fs.unlinkSync(filePath);
+ fs.rmdirSync(path.dirname(filePath));
+ const outside = path.join(h.dir, 'outside');
+ fs.mkdirSync(outside);
+ fs.writeFileSync(path.join(outside, `${hash}.mp4`), 'private');
+ fs.symlinkSync(
+ outside,
+ path.dirname(filePath),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ expect((await handler(new Request(url))).status).toBe(403);
+ fs.unlinkSync(path.dirname(filePath));
+ fs.mkdirSync(filePath, { recursive: true });
+ expect((await handler(new Request(url))).status).toBe(403);
+ expect(streams).toHaveLength(0);
+ });
+
+ it('rejects replacement during open and closes the unserved handle', async () => {
+ const open = vi.mocked(fsp.open).getMockImplementation()!;
+ vi.mocked(fsp.open).mockImplementationOnce(async (...args) => {
+ const file = await open(...args);
+ fs.renameSync(filePath, filePath + '.old');
+ fs.writeFileSync(filePath, 'replacement');
+ return file;
+ });
+ expect((await handler(new Request(url))).status).toBe(403);
+ expect(files[0].fd).toBe(-1);
+ expect(streams).toHaveLength(0);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-media/blobStore.ts b/apps/desktop/src/main/cindy-media/blobStore.ts
index f69906cfd7..b8c0c3c3b8 100644
--- a/apps/desktop/src/main/cindy-media/blobStore.ts
+++ b/apps/desktop/src/main/cindy-media/blobStore.ts
@@ -530,6 +530,29 @@ export async function readClientWallpaperFile(url: string): Promise<{ buffer: Bu
return { buffer: await fs.readFile(absPath), mimeType };
}
+/** Open a verified wallpaper video once; the response stream owns this handle. */
+export async function openClientWallpaperVideo(url: string) {
+ const parsed = parseClientWallpaperUrl(url);
+ if (parsed?.ext !== '.mp4') throw new Error('cindy-media: invalid client wallpaper video url');
+ const { absPath, mimeType } = resolveHashRef(parsed.hash, parsed.ext, 'client-wallpaper');
+ await assertBlobPathContained(absPath, 'client-wallpaper');
+ const before = await fs.lstat(absPath);
+ if (!before.isFile()) throw new Error('cindy-media: wallpaper is not a regular file');
+ const file = await fs.open(absPath, noFollowReadFlags() | (fsConstants.O_NONBLOCK ?? 0));
+ try {
+ const stat = await file.stat();
+ await assertBlobPathContained(absPath, 'client-wallpaper');
+ const after = await fs.lstat(absPath);
+ if (!stat.isFile() || !sameFileIdentity(before, stat) || !sameFileIdentity(after, stat)) {
+ throw new Error('cindy-media: wallpaper changed while opening');
+ }
+ return { file, totalSize: stat.size, mimeType };
+ } catch (error) {
+ await file.close();
+ throw error;
+ }
+}
+
// ── 回收器 / 对账底层能力(第 5 步)──────────────────────────────────────
// 本模块仍然只管字节:下面的枚举与删除不看账本,"该不该删"由 recycler.ts
// 按账本判定后才调用这里。
diff --git a/apps/desktop/src/main/cindy-media/cindyMediaProtocol.ts b/apps/desktop/src/main/cindy-media/cindyMediaProtocol.ts
index 161dc4529d..6a15bad686 100644
--- a/apps/desktop/src/main/cindy-media/cindyMediaProtocol.ts
+++ b/apps/desktop/src/main/cindy-media/cindyMediaProtocol.ts
@@ -19,7 +19,7 @@ import { protocol, type CustomScheme } from 'electron';
import * as blobStore from './blobStore';
import * as ledger from './ledger';
-import { buildRangedMediaResponse } from './rangeResponse';
+import { buildRangedFileResponse, buildRangedMediaResponse } from './rangeResponse';
import { createLogger } from '../logger';
const log = createLogger('cindyMediaProtocol');
@@ -42,6 +42,14 @@ export const cindyMediaSchemePrivilege: CustomScheme = {
export function registerCindyMediaProtocolHandler(): void {
protocol.handle(SCHEME, async (request) => {
try {
+ if (blobStore.parseClientWallpaperUrl(request.url)?.ext === '.mp4') {
+ return await buildRangedFileResponse({
+ ...(await blobStore.openClientWallpaperVideo(request.url)),
+ rangeHeader: request.headers.get('range'),
+ cacheControl: 'public, max-age=31536000, immutable',
+ signal: request.signal,
+ });
+ }
const { buffer, mimeType } = blobStore.parseClientWallpaperUrl(request.url)
? await blobStore.readClientWallpaperFile(request.url)
: await blobStore.readFile(request.url);
diff --git a/apps/desktop/src/main/cindy-media/ingest.ts b/apps/desktop/src/main/cindy-media/ingest.ts
index 5ee0e33bfe..be4b6357cc 100644
--- a/apps/desktop/src/main/cindy-media/ingest.ts
+++ b/apps/desktop/src/main/cindy-media/ingest.ts
@@ -62,7 +62,7 @@ export type IngestMediaParams = blobStore.BlobSource & {
* compensated after the DbClient worker disappears before its ACK.
*/
refCompensationScope?: MediaRefCompensationScope;
-}
+};
export interface IngestedMedia {
/** SHA-256 指纹(64 位小写十六进制)。 */
@@ -154,13 +154,14 @@ export const supportedMime = blobStore.supportedMime;
/**
* Client UI media has no account owner. Its reference is the client appearance
- * setting (custom WebP) or bundled catalog (optional CDN MP4), not an account DB.
+ * setting (custom WebP/MP4) or bundled catalog (optional CDN MP4), not an account DB.
* Reuse the same atomic byte store in an isolated deletion scope; callers must
* serialize publication and recycling with the client wallpaper operation lock.
*/
-export async function ingestClientWallpaper(
- params: { buffer: Uint8Array; mimeType: 'image/webp' | 'video/mp4' },
-): Promise<blobStore.WrittenBlob> {
+export async function ingestClientWallpaper(params: {
+ buffer: Uint8Array;
+ mimeType: 'image/webp' | 'video/mp4';
+}): Promise<blobStore.WrittenBlob> {
if (params.mimeType !== 'image/webp' && params.mimeType !== 'video/mp4')
throw new Error('cindy-media: unsupported client wallpaper type');
return blobStore.writeBlob({ ...params, scope: 'client-wallpaper' });
diff --git a/apps/desktop/src/main/cindy-media/rangeResponse.ts b/apps/desktop/src/main/cindy-media/rangeResponse.ts
index ee1eb16a3a..afcc70d663 100644
--- a/apps/desktop/src/main/cindy-media/rangeResponse.ts
+++ b/apps/desktop/src/main/cindy-media/rangeResponse.ts
@@ -11,6 +11,8 @@
*/
import { parseRangeHeader } from '../audioFileProtocol.js';
+import type { FileHandle } from 'node:fs/promises';
+import { addAbortSignal, Readable } from 'node:stream';
/** Buffer → 独立 ArrayBuffer(Response 不接受共享底层的偏移视图)。 */
function toArrayBuffer(buf: Buffer): ArrayBuffer {
@@ -67,3 +69,55 @@ export function buildRangedMediaResponse(params: {
},
});
}
+
+/** Consume an already verified file handle, streaming only the selected bytes. */
+export async function buildRangedFileResponse(params: {
+ file: FileHandle;
+ totalSize: number;
+ mimeType: string;
+ rangeHeader: string | null;
+ cacheControl: string;
+ signal: AbortSignal;
+}): Promise<Response> {
+ const { file, totalSize, mimeType, rangeHeader, cacheControl, signal } = params;
+ try {
+ const range = parseRangeHeader(rangeHeader, totalSize);
+ const headers: Record<string, string> = {
+ 'Content-Type': mimeType,
+ 'Accept-Ranges': 'bytes',
+ 'Cache-Control': cacheControl,
+ };
+ if (range?.kind === 'unsatisfiable') {
+ await file.close();
+ return new Response(null, {
+ status: 416,
+ headers: { ...headers, 'Content-Range': `bytes */${totalSize}` },
+ });
+ }
+ const start = range?.kind === 'range' ? range.start : 0;
+ const end = range?.kind === 'range' ? range.end : totalSize - 1;
+ headers['Content-Length'] = String(end - start + 1);
+ if (range) headers['Content-Range'] = `bytes ${start}-${end}/${totalSize}`;
+ if (totalSize === 0) {
+ await file.close();
+ return new Response(null, { status: 200, headers });
+ }
+ // Both queues are byte-bounded. toWeb's default counts chunks, which could
+ // otherwise buffer thousands of 64 KiB chunks from an open-ended Range.
+ // autoClose handles EOF/errors; web cancellation and request abort destroy it.
+ const stream = file.createReadStream({ start, end, highWaterMark: 64 * 1024 });
+ const body = Readable.toWeb(stream, {
+ strategy: { highWaterMark: 64 * 1024, size: (chunk: Uint8Array) => chunk.byteLength },
+ });
+ // Attach cancellation only after toWeb installed its error listener, including
+ // when the request was already aborted while opening the file.
+ addAbortSignal(signal, stream);
+ return new Response(body as ReadableStream<Uint8Array>, {
+ status: range ? 206 : 200,
+ headers,
+ });
+ } catch (error) {
+ await file.close();
+ throw error;
+ }
+}
diff --git a/apps/desktop/src/main/cindy-media/recycler.ts b/apps/desktop/src/main/cindy-media/recycler.ts
index f631786bc8..4b21f9a93c 100644
--- a/apps/desktop/src/main/cindy-media/recycler.ts
+++ b/apps/desktop/src/main/cindy-media/recycler.ts
@@ -31,7 +31,7 @@ import type { LedgerDb } from './ledger';
const log = createLogger('cindy-media-recycler');
-/** Called under the client wallpaper publication lock after saving its reference.
+/** Called under the client wallpaper publication lock with re-read durable references.
* This scope cannot contain chat/attachment bytes; never delete ordinary blobs.
* A later successful operation also retries failed cleanup or interrupted imports.
*/
diff --git a/apps/desktop/src/main/custom-wallpaper-settings.ts b/apps/desktop/src/main/custom-wallpaper-settings.ts
index e1590c08b9..114d793e87 100644
--- a/apps/desktop/src/main/custom-wallpaper-settings.ts
+++ b/apps/desktop/src/main/custom-wallpaper-settings.ts
@@ -1,12 +1,16 @@
import { app } from 'electron';
import path from 'node:path';
+import fs from 'node:fs';
import { normalizeCustomWallpaperUrl } from '../shared/appearanceSettings.js';
import { createOverrideSettingsFile } from './maker-host/override-settings-file.js';
import { createLogger } from './logger.js';
+import manifest from '../shared/wallpaper-video-manifest.json';
+import { blobUrl } from './cindy-media/blobStore.js';
+import { readBoundedFileNoFollowSync } from './utils/readBoundedFile.js';
const filePath = () => path.join(app.getPath('userData'), 'custom-wallpaper.json');
-// Like theme preferences, the image is shared by accounts in this Desktop profile.
+// Like theme preferences, the media is shared by accounts in this Desktop profile.
export const customWallpaperStore = createOverrideSettingsFile<{ url: string }>({
filePath,
defaults: { url: '' },
@@ -25,3 +29,34 @@ export function readCustomWallpaperUrl(): string {
customWallpaperStore.invalidateIfChanged();
return customWallpaperStore.read().url;
}
+
+/** Both custom media and optional official downloads own references in this scope. */
+export function readReferencedClientWallpaperUrls(): string[] {
+ // Display reads may fall back to defaults; recycling must never interpret a
+ // corrupt/unreadable preference as permission to delete the user's video.
+ let customUrl = '';
+ let exists = true;
+ try {
+ fs.lstatSync(filePath());
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ exists = false;
+ }
+ if (exists) {
+ const bytes = readBoundedFileNoFollowSync(filePath(), 4096);
+ if (!bytes) throw new Error('Cannot read client wallpaper references');
+ const raw: unknown = JSON.parse(bytes.toString('utf8'));
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
+ throw new Error('Invalid client wallpaper references');
+ const url = (raw as { url?: unknown }).url;
+ customUrl = normalizeCustomWallpaperUrl(url);
+ if (url !== undefined && url !== '' && !customUrl)
+ throw new Error('Invalid client wallpaper reference');
+ }
+ return [
+ customUrl,
+ ...Object.values(manifest)
+ .filter((item) => item.delivery === 'cdn')
+ .map((item) => blobUrl(item.sha256, '.mp4', 'client-wallpaper')),
+ ].filter(Boolean);
+}
diff --git a/apps/desktop/src/main/custom-wallpaper.ts b/apps/desktop/src/main/custom-wallpaper.ts
index cfa0391fcc..24b46b6225 100644
--- a/apps/desktop/src/main/custom-wallpaper.ts
+++ b/apps/desktop/src/main/custom-wallpaper.ts
@@ -6,11 +6,16 @@ import { throwIpcError } from './utils/ipcValidate.js';
import { ingestClientWallpaper } from './cindy-media/ingest.js';
import { recycleClientWallpapers } from './cindy-media/recycler.js';
import { withClientWallpaperLock } from './cindy-media/clientWallpaperLock.js';
-import { customWallpaperStore, readCustomWallpaperUrl } from './custom-wallpaper-settings.js';
+import {
+ customWallpaperStore,
+ readReferencedClientWallpaperUrls,
+} from './custom-wallpaper-settings.js';
+import { sniffMediaMime } from './cindy-media/sniffMediaMime.js';
import { createLogger } from './logger.js';
const log = createLogger('custom-wallpaper');
const MAX_BYTES = 20 * 1024 * 1024;
+const MAX_VIDEO_BYTES = 100 * 1024 * 1024;
/** Decode real raster bytes, apply orientation, strip metadata and retain a static 4K preview. */
export async function prepareWallpaperImage(bytes: Buffer): Promise<Buffer> {
@@ -35,27 +40,42 @@ export async function prepareWallpaperImage(bytes: Buffer): Promise<Buffer> {
export async function importCustomWallpaper(parent: BrowserWindow): Promise<boolean> {
const selected = await dialog.showOpenDialog(parent, {
properties: ['openFile'],
- filters: [{ name: 'PNG / JPEG / WebP', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],
+ filters: [
+ { name: 'PNG / JPEG / WebP / MP4', extensions: ['png', 'jpg', 'jpeg', 'webp', 'mp4'] },
+ ],
});
if (selected.canceled || !selected.filePaths[0]) return false;
let bytes: Buffer;
try {
- const read = await readBoundedFileNoFollow(selected.filePaths[0], MAX_BYTES, {
+ const read = await readBoundedFileNoFollow(selected.filePaths[0], MAX_VIDEO_BYTES, {
nonBlocking: true,
+ // Reject known oversized images before allocating their full contents.
+ // Unknown prefixes retain the outer limit (e.g. a large ftyp box);
+ // full-byte sniffing and image decoding still validate them below.
+ maxBytesForPrefix: (prefix) =>
+ sniffMediaMime(prefix)?.startsWith('image/') ? MAX_BYTES : MAX_VIDEO_BYTES,
});
- if (!read) throw new Error('Unreadable image');
+ if (!read) throw new Error('Unreadable wallpaper');
bytes = read;
} catch {
- throwIpcError('INVALID_PARAMS', 'Cannot read image; choose a local image up to 20 MB');
+ throwIpcError('INVALID_PARAMS', 'Choose a local image up to 20 MB or MP4 video up to 100 MB');
}
- const buffer = await prepareWallpaperImage(bytes);
+ const isVideo = sniffMediaMime(bytes) === 'video/mp4';
+ const buffer = isVideo ? bytes : await prepareWallpaperImage(bytes);
return withClientWallpaperLock(async () => {
- const media = await ingestClientWallpaper({ buffer, mimeType: 'image/webp' });
- await customWallpaperStore.writePatchAtomic({ url: media.url });
- // Recycle only after successful publication. Unreadable settings or a failed
- // write must not delete the previous image; a later successful operation also
- // collects bytes left by interrupted/failed imports.
- await recycleUnusedImages();
+ const media = await ingestClientWallpaper({
+ buffer,
+ mimeType: isVideo ? 'video/mp4' : 'image/webp',
+ });
+ try {
+ await customWallpaperStore.writePatchAtomic({ url: media.url });
+ } catch (error) {
+ // A reported failure may follow publication: re-read durable references.
+ // Unreadable references defer cleanup rather than risking the current media.
+ await recycleUnusedWallpapers();
+ throw error;
+ }
+ await recycleUnusedWallpapers();
return true;
});
}
@@ -63,13 +83,15 @@ export async function importCustomWallpaper(parent: BrowserWindow): Promise<bool
export async function removeCustomWallpaper(): Promise<void> {
return withClientWallpaperLock(async () => {
await customWallpaperStore.resetAtomic();
- await recycleUnusedImages();
+ await recycleUnusedWallpapers();
});
}
-async function recycleUnusedImages(): Promise<void> {
+async function recycleUnusedWallpapers(): Promise<void> {
try {
- await recycleClientWallpapers([readCustomWallpaperUrl()], '.webp');
+ const keep = readReferencedClientWallpaperUrls();
+ await recycleClientWallpapers(keep, '.webp');
+ await recycleClientWallpapers(keep, '.mp4');
} catch {
log.warn('Unused client wallpaper cleanup deferred');
}
diff --git a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
index 0ea5b2c6d7..57bc4ed6a8 100644
--- a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
+++ b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
@@ -30,6 +30,56 @@ afterEach(async () => {
});
describe('readBoundedFileNoFollow', () => {
+ it('rejects by a bounded prefix before reading the payload, using one handle', async () => {
+ const file = path.join(workDir, 'large.bin');
+ await fs.promises.writeFile(file, Buffer.alloc(8192, 7));
+ const realOpen = fs.promises.open;
+ const lengths: number[] = [];
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation(async (...args) => {
+ const handle = await realOpen(...args);
+ const realRead = handle.read.bind(handle);
+ vi.spyOn(handle, 'read').mockImplementation((async (...readArgs: unknown[]) => {
+ lengths.push((readArgs[0] as Buffer).length);
+ return realRead(
+ readArgs[0] as Buffer,
+ readArgs[1] as number,
+ readArgs[2] as number,
+ readArgs[3] as number,
+ );
+ }) as typeof handle.read);
+ return handle;
+ });
+ try {
+ const limit = vi.fn<(prefix: Buffer) => number>(() => 4096);
+ expect(await readBoundedFileNoFollow(file, 16384, { maxBytesForPrefix: limit })).toBeNull();
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ expect(lengths).toEqual([4096]);
+ expect(limit.mock.calls[0][0]).toEqual(Buffer.alloc(4096, 7));
+ lengths.length = 0;
+ expect(await readBoundedFileNoFollow(file, 16384, { maxBytesForPrefix: () => 8192 })).toEqual(
+ Buffer.alloc(8192, 7),
+ );
+ expect(lengths).toEqual([4096, 8192]);
+ expect(
+ await readBoundedFileNoFollow(file, 4096, { maxBytesForPrefix: () => 16384 }),
+ ).toBeNull();
+ } finally {
+ vi.restoreAllMocks();
+ }
+ });
+
+ it('still rejects content changed between the prefix probe and the full read', async () => {
+ const file = path.join(workDir, 'changing.bin');
+ await fs.promises.writeFile(file, 'before');
+ await expect(
+ readBoundedFileNoFollow(file, 1024, {
+ maxBytesForPrefix: () => {
+ fs.writeFileSync(file, 'changed-and-longer');
+ return 1024;
+ },
+ }),
+ ).rejects.toThrow('source file changed');
+ });
it('opens follow-links untrusted paths in non-blocking mode; no-follow defaults to blocking', async () => {
const file = path.join(workDir, 'plain.json');
await fs.promises.writeFile(file, '{"ok":1}');
diff --git a/apps/desktop/src/main/utils/readBoundedFile.ts b/apps/desktop/src/main/utils/readBoundedFile.ts
index 6ddf742db3..3a3c1b5fca 100644
--- a/apps/desktop/src/main/utils/readBoundedFile.ts
+++ b/apps/desktop/src/main/utils/readBoundedFile.ts
@@ -38,6 +38,8 @@ export interface ReadBoundedFileOptions {
rejectHardLinks?: boolean;
/** 复读同一句柄并比较字节;内容或版本变化时抛出可重试错误。 */
verifyContentStability?: boolean;
+ /** Optionally lower the size limit using up to 4 KiB from the same verified handle. */
+ maxBytesForPrefix?: (prefix: Buffer) => number;
}
type ReadBoundedFileNoFollowSyncOptions = Pick<
@@ -240,6 +242,12 @@ export async function readBoundedFileNoFollowWithStat(
if (options?.containWithin !== undefined) {
if (!(await verifyStillWithinRoot(stat, filePath, options.containWithin))) return null;
}
+ if (options?.maxBytesForPrefix) {
+ const prefix = await readToLength(handle, Math.min(Number(stat.size), 4096));
+ const limit = options.maxBytesForPrefix(prefix);
+ if (!Number.isFinite(limit) || limit < 0 || Number(stat.size) > Math.min(maxBytes, limit))
+ return null;
+ }
const bytes = await readToLength(handle, Number(stat.size));
const after = await handle.stat({ bigint: true });
if (options?.rejectHardLinks && after.nlink !== 1n) {
diff --git a/apps/desktop/src/main/wallpaper-video.ts b/apps/desktop/src/main/wallpaper-video.ts
index 442d011059..1d63f58d95 100644
--- a/apps/desktop/src/main/wallpaper-video.ts
+++ b/apps/desktop/src/main/wallpaper-video.ts
@@ -8,6 +8,7 @@ import { readBoundedFileNoFollow } from './utils/readBoundedFile.js';
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';
type Scene = keyof typeof manifest;
type Asset = { sha256: string; bytes: number };
@@ -85,12 +86,9 @@ export async function ensureWallpaperVideo(id: unknown): Promise<string | null>
const bytes = await download(asset);
return await withClientWallpaperLock(async () => {
const media = await ingestClientWallpaper({ buffer: bytes, mimeType: 'video/mp4' });
- await recycleClientWallpapers(
- Object.values(manifest)
- .filter((item) => item.delivery === 'cdn')
- .map((item) => blobUrl(item.sha256, '.mp4', 'client-wallpaper')),
- '.mp4',
- ).catch(() => undefined);
+ await recycleClientWallpapers(readReferencedClientWallpaperUrls(), '.mp4').catch(
+ () => undefined,
+ );
return media.url;
});
} catch {
diff --git a/apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx b/apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx
index 388e3a26e5..027de7497b 100644
--- a/apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx
+++ b/apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx
@@ -1,23 +1,48 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import type { WallpaperId, WallpaperMotion } from '@/../shared/appearanceSettings';
+import {
+ isCustomWallpaperVideo,
+ 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';
-/** One decoder and one viewport canvas. Static mode does not fetch any video. */
+/** One decoder and one viewport canvas. Custom videos retain a paused frame in static mode. */
export function WallpaperVideo({
wallpaperId,
motion,
+ customWallpaperUrl,
+ onFailure,
+ onReady,
}: {
wallpaperId: WallpaperId;
motion: WallpaperMotion;
+ customWallpaperUrl?: string;
+ onFailure?: () => void;
+ onReady?: () => void;
}) {
const reducedMotion = useReducedMotion();
+ if (wallpaperId === 'custom' && isCustomWallpaperVideo(customWallpaperUrl)) {
+ const src = normalizeCustomWallpaperUrl(customWallpaperUrl);
+ return (
+ <PlayingWallpaper
+ key={src}
+ src={src}
+ active
+ playing={motion === 'dynamic' && !reducedMotion}
+ onFailure={onFailure}
+ onReady={onReady}
+ />
+ );
+ }
const src = getWallpaperVideo(wallpaperId);
if (reducedMotion || !src) return null;
- return <WallpaperPlayback key={wallpaperId} wallpaperId={wallpaperId} active={motion === 'dynamic'} />;
+ return (
+ <WallpaperPlayback key={wallpaperId} wallpaperId={wallpaperId} active={motion === 'dynamic'} />
+ );
}
type PlaybackProps = { active: boolean; onExited: () => void };
@@ -25,25 +50,38 @@ type PlaybackProps = { active: boolean; onExited: () => void };
function WallpaperPlayback({ wallpaperId, active }: { wallpaperId: WallpaperId; active: boolean }) {
const [retained, setRetained] = useState(active);
const onExited = useCallback(() => setRetained(false), []);
- useEffect(() => { if (active) setRetained(true); }, [active]);
+ 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} />;
+ 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) {
+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); })
+ void window.electronAPI?.appearanceSettings
+ ?.ensureWallpaperVideo?.(wallpaperId)
+ .then((url) => {
+ if (current) setHdSrc(url);
+ })
.catch(() => undefined);
- return () => { current = false; };
+ return () => {
+ current = false;
+ };
}, [wallpaperId, tier, hdFailed, hdSrc, active]);
const useHd = tier === 'hd' && !hdFailed && !!hdSrc;
const src = useHd ? hdSrc : getWallpaperVideo(wallpaperId);
@@ -58,36 +96,60 @@ function AdaptiveWallpaper({ wallpaperId, active, onExited }: { wallpaperId: Wal
) : null;
}
-function PlayingWallpaper({ src, onFailure, active, onExited }: { src: string; onFailure?: () => void } & PlaybackProps) {
+function PlayingWallpaper({
+ src,
+ onFailure,
+ active,
+ onExited,
+ playing = true,
+ onReady,
+}: {
+ src: string;
+ onFailure?: () => void;
+ active: boolean;
+ onExited?: () => void;
+ playing?: boolean;
+ onReady?: () => void;
+}) {
const ref = useRef<HTMLVideoElement>(null);
const layerRef = useRef<HTMLDivElement>(null);
const onFailureRef = useRef(onFailure);
onFailureRef.current = onFailure;
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
+ const playingRef = useRef(playing);
+ playingRef.current = playing;
+ const syncPlaybackRef = useRef<() => void>(() => {});
useEffect(() => {
if (active) return;
if (!ready || failed || !layerRef.current) {
- onExited();
+ onExited?.();
return;
}
// Bound decoder retention even when transitionend is suppressed (e.g. hidden
// windows). Read the CSS token's resolved duration rather than duplicating it.
const duration = getComputedStyle(layerRef.current).transitionDuration;
const ms = (parseFloat(duration) || 0) * (duration.endsWith('ms') ? 1 : 1000);
- const timeout = window.setTimeout(onExited, ms);
+ const timeout = window.setTimeout(() => onExited?.(), ms);
return () => window.clearTimeout(timeout);
}, [active, ready, failed, onExited]);
useLayoutEffect(() => {
if (!ready || failed) return;
+ // A paused custom frame still lives on the video canvas; keep the composer
+ // transparent instead of painting the image-only fallback over that frame.
document.documentElement.dataset.wallpaperMotion = 'dynamic';
return () => {
delete document.documentElement.dataset.wallpaperMotion;
};
}, [ready, failed]);
+ useEffect(() => {
+ syncPlaybackRef.current();
+ if (!playing && (ref.current?.readyState ?? 0) >= 2) setReady(true);
+ }, [playing]);
+
useEffect(() => {
const video = ref.current;
if (!video || failed) return;
@@ -97,7 +159,11 @@ function PlayingWallpaper({ src, onFailure, active, onExited }: { src: string; o
const sync = () => {
const current = ++generation;
// The shared gate also covers Electron minimize/hide with throttling disabled.
- if (document.hidden || document.documentElement.hasAttribute(HIDDEN_ANIMATION_ATTR)) {
+ if (
+ !playingRef.current ||
+ document.hidden ||
+ document.documentElement.hasAttribute(HIDDEN_ANIMATION_ATTR)
+ ) {
video.pause();
} else {
void video.play().catch(() => {
@@ -108,6 +174,7 @@ function PlayingWallpaper({ src, onFailure, active, onExited }: { src: string; o
});
}
};
+ syncPlaybackRef.current = sync;
const observer = new MutationObserver(sync);
observer.observe(document.documentElement, {
attributes: true,
@@ -117,6 +184,7 @@ function PlayingWallpaper({ src, onFailure, active, onExited }: { src: string; o
sync();
return () => {
generation++;
+ syncPlaybackRef.current = () => {};
observer.disconnect();
document.removeEventListener('visibilitychange', sync);
video.pause();
@@ -132,8 +200,9 @@ function PlayingWallpaper({ src, onFailure, active, onExited }: { src: string; o
className="app-wallpaper-video"
aria-hidden="true"
style={{ opacity: ready && active ? 1 : 0 }}
- onTransitionEnd={event => {
- if (event.target === event.currentTarget && event.propertyName === 'opacity' && !active) onExited();
+ onTransitionEnd={(event) => {
+ if (event.target === event.currentTarget && event.propertyName === 'opacity' && !active)
+ onExited?.();
}}
>
<video
@@ -144,7 +213,14 @@ function PlayingWallpaper({ src, onFailure, active, onExited }: { src: string; o
playsInline
preload="auto"
disablePictureInPicture
- onPlaying={() => setReady(true)}
+ onLoadedData={() => {
+ if (!playingRef.current) setReady(true);
+ onReady?.();
+ }}
+ onPlaying={() => {
+ setReady(true);
+ onReady?.();
+ }}
onError={() => {
setFailed(true);
onFailureRef.current?.();
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx
index b0a5ea3c27..d3a28c3cbf 100644
--- a/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx
+++ b/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx
@@ -4,6 +4,10 @@ import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { WallpaperVideo } from '../WallpaperVideo';
import { HIDDEN_ANIMATION_ATTR } from '@/lib/hiddenAnimationGate';
+import { parse } from 'postcss';
+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 ensureVideo = vi.fn();
@@ -12,10 +16,36 @@ vi.mock('@/hooks/useWallpaperVideoTier', () => ({ useWallpaperVideoTier: () => s
vi.mock('@/lib/wallpaper', () => ({
usesCdnWallpaperVideo: () => state.cdn,
getWallpaperVideo: (id: string, tier = 'standard') =>
- (id.startsWith('cindy-') ? `/${id}${tier === 'hd' ? '-hd' : ''}.mp4` : undefined),
+ id.startsWith('cindy-') ? `/${id}${tier === 'hd' ? '-hd' : ''}.mp4` : undefined,
}));
describe('dynamic wallpaper lifecycle', () => {
+ it('keeps visibility on the video over an opaque theme backing without an independent veil', () => {
+ // The import tracks CSS dependencies for Vitest related; unit mode stubs CSS
+ // modules, so read the source explicitly. Pixel/HDR acceptance stays separate.
+ const css = parse(readFileSync(resolve(__dirname, '../../../styles/globals.css'), 'utf8'));
+ const declarations = (selector: string) => {
+ const values: Record<string, string> = {};
+ css.walkRules(selector, (rule) => {
+ rule.walkDecls((decl) => {
+ values[decl.prop] = decl.value;
+ });
+ });
+ return values;
+ };
+ expect(declarations('.app-wallpaper-video').background).toBe('var(--surface)');
+ expect(declarations('.app-wallpaper-video').opacity).toBeUndefined();
+ expect(declarations('.app-wallpaper-video video').opacity).toBe(
+ 'calc(100% - var(--app-wallpaper-veil))',
+ );
+ css.walkRules((rule) => {
+ if (/\.app-wallpaper-video[^,{]*::?(before|after)/.test(rule.selector)) {
+ rule.walkDecls('content', (decl) => {
+ expect(['none', 'normal']).toContain(decl.value);
+ });
+ }
+ });
+ });
beforeEach(() => {
state.reduced = false;
state.tier = 'standard';
@@ -44,6 +74,48 @@ describe('dynamic wallpaper lifecycle', () => {
expect(document.querySelector('video')).toBeNull();
expect(ensureVideo).not.toHaveBeenCalled();
});
+ it('plays custom videos silently, freezes in static/reduced motion, and releases the replaced source', () => {
+ const src = `cindy-media://client-wallpaper/${'a'.repeat(64)}.mp4`;
+ const { rerender, unmount } = render(
+ <WallpaperVideo wallpaperId="custom" motion="static" customWallpaperUrl={src} />,
+ );
+ const video = document.querySelector('video')!;
+ expect(video.getAttribute('src')).toBe(src);
+ expect(video.play).not.toHaveBeenCalled();
+ fireEvent.loadedData(video);
+ expect(video.parentElement!.style.opacity).toBe('1');
+ rerender(<WallpaperVideo wallpaperId="custom" motion="dynamic" customWallpaperUrl={src} />);
+ expect(document.querySelectorAll('video')).toHaveLength(1);
+ expect(video.play).toHaveBeenCalledOnce();
+ expect(video.muted && video.loop).toBe(true);
+ state.reduced = true;
+ rerender(<WallpaperVideo wallpaperId="custom" motion="dynamic" customWallpaperUrl={src} />);
+ expect(document.querySelector('video')).toBe(video);
+ expect(video.pause).toHaveBeenCalled();
+ const next = src.replace('a'.repeat(64), 'b'.repeat(64));
+ rerender(<WallpaperVideo wallpaperId="custom" motion="dynamic" customWallpaperUrl={next} />);
+ expect(video.getAttribute('src')).toBeNull();
+ expect(document.querySelector('video')!.getAttribute('src')).toBe(next);
+ expect(ensureVideo).not.toHaveBeenCalled();
+ unmount();
+ expect(document.documentElement.dataset.wallpaperMotion).toBeUndefined();
+ });
+ it('reports an unplayable custom video and releases its decoder', () => {
+ const onFailure = vi.fn();
+ render(
+ <WallpaperVideo
+ wallpaperId="custom"
+ motion="dynamic"
+ customWallpaperUrl={`cindy-media://client-wallpaper/${'a'.repeat(64)}.mp4`}
+ onFailure={onFailure}
+ />,
+ );
+ const video = document.querySelector('video')!;
+ fireEvent.error(video);
+ expect(onFailure).toHaveBeenCalledOnce();
+ expect(document.querySelector('video')).toBeNull();
+ expect(video.getAttribute('src')).toBeNull();
+ });
it('shows only decoded frames, pauses with the shared hidden gate, and releases on static', async () => {
vi.useFakeTimers();
state.cdn = false;
@@ -63,7 +135,9 @@ describe('dynamic wallpaper lifecycle', () => {
expect(video.getAttribute('src')).not.toBeNull();
// DOM removal precedes passive decoder cleanup. Flush the exit timer and
// React effects together instead of racing waitFor's DOM-only observation.
- await act(async () => { vi.advanceTimersByTime(200); });
+ await act(async () => {
+ vi.advanceTimersByTime(200);
+ });
expect(document.querySelector('video')).toBeNull();
expect(video.getAttribute('src')).toBeNull();
expect(video.load).toHaveBeenCalled();
@@ -154,40 +228,50 @@ describe('dynamic wallpaper lifecycle', () => {
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(['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);
@@ -201,7 +285,11 @@ describe('dynamic wallpaper lifecycle', () => {
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; }));
+ ensureVideo.mockReturnValue(
+ new Promise<string>((resolve) => {
+ finish = resolve;
+ }),
+ );
const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);
rerender(<WallpaperVideo wallpaperId="cindy-window" motion="static" />);
await act(async () => finish('/old-hd.mp4'));
diff --git a/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx b/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
index 31153078c6..1d64ea5120 100644
--- a/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
@@ -1,5 +1,5 @@
import { useTranslation } from 'react-i18next';
-import { RotateCcw, ImagePlus } from 'lucide-react';
+import { RotateCcw, ImagePlus, Film } from 'lucide-react';
import { useState } from 'react';
import { extractIpcError } from '@/utils/ipcError';
@@ -12,6 +12,7 @@ import { getBuiltinWallpaperBackground, isSceneWallpaper } from '@/lib/wallpaper
import {
APPEARANCE_LIMITS,
DEFAULT_APPEARANCE_SETTINGS,
+ isCustomWallpaperVideo,
type WallpaperId,
} from '@/../shared/appearanceSettings';
@@ -29,14 +30,18 @@ export function WallpaperSection() {
const {
wallpaperId,
wallpaperOverlay,
+ wallpaperVisibility,
+ visibility,
wallpaperMotion,
customWallpaperUrl,
+ playbackFailed,
setWallpaper,
- setOverlay,
+ setVisibility,
setMotion,
resetWallpaper,
} = useWallpaperSettings();
- const chooseImage = async () => {
+ const customVideo = isCustomWallpaperVideo(customWallpaperUrl);
+ const chooseWallpaper = async () => {
setBusy(true);
setError('');
try {
@@ -54,7 +59,7 @@ export function WallpaperSection() {
setBusy(false);
}
};
- const removeImage = async () => {
+ const removeWallpaper = async () => {
setBusy(true);
setError('');
try {
@@ -94,6 +99,7 @@ export function WallpaperSection() {
busy ||
(wallpaperId === DEFAULT_APPEARANCE_SETTINGS.wallpaperId &&
wallpaperOverlay === DEFAULT_APPEARANCE_SETTINGS.wallpaperOverlay &&
+ wallpaperVisibility == null &&
wallpaperMotion === DEFAULT_APPEARANCE_SETTINGS.wallpaperMotion)
}
>
@@ -110,7 +116,7 @@ export function WallpaperSection() {
{[...WALLPAPER_OPTIONS, { id: 'custom' as const }].map((option) => {
const selected = wallpaperId === option.id;
const background =
- option.id === 'custom' && customWallpaperUrl
+ option.id === 'custom' && customWallpaperUrl && !customVideo
? `url("${customWallpaperUrl}")`
: getBuiltinWallpaperBackground(option.id);
return (
@@ -123,7 +129,7 @@ export function WallpaperSection() {
disabled={busy}
onClick={() =>
option.id === 'custom' && !customWallpaperUrl
- ? void chooseImage()
+ ? void chooseWallpaper()
: setWallpaper(option.id)
}
className={cn(
@@ -145,6 +151,11 @@ export function WallpaperSection() {
backgroundSize: 'cover',
}}
>
+ {option.id === 'custom' && customVideo ? (
+ <span className="absolute inset-0 flex items-center justify-center text-[var(--settings-section-sublabel)]">
+ <Film size={22} aria-hidden="true" />
+ </span>
+ ) : null}
{option.id === 'custom' && !customWallpaperUrl ? (
<span className="absolute inset-0 flex items-center justify-center text-[var(--settings-section-sublabel)]">
<ImagePlus size={22} aria-hidden="true" />
@@ -176,7 +187,7 @@ export function WallpaperSection() {
variant="secondary"
type="button"
disabled={busy}
- onClick={() => void chooseImage()}
+ onClick={() => void chooseWallpaper()}
>
<ImagePlus size={14} aria-hidden="true" />
{t(
@@ -188,7 +199,7 @@ export function WallpaperSection() {
variant="secondary"
type="button"
disabled={busy}
- onClick={() => void removeImage()}
+ onClick={() => void removeWallpaper()}
>
{t('settings.appearance.wallpaper.customRemove')}
</Button>
@@ -197,16 +208,16 @@ export function WallpaperSection() {
{t('settings.appearance.wallpaper.customHint')}
</p>
</div>
- {error && (
+ {(error || (wallpaperId === 'custom' && playbackFailed)) && (
<p role="alert" className="text-12 text-[var(--text-primary)]">
- {error}
+ {error || t('settings.appearance.wallpaper.customPlaybackFailed')}
</p>
)}
<div className="h-px bg-[var(--settings-input-border)]" />
<div className="flex flex-col gap-3">
- {isSceneWallpaper(wallpaperId) && (
+ {(isSceneWallpaper(wallpaperId) || (wallpaperId === 'custom' && customVideo)) && (
<div className="flex items-center justify-between gap-3">
<div>
<p className="text-13 font-medium text-[var(--settings-section-sublabel)]">
@@ -229,22 +240,29 @@ export function WallpaperSection() {
)}
<div className="flex items-center gap-3">
<span className="shrink-0 text-12 text-[var(--settings-section-sublabel)]">
- {t('settings.appearance.wallpaper.overlayLabel')}
+ {t('settings.appearance.wallpaper.visibilityLabel')}
</span>
<Slider
- min={APPEARANCE_LIMITS.wallpaperOverlay.min}
- max={APPEARANCE_LIMITS.wallpaperOverlay.max}
- step={APPEARANCE_LIMITS.wallpaperOverlay.step}
- value={[wallpaperOverlay]}
+ min={APPEARANCE_LIMITS.wallpaperVisibility.min}
+ max={APPEARANCE_LIMITS.wallpaperVisibility.max}
+ step={APPEARANCE_LIMITS.wallpaperVisibility.step}
+ value={[visibility]}
onValueChange={([value]) => {
- if (typeof value === 'number') setOverlay(value);
+ if (typeof value === 'number') setVisibility(value);
}}
- aria-label={t('settings.appearance.wallpaper.overlayAria')}
+ aria-label={t('settings.appearance.wallpaper.visibilityLabel')}
+ aria-describedby="wallpaper-visibility-hint"
/>
<span className="w-10 shrink-0 text-right font-mono text-12 text-[var(--settings-section-sublabel)]">
- {Math.round(wallpaperOverlay * 100)}%
+ {Math.round(visibility * 100)}%
</span>
</div>
+ <p
+ id="wallpaper-visibility-hint"
+ className="text-12 text-[var(--settings-section-sublabel)]"
+ >
+ {t('settings.appearance.wallpaper.visibilityHint')}
+ </p>
</div>
</div>
);
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/AppearanceSection.accessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/AppearanceSection.accessibility.test.tsx
index e9add62349..0b2cfa9160 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/AppearanceSection.accessibility.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/AppearanceSection.accessibility.test.tsx
@@ -45,7 +45,8 @@ vi.mock('@/hooks/useWallpaperSettings', () => ({
wallpaperOverlay: 0,
wallpaperMotion: 'static',
setWallpaper: vi.fn(),
- setOverlay: vi.fn(),
+ visibility: 0.37,
+ setVisibility: vi.fn(),
setMotion: vi.fn(),
resetWallpaper: vi.fn(),
}),
@@ -90,6 +91,14 @@ vi.mock('../LayoutResetControl', () => ({ LayoutResetControl: () => null }));
describe('AppearanceSection accessibility', () => {
it('labels the UI and code font-size number inputs', () => {
render(<AppearanceSection />);
+ const visibility = screen.getByRole('slider', {
+ name: 'settings.appearance.wallpaper.visibilityLabel',
+ });
+ expect(visibility.getAttribute('min')).toBe('0');
+ expect(visibility.getAttribute('max')).toBe('1');
+ expect(visibility.getAttribute('step')).toBe('0.01');
+ expect(visibility.getAttribute('aria-describedby')).toBe('wallpaper-visibility-hint');
+ expect(screen.getByText('37%')).toBeTruthy();
const wallpapers = within(
screen.getByRole('radiogroup', { name: 'settings.appearance.wallpaper.aria' }),
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
index d9c96c1c91..65b1f3836f 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
+++ b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
@@ -12,6 +12,9 @@ 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.setVisibility(1)}>Show Fully</button>
+ <button onClick={() => settings.setVisibility(0)}>Hide</button>
+ <span data-testid="visibility">{settings.visibility}</span>
<span data-testid="motion">{settings.wallpaperMotion}</span>
</>
);
@@ -31,14 +34,70 @@ afterEach(() => {
});
describe('application wallpaper lifecycle', () => {
+ it('updates literal visibility and restores the previous value when saving fails', async () => {
+ const setPatch = vi.fn().mockRejectedValue(new Error('save failed'));
+ vi.stubGlobal('electronAPI', {
+ appearanceSettings: {
+ getSync: () => ({ ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'cindy-window' }),
+ onChanged: () => () => {},
+ setPatch,
+ },
+ });
+ render(
+ <WallpaperSettingsProvider>
+ <Controls />
+ </WallpaperSettingsProvider>,
+ );
+ expect(screen.getByTestId('visibility').textContent).toBe('0.37');
+ fireEvent.click(screen.getByText('Show Fully'));
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-veil')).toBe('0%');
+ await waitFor(() => expect(setPatch).toHaveBeenCalledWith({ wallpaperVisibility: 1 }));
+ await waitFor(() => expect(screen.getByTestId('visibility').textContent).toBe('0.37'));
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-veil')).toBe('63%');
+ });
+ it.each([false, true])(
+ 'hides custom video at zero visibility and fully reveals it at 100% (dark=%s)',
+ (dark) => {
+ document.documentElement.classList.toggle('dark', dark);
+ let changed: (value: typeof DEFAULT_APPEARANCE_SETTINGS) => void = () => {};
+ const settings = {
+ ...DEFAULT_APPEARANCE_SETTINGS,
+ wallpaperId: 'custom' as const,
+ wallpaperMotion: 'dynamic' as const,
+ customWallpaperUrl: `cindy-media://client-wallpaper/${'a'.repeat(64)}.mp4`,
+ };
+ vi.stubGlobal('electronAPI', {
+ appearanceSettings: {
+ getSync: () => settings,
+ onChanged: (fn: typeof changed) => {
+ changed = fn;
+ return () => {};
+ },
+ },
+ });
+ render(
+ <WallpaperSettingsProvider>
+ <Controls />
+ </WallpaperSettingsProvider>,
+ );
+ const video = document.querySelector('video')!;
+ expect(video).not.toBeNull();
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-image')).toBe('none');
+ act(() => changed({ ...settings, wallpaperVisibility: 0 }));
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-veil')).toBe('100%');
+ expect(document.querySelector('video')).toBeNull();
+ expect(video.getAttribute('src')).toBeNull();
+ act(() => changed({ ...settings, wallpaperVisibility: 1 }));
+ expect(document.querySelector('video')).not.toBeNull();
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-veil')).toBe('0%');
+ },
+ );
it('loads client artwork without subscribing to account changes', async () => {
const url = `cindy-media://client-wallpaper/${'b'.repeat(64)}.webp`;
const subscribeAuth = vi.fn();
- const get = vi
- .fn()
- .mockResolvedValue({
- value: { ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'custom', customWallpaperUrl: url },
- });
+ const get = vi.fn().mockResolvedValue({
+ value: { ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'custom', customWallpaperUrl: url },
+ });
vi.stubGlobal('electronAPI', {
onAuthStateChange: subscribeAuth,
appearanceSettings: {
@@ -216,7 +275,11 @@ describe('application wallpaper lifecycle', () => {
expect(screen.getByTestId('motion').textContent).toBe('static');
await waitFor(() =>
expect(setPatch).toHaveBeenLastCalledWith(
- expect.objectContaining({ wallpaperMotion: 'static', wallpaperId: 'none' }),
+ expect.objectContaining({
+ wallpaperMotion: 'static',
+ wallpaperId: 'none',
+ wallpaperVisibility: null,
+ }),
),
);
});
diff --git a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
index c9914df12c..e65be9ff00 100644
--- a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
+++ b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
@@ -12,12 +12,14 @@ import {
import {
DEFAULT_APPEARANCE_SETTINGS,
- clampAppearanceWallpaperOverlay,
+ clampAppearanceWallpaperVisibility,
normalizeAppearanceSettings,
type AppearanceSettings,
type WallpaperId,
type WallpaperMotion,
normalizeCustomWallpaperUrl,
+ isCustomWallpaperVideo,
+ getWallpaperVisibility,
} from '@/../shared/appearanceSettings';
import { getBuiltinWallpaperBackground } from '@/lib/wallpaper';
@@ -27,13 +29,16 @@ import { WallpaperVideo } from '@/components/layout/WallpaperVideo';
export interface WallpaperSettings {
wallpaperId: WallpaperId;
wallpaperOverlay: number;
+ wallpaperVisibility?: number | null;
wallpaperMotion: WallpaperMotion;
customWallpaperUrl?: string;
}
interface WallpaperSettingsContextValue extends WallpaperSettings {
+ playbackFailed: boolean;
+ visibility: number;
setWallpaper: (id: WallpaperId) => void;
- setOverlay: (value: number) => void;
+ setVisibility: (value: number) => void;
setMotion: (value: WallpaperMotion) => void;
resetWallpaper: () => void;
}
@@ -57,6 +62,7 @@ function pickWallpaperSettings(settings: AppearanceSettings): WallpaperSettings
return {
wallpaperId: settings.wallpaperId,
wallpaperOverlay: settings.wallpaperOverlay,
+ wallpaperVisibility: settings.wallpaperVisibility,
wallpaperMotion: settings.wallpaperMotion,
customWallpaperUrl: settings.customWallpaperUrl,
};
@@ -64,7 +70,14 @@ function pickWallpaperSettings(settings: AppearanceSettings): WallpaperSettings
export function WallpaperSettingsProvider({ children }: { children: ReactNode }) {
const [settings, setSettings] = useState<WallpaperSettings>(getInitialWallpaperSettings);
+ const [failedUrl, setFailedUrl] = useState('');
+ const onPlaybackFailure = useCallback(
+ () => setFailedUrl(settings.customWallpaperUrl ?? ''),
+ [settings.customWallpaperUrl],
+ );
+ const onPlaybackReady = useCallback(() => setFailedUrl(''), []);
const isDark = useIsDarkMode();
+ const visibility = getWallpaperVisibility(settings, isDark);
// 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(() => {
@@ -73,7 +86,9 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
const background =
settings.wallpaperId === 'custom'
? customUrl
- ? `url("${customUrl}")`
+ ? isCustomWallpaperVideo(customUrl)
+ ? 'none'
+ : `url("${customUrl}")`
: undefined
: getBuiltinWallpaperBackground(settings.wallpaperId);
const active = Boolean(background);
@@ -81,7 +96,7 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
root.dataset.wallpaperActive = 'true';
root.style.setProperty('--app-wallpaper-image', background!);
// One cover-fitted canvas; theme-derived veil keeps messages readable.
- const veil = (isDark ? 65 : 55) + settings.wallpaperOverlay * 40;
+ const veil = 100 - visibility * 100;
root.style.setProperty('--app-wallpaper-veil', `${veil}%`);
}
return () => {
@@ -89,7 +104,7 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
for (const name of ['--app-wallpaper-image', '--app-wallpaper-veil'])
root.style.removeProperty(name);
};
- }, [settings, isDark]);
+ }, [settings, visibility]);
const settingsRef = useRef(settings);
const confirmedRef = useRef(settings);
const pendingRef = useRef<Array<{ id: number; patch: Partial<WallpaperSettings> }>>([]);
@@ -167,8 +182,8 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
}, []);
const setWallpaper = useCallback((wallpaperId: WallpaperId) => patch({ wallpaperId }), [patch]);
- const setOverlay = useCallback(
- (value: number) => patch({ wallpaperOverlay: clampAppearanceWallpaperOverlay(value) }),
+ const setVisibility = useCallback(
+ (value: number) => patch({ wallpaperVisibility: clampAppearanceWallpaperVisibility(value) }),
[patch],
);
const setMotion = useCallback(
@@ -180,19 +195,36 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
patch({
wallpaperId: DEFAULT_APPEARANCE_SETTINGS.wallpaperId,
wallpaperOverlay: DEFAULT_APPEARANCE_SETTINGS.wallpaperOverlay,
+ wallpaperVisibility: null,
wallpaperMotion: DEFAULT_APPEARANCE_SETTINGS.wallpaperMotion,
}),
[patch],
);
const value = useMemo<WallpaperSettingsContextValue>(
- () => ({ ...settings, setWallpaper, setOverlay, setMotion, resetWallpaper }),
- [resetWallpaper, setMotion, setOverlay, setWallpaper, settings],
+ () => ({
+ ...settings,
+ visibility,
+ playbackFailed: !!failedUrl && failedUrl === settings.customWallpaperUrl,
+ setWallpaper,
+ setVisibility,
+ setMotion,
+ resetWallpaper,
+ }),
+ [resetWallpaper, setMotion, setVisibility, setWallpaper, settings, failedUrl, visibility],
);
return (
<WallpaperSettingsContext.Provider value={value}>
- <WallpaperVideo wallpaperId={settings.wallpaperId} motion={settings.wallpaperMotion} />
+ {visibility > 0 && (
+ <WallpaperVideo
+ wallpaperId={settings.wallpaperId}
+ motion={settings.wallpaperMotion}
+ customWallpaperUrl={settings.customWallpaperUrl}
+ onFailure={onPlaybackFailure}
+ onReady={onPlaybackReady}
+ />
+ )}
{children}
</WallpaperSettingsContext.Provider>
);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f463e22a2f..c1117ceaa8 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -905,7 +905,7 @@
},
"wallpaper": {
"title": "Wallpaper",
- "description": "Choose a Cindy scene or your own image for the whole app, independently of the theme.",
+ "description": "Choose a Cindy scene, image or video for the whole app, independently of the theme.",
"reset": "Reset",
"aria": "Wallpaper selection",
"nonePreview": "None",
@@ -916,18 +916,19 @@
"cindy-dream": "Cindy · Dream Voyage",
"custom": "Custom wallpaper"
},
- "overlayLabel": "Overlay",
- "overlayAria": "Wallpaper overlay strength",
+ "visibilityLabel": "Wallpaper Visibility",
+ "visibilityHint": "0% hides the wallpaper; 100% shows it without an overlay.",
"motionLabel": "Display",
"motionHint": "Still by default. Motion pauses when hidden and follows your reduced-motion preference.",
"motionStatic": "Static",
"motionDynamic": "Dynamic",
- "customChoose": "Choose image",
- "customReplace": "Replace image",
- "customRemove": "Remove image",
+ "customChoose": "Choose Wallpaper",
+ "customReplace": "Replace Wallpaper",
+ "customRemove": "Remove Wallpaper",
"customBusy": "Working…",
- "customHint": "PNG, JPEG or WebP, up to 20 MB. Stored on this device, displayed as a still image.",
- "customInvalid": "Choose a valid PNG, JPEG or WebP image (up to 20 MB and 40 megapixels).",
+ "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."
},
"layout": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 31d1577a89..1c1300009a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -905,7 +905,7 @@
},
"wallpaper": {
"title": "壁紙",
- "description": "アプリ全体に Cindy の壁紙や自分の画像を設定できます。テーマは独立して選べます。",
+ "description": "アプリ全体に Cindy の壁紙や自分の画像・動画を設定できます。テーマは独立して選べます。",
"reset": "デフォルトに戻す",
"aria": "壁紙の選択",
"nonePreview": "なし",
@@ -916,18 +916,19 @@
"cindy-dream": "Cindy · 夢の旅",
"custom": "カスタム壁紙"
},
- "overlayLabel": "オーバーレイ",
- "overlayAria": "壁紙オーバーレイの強さ",
+ "visibilityLabel": "壁紙の表示濃度",
+ "visibilityHint": "0% で壁紙を非表示にし、100% でそのまま表示します。",
"motionLabel": "表示方法",
"motionHint": "初期設定は静止画です。非表示時は停止し、システムの視差効果を減らす設定に従います。",
"motionStatic": "静止画",
"motionDynamic": "動画",
- "customChoose": "画像を選択",
- "customReplace": "画像を変更",
- "customRemove": "画像を削除",
+ "customChoose": "壁紙を選択",
+ "customReplace": "壁紙を変更",
+ "customRemove": "壁紙を削除",
"customBusy": "処理中…",
- "customHint": "PNG・JPEG・WebP、最大 20 MB。この端末にのみ保存し、静止画として表示します。",
- "customInvalid": "有効な PNG・JPEG・WebP 画像を選択してください(最大 20 MB・4000 万画素)。",
+ "customPlaybackFailed": "この動画を再生できません。H.264 でエンコードされた MP4 動画を選択してください。",
+ "customHint": "PNG・JPEG・WebP 画像は最大 20 MB、MP4 動画は最大 100 MB。この端末にのみ保存します。動画モードでは無音で繰り返し再生します。",
+ "customInvalid": "有効な PNG・JPEG・WebP 画像(最大 20 MB・4000 万画素)、または最大 100 MB の MP4 動画を選択してください。",
"customFailed": "壁紙を保存できませんでした。もう一度お試しください。"
},
"layout": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 6134a8ec92..3dcf19d89f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -905,7 +905,7 @@
},
"wallpaper": {
"title": "배경화면",
- "description": "앱 전체에 Cindy 배경이나 내 이미지를 적용하세요. 테마는 별도로 선택할 수 있습니다.",
+ "description": "앱 전체에 Cindy 배경이나 내 이미지 또는 동영상을 적용하세요. 테마는 별도로 선택할 수 있습니다.",
"reset": "기본값으로 복원",
"aria": "배경화면 선택",
"nonePreview": "없음",
@@ -916,18 +916,19 @@
"cindy-dream": "Cindy · 꿈속 여행",
"custom": "사용자 지정 배경화면"
},
- "overlayLabel": "오버레이",
- "overlayAria": "배경화면 오버레이 강도",
+ "visibilityLabel": "배경화면 표시 강도",
+ "visibilityHint": "0%에서는 배경화면을 숨기고, 100%에서는 원본 그대로 표시합니다.",
"motionLabel": "표시 방식",
"motionHint": "기본값은 정적입니다. 창이 숨겨지면 일시 정지하며 시스템의 동작 줄이기 설정을 따릅니다.",
"motionStatic": "정적",
"motionDynamic": "동적",
- "customChoose": "이미지 선택",
- "customReplace": "이미지 교체",
- "customRemove": "이미지 제거",
+ "customChoose": "배경화면 선택",
+ "customReplace": "배경화면 교체",
+ "customRemove": "배경화면 제거",
"customBusy": "처리 중…",
- "customHint": "PNG, JPEG, WebP, 최대 20 MB. 이 기기에만 저장되며 정지 이미지로 표시됩니다.",
- "customInvalid": "올바른 PNG, JPEG 또는 WebP 이미지를 선택하세요(최대 20 MB, 4천만 화소).",
+ "customPlaybackFailed": "이 동영상을 재생할 수 없습니다. H.264로 인코딩된 MP4 동영상을 선택하세요.",
+ "customHint": "PNG, JPEG, WebP 이미지는 최대 20 MB, MP4 동영상은 최대 100 MB. 이 기기에만 저장됩니다. 동적 모드에서는 소리 없이 반복 재생됩니다.",
+ "customInvalid": "올바른 PNG, JPEG 또는 WebP 이미지(최대 20 MB, 4천만 화소)나 최대 100 MB의 MP4 동영상을 선택하세요.",
"customFailed": "배경화면을 저장하지 못했습니다. 다시 시도하세요."
},
"layout": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 55a1c2dca9..42a1f5b2c7 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -905,7 +905,7 @@
},
"wallpaper": {
"title": "壁纸",
- "description": "为整个应用选择 Cindy 场景或自己的图片,主题保持独立。",
+ "description": "为整个应用选择 Cindy 场景、自己的图片或视频,主题保持独立。",
"reset": "恢复默认",
"aria": "壁纸选择",
"nonePreview": "无",
@@ -916,18 +916,19 @@
"cindy-dream": "Cindy · 梦境漫游",
"custom": "自定义壁纸"
},
- "overlayLabel": "遮罩",
- "overlayAria": "壁纸遮罩强度",
+ "visibilityLabel": "壁纸可见度",
+ "visibilityHint": "0% 隐藏壁纸,100% 完全显示壁纸。",
"motionLabel": "展示方式",
"motionHint": "默认静态;动态在窗口隐藏时暂停,并遵循系统减少动效设置。",
"motionStatic": "静态",
"motionDynamic": "动态",
- "customChoose": "选择图片",
- "customReplace": "替换图片",
- "customRemove": "移除图片",
+ "customChoose": "选择壁纸",
+ "customReplace": "替换壁纸",
+ "customRemove": "移除壁纸",
"customBusy": "处理中…",
- "customHint": "PNG、JPEG、WebP,最大 20 MB。仅保存在此设备,静态展示。",
- "customInvalid": "请选择有效的 PNG、JPEG 或 WebP 图片(不超过 20 MB、4000 万像素)。",
+ "customPlaybackFailed": "无法播放此视频,请选择使用 H.264 编码的 MP4 视频。",
+ "customHint": "PNG、JPEG、WebP 图片最大 20 MB,MP4 视频最大 100 MB。仅保存在此设备,视频在动态模式下静音循环播放。",
+ "customInvalid": "请选择有效的 PNG、JPEG 或 WebP 图片(不超过 20 MB、4000 万像素),或不超过 100 MB 的 MP4 视频。",
"customFailed": "未能保存壁纸,请重试。"
},
"layout": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index dcbd120163..c9e698d9bf 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -905,7 +905,7 @@
},
"wallpaper": {
"title": "桌布",
- "description": "為整個應用程式選擇 Cindy 場景或自己的圖片,主題保持獨立。",
+ "description": "為整個應用程式選擇 Cindy 場景、自己的圖片或影片,主題保持獨立。",
"reset": "恢復預設",
"aria": "桌布選擇",
"nonePreview": "無",
@@ -916,18 +916,19 @@
"cindy-dream": "Cindy · 夢境漫遊",
"custom": "自訂桌布"
},
- "overlayLabel": "遮罩",
- "overlayAria": "桌布遮罩強度",
+ "visibilityLabel": "桌布可見度",
+ "visibilityHint": "0% 隱藏桌布,100% 完全顯示桌布。",
"motionLabel": "展示方式",
"motionHint": "預設靜態;動態在視窗隱藏時暫停,並遵循系統減少動態效果設定。",
"motionStatic": "靜態",
"motionDynamic": "動態",
- "customChoose": "選擇圖片",
- "customReplace": "替換圖片",
- "customRemove": "移除圖片",
+ "customChoose": "選擇桌布",
+ "customReplace": "替換桌布",
+ "customRemove": "移除桌布",
"customBusy": "處理中…",
- "customHint": "PNG、JPEG、WebP,最大 20 MB。僅儲存在此裝置,靜態顯示。",
- "customInvalid": "請選擇有效的 PNG、JPEG 或 WebP 圖片(不超過 20 MB、4000 萬像素)。",
+ "customPlaybackFailed": "無法播放此影片,請選擇使用 H.264 編碼的 MP4 影片。",
+ "customHint": "PNG、JPEG、WebP 圖片最大 20 MB,MP4 影片最大 100 MB。僅儲存在此裝置,影片在動態模式下靜音循環播放。",
+ "customInvalid": "請選擇有效的 PNG、JPEG 或 WebP 圖片(不超過 20 MB、4000 萬像素),或不超過 100 MB 的 MP4 影片。",
"customFailed": "無法儲存桌布,請重試。"
},
"layout": {
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 89d031db8f..d38442706d 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -2397,25 +2397,23 @@ html[data-wallpaper-active='true'] .wallpaper-composer-fade {
mask-image: linear-gradient(transparent, currentColor);
}
-/* Opt-in scene motion shares one decoder behind every pane. Its veil matches
- the still canvas exactly; no animated paint properties or per-frame JS. */
+/* Blend video into an opaque theme surface before composing with the UI.
+ A separate translucent veil over a hardware video overlay changes brightness
+ when P3 content switches Windows HDR output to scRGB. Keep visibility on the
+ video itself; the wrapper opacity is reserved for loading/exit crossfades. */
.app-wallpaper-video {
position: fixed;
inset: 0;
z-index: -1;
pointer-events: none;
+ background: var(--surface);
transition: opacity var(--motion-base) var(--motion-ease-move);
}
.app-wallpaper-video video {
width: 100%;
height: 100%;
object-fit: cover;
-}
-.app-wallpaper-video::after {
- content: '';
- position: absolute;
- inset: 0;
- background: color-mix(in srgb, var(--surface) var(--app-wallpaper-veil), transparent);
+ opacity: calc(100% - var(--app-wallpaper-veil));
}
/* Fade the message layer itself, so the moving scene remains continuous behind
the composer. Repainting a static copy there would create a visible seam. */
diff --git a/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts b/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts
index 950afbd2f7..08994481c8 100644
--- a/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts
+++ b/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts
@@ -1,7 +1,64 @@
import { describe, expect, it } from 'vitest';
-import { normalizeAppearanceSettings } from '../appearanceSettings';
+import {
+ normalizeAppearanceSettings,
+ getWallpaperVeil,
+ clampAppearanceWallpaperOverlay,
+ getWallpaperVisibility,
+} from '../appearanceSettings';
describe('wallpaper catalog compatibility', () => {
+ it.each([false, true])(
+ 'preserves legacy visuals but gives explicit visibility the full range (dark=%s)',
+ (dark) => {
+ for (const wallpaperOverlay of [0, 0.2, 0.6, 0.85, 1]) {
+ const legacy = normalizeAppearanceSettings({ wallpaperOverlay });
+ expect(legacy).not.toHaveProperty('wallpaperVisibility');
+ expect(getWallpaperVisibility(legacy, dark) * 100).toBeCloseTo(
+ 100 - getWallpaperVeil(wallpaperOverlay, dark),
+ );
+ for (const visibility of [0, 0.37, 1]) {
+ const explicit = normalizeAppearanceSettings({
+ ...legacy,
+ wallpaperVisibility: visibility,
+ });
+ expect(getWallpaperVisibility(explicit, dark)).toBe(visibility);
+ }
+ }
+ expect(getWallpaperVisibility(normalizeAppearanceSettings({}), dark)).toBe(
+ dark ? 0.27 : 0.37,
+ );
+ expect(normalizeAppearanceSettings({ wallpaperVisibility: null })).not.toHaveProperty(
+ 'wallpaperVisibility',
+ );
+ },
+ );
+ it('accepts a managed custom MP4 and rejects video URLs outside the wallpaper scope', () => {
+ const url = `cindy-media://client-wallpaper/${'a'.repeat(64)}.mp4`;
+ expect(normalizeAppearanceSettings({ customWallpaperUrl: url }).customWallpaperUrl).toBe(url);
+ for (const invalid of [
+ url + '?x=1',
+ url.replace('client-wallpaper', 'blobs'),
+ 'file:///a.mp4',
+ ]) {
+ expect(normalizeAppearanceSettings({ customWallpaperUrl: invalid }).customWallpaperUrl).toBe(
+ '',
+ );
+ }
+ });
+ it.each([false, true])(
+ 'preserves old veil strengths and extends monotonically to opaque (dark=%s)',
+ (dark) => {
+ const base = dark ? 65 : 55;
+ for (let i = 0; i <= 12; i++)
+ expect(getWallpaperVeil(i * 0.05, dark)).toBeCloseTo(base + i * 2);
+ expect(getWallpaperVeil(1, dark)).toBe(100);
+ expect(getWallpaperVeil(0.8, dark)).toBeGreaterThan(getWallpaperVeil(0.6, dark));
+ expect(clampAppearanceWallpaperOverlay(2)).toBe(1);
+ expect(clampAppearanceWallpaperOverlay(-1)).toBe(0);
+ expect(clampAppearanceWallpaperOverlay(NaN)).toBe(0.2);
+ expect(normalizeAppearanceSettings({ wallpaperOverlay: 1 }).wallpaperOverlay).toBe(1);
+ },
+ );
it('accepts only canonical host-owned custom artwork and never legacy paths or CSS', () => {
const url = `cindy-media://client-wallpaper/${'a'.repeat(64)}.webp`;
expect(
diff --git a/apps/desktop/src/shared/appearanceSettings.ts b/apps/desktop/src/shared/appearanceSettings.ts
index 60c016bd39..61f2ec34ef 100644
--- a/apps/desktop/src/shared/appearanceSettings.ts
+++ b/apps/desktop/src/shared/appearanceSettings.ts
@@ -15,6 +15,8 @@ export interface AppearanceOverrides {
windowZoom?: number;
wallpaperId?: WallpaperId;
wallpaperOverlay?: number;
+ /** null removes the explicit visibility override. */
+ wallpaperVisibility?: number | null;
wallpaperMotion?: WallpaperMotion;
}
@@ -28,6 +30,8 @@ export interface AppearanceSettings {
windowZoom: number;
wallpaperId: WallpaperId;
wallpaperOverlay: number;
+ /** Absent for legacy/default preferences; derive visibility from the theme's old veil. */
+ wallpaperVisibility?: number | null;
wallpaperMotion: WallpaperMotion;
/** Read-only, host-owned media reference; never accepted by set-patch. */
customWallpaperUrl?: string;
@@ -49,7 +53,8 @@ export const APPEARANCE_LIMITS = {
uiSize: { min: 12, max: 24 },
codeSize: { min: 10, max: 24 },
windowZoom: { min: 0.5, max: 3, step: 0.1 },
- wallpaperOverlay: { min: 0, max: 0.6, step: 0.05 },
+ wallpaperOverlay: { min: 0, max: 1, step: 0.05 },
+ wallpaperVisibility: { min: 0, max: 1, step: 0.01 },
} as const;
export const WALLPAPER_IDS = [
@@ -62,11 +67,40 @@ export const WALLPAPER_IDS = [
export type WallpaperId = (typeof WALLPAPER_IDS)[number];
export function normalizeCustomWallpaperUrl(value: unknown): string {
- return typeof value === 'string' && /^cindy-media:\/\/client-wallpaper\/[0-9a-f]{64}\.webp$/.test(value)
+ return typeof value === 'string' &&
+ /^cindy-media:\/\/client-wallpaper\/[0-9a-f]{64}\.(webp|mp4)$/.test(value)
? value
: '';
}
+export function isCustomWallpaperVideo(value: unknown): boolean {
+ return normalizeCustomWallpaperUrl(value).endsWith('.mp4');
+}
+
+/** Keep existing 0–60% preferences visually unchanged; extend to a fully opaque veil. */
+export function getWallpaperVeil(overlay: number, isDark: boolean): number {
+ const strength = clampAppearanceWallpaperOverlay(overlay);
+ const base = isDark ? 65 : 55;
+ if (strength <= 0.6) return base + strength * 40;
+ const previousMax = base + 24;
+ return previousMax + ((strength - 0.6) / 0.4) * (100 - previousMax);
+}
+
+export function clampAppearanceWallpaperVisibility(value: number): number {
+ return Number.isFinite(value) ? roundDecimal(Math.min(1, Math.max(0, value)), 2) : 0;
+}
+
+/** Old settings retain their exact Light/Dark appearance until explicitly adjusted. */
+export function getWallpaperVisibility(
+ settings: Pick<AppearanceSettings, 'wallpaperOverlay' | 'wallpaperVisibility'>,
+ isDark: boolean,
+): number {
+ return typeof settings.wallpaperVisibility === 'number' &&
+ Number.isFinite(settings.wallpaperVisibility)
+ ? clampAppearanceWallpaperVisibility(settings.wallpaperVisibility)
+ : (100 - getWallpaperVeil(settings.wallpaperOverlay, isDark)) / 100;
+}
+
export function clampAppearanceWallpaperOverlay(
value: number,
fallback = DEFAULT_APPEARANCE_SETTINGS.wallpaperOverlay,
@@ -142,6 +176,9 @@ export function normalizeAppearanceSettings(raw: unknown): AppearanceSettings {
? clampAppearanceWallpaperOverlay(value.wallpaperOverlay)
: DEFAULT_APPEARANCE_SETTINGS.wallpaperOverlay,
wallpaperMotion: value.wallpaperMotion === 'dynamic' ? 'dynamic' : 'static',
+ ...(typeof value.wallpaperVisibility === 'number' && Number.isFinite(value.wallpaperVisibility)
+ ? { wallpaperVisibility: clampAppearanceWallpaperVisibility(value.wallpaperVisibility) }
+ : {}),
customWallpaperUrl: normalizeCustomWallpaperUrl(value.customWallpaperUrl),
};
}
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 69f1af4cdf..1f6ec38cc9 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -69,7 +69,7 @@ the whole host application: title bar, navigation, messages, tool-pane chrome,
settings and other host pages share continuous viewport-aligned artwork. This
opt-in setting supersedes the CINDY sidebar-only backdrop treatment while active;
disabling it restores the original theme without modifying theme files or tokens.
-Use a theme-surface veil, never a fixed black overlay in Light mode. Image opacity
+Blend wallpaper with the theme surface, never a fixed black overlay in Light mode. Image opacity
must not affect text or icons. Elevated controls, menus, dialogs and embedded web
or editor content keep their readable surfaces. Composer scroll masking must
align with the same wallpaper instead of introducing an opaque footer rectangle.
@@ -78,10 +78,11 @@ Verify actual Light/Dark screenshots across host pages and the expanded tool pan
The built-in wallpaper catalog contains only Window Companion, Future Atelier and Dream
Wander, plus None to restore the theme canvas (user decision, 2026-10-01).
-Custom wallpaper is available through Choose image, Replace image and Remove image
-in the same section (user addition, 2026-10-01). Accept local PNG/JPEG/WebP up to
+Custom wallpaper is available through Choose Wallpaper, Replace Wallpaper and Remove Wallpaper
+in the same section (user addition, 2026-10-01; video support, 2026-10-05). Accept local PNG/JPEG/WebP up to
20 MB and 40 megapixels, store a metadata-free static image up to 3840 pixels
-in the managed media store. Wallpaper selection and the custom image reference
+in the managed media store. Also accept local MP4 videos up to 100 MB, preserving their bytes;
+H.264 is recommended for playback compatibility. Wallpaper selection and the custom media reference
are shared within the Desktop profile, just like theme preferences (user decision,
2026-10-02). Import, replacement, removal and recycling are client-wide as well:
no account database, account-bound operation guard or pre-release owner migration.
@@ -90,9 +91,25 @@ switching accounts (or signing out) keeps the same wallpaper. Font-only utility
custom media URLs.
Detached sidebar and plugin-panel host chrome use the same wallpaper provider;
embedded plugin webviews retain their own surfaces and permission boundary.
-Cancellation and import failures retain the existing image. Switching to a built-in
-or None keeps the imported image available; Remove image forgets it. Custom imagery
-shares the continuous cover-fit canvas and readability veil; no dynamic toggle.
+Cancellation and import failures retain the existing media. Switching to a built-in
+or None keeps the imported media available; Remove Wallpaper forgets it. Custom imagery
+shares the continuous cover-fit canvas and readability veil. Custom MP4 exposes the existing
+Static / Dynamic choice: Static and reduced motion show a paused frame; Dynamic loops silently
+and pauses when hidden/minimized. Playback failure releases the decoder, leaves the theme surface
+visible and shows an actionable error in wallpaper settings. The custom video tile uses a film icon
+instead of opening a second decoder for a thumbnail.
+Wallpaper Visibility ranges from 0% (hidden) to 100% (fully visible), in 1% steps
+(user decision, 2026-10-05). Static images use the theme-surface veil with opacity equal to
+100% minus visibility. Video uses visibility directly as the video element's opacity over
+an opaque theme-surface backing, without a separate translucent veil; this avoids the
+observed Windows HDR brightness shift when P3 content changes the output composition.
+The video wrapper's opacity is reserved for loading/exit crossfades. Never reduce text
+or control opacity. Release video playback at 0%. Blur and blend-mode controls are out of scope.
+Existing preferences without an explicit visibility override keep the previous Light/Dark veil
+mapping and display its equivalent visibility. The unchanged soft default is 37% visible in
+Light and 27% in Dark. Adjusting the slider saves literal visibility, shared across themes;
+Reset removes that override and restores the theme-dependent default. Do not rewrite old
+preferences just because they were read or a theme changed.
Remove the previous arrow, standalone portrait, gradient and paper
options and assets. Retired saved selections normalize to None; unrelated theme
and font preferences remain unchanged. All three scenes use the same cover fit,
diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.md
index 54048c854a..27c1abe5e7 100644
--- a/docs/dev-rules/media-storage-and-protocols.md
+++ b/docs/dev-rules/media-storage-and-protocols.md
@@ -39,12 +39,18 @@
数据表或协议,也不在调用方重复实现“写 blob、记账、挂引用”。
- 客户端共用壁纸使用统一媒体仓的 `ingestClientWallpaper` 入口与
`client-wallpaper` 字节作用域(2026-10-02 用户裁决),复用 blobStore 的指纹、
- 原子发布和安全校验,不挂账号数据库引用。引用真相为客户端自定义图片设置或
+ 原子发布和安全校验,不挂账号数据库引用。引用真相为客户端自定义图片/MP4 视频设置或
官方视频清单;发布与回收共用客户端操作锁,原生选图和下载不占锁。先成功保存引用,
- 再由 recycler 回收该作用域中不再引用的文件,失败留到下次成功操作重试。
+ 再由 recycler 回收该作用域中不再引用的文件。保存失败时在同一操作锁内重新读取磁盘引用,
+ 尽力回收未引用媒体;引用不可读或回收失败则保留文件,留到后续成功操作重试。
这是统一仓内的生命周期隔离,不另建缓存引擎、数据库或协议;即使字节内容相同,
也不与账号附件跨作用域去重,删除壁纸不会删除聊天引用的副本,反向清理亦然。
本 PR 尚未发布,不迁移中间版本的账号设置或引用。
+ 自定义 MP4 与官方可选 CDN 视频共用 `.mp4` 作用域;两条回收入口都必须合并保留
+ 自定义引用与当前 CDN 清单引用,避免互删。导入只接受原生文件选择器返回的路径,
+ 主机按真实字节识别 MP4,视频上限 100 MB;图片继续走原有解码与 20 MB 限制。
+ 完整读取前,从同一安全文件句柄探测最多 4 KiB,已识别图片提前应用 20 MB 上限;
+ 未知头部保留原有 100 MB 外层上限,随后完整识别与解码,避免误拒头部较大的合法视频。
- 标准顺序是:主机核验媒体类型 → 按字节计算 SHA-256 并原子落盘 → 记录 blob → 挂业务
引用。外部、插件或远端自报的指纹、扩展名和 Content-Type 不能单独作为可信依据。
- 持久附件或作品必须使用符合业务生命周期的引用。业务删除时只删除自己名下的引用,
@@ -74,6 +80,9 @@
- 客户端壁纸地址为 `cindy-media://client-wallpaper/<sha256>.webp` 或 `.mp4`,
由既有协议 handler 的严格解析分支服务,不触发账号账本的访问时间更新。普通附件
与插件的 blob 解析器不接受该 UI 专用作用域;字体工具窗口不获得自定义图片地址。
+- 客户端壁纸 MP4 的播放请求从已校验的同一文件句柄按 Range 流式读取;无 Range 或开放区间
+ 也分块传输,不先把整份视频读入主进程。Node 与 Web 两侧队列均按字节设置缓冲上限,
+ 结束、错误、请求中止和消费者取消时关闭句柄;沿用既有 200 / 206 / 416 与缓存语义。
- `cindy-media://` 的 scheme privilege 和 handler 只在现有集中入口注册。不要为单一功能
新增媒体协议;确需改变协议能力时,同时按 Electron 安全规则审查 CSP、fetch、Range、
路径校验和 Renderer 暴露面。
diff --git a/docs/pr-assets/wallpaper-visibility/dark.png b/docs/pr-assets/wallpaper-visibility/dark.png
new file mode 100644
index 0000000000..3427fdadff
Binary files /dev/null and b/docs/pr-assets/wallpaper-visibility/dark.png differ
diff --git a/docs/pr-assets/wallpaper-visibility/light.png b/docs/pr-assets/wallpaper-visibility/light.png
new file mode 100644
index 0000000000..6a5013ca94
Binary files /dev/null and b/docs/pr-assets/wallpaper-visibility/light.png differ
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 01ca72b011..d58e4a953d 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -569,6 +569,10 @@ Cindy 里的**持久 AI 助手实体**(原名 Bot):有长期身份、自
Desktop appearance setting for an in-app visual background layer.
+### Wallpaper Visibility
+
+壁纸背景层的实际可见程度,0% 隐藏,100% 原样显示;不改变文字或控件的不透明度。
+
### WeChat
个人微信连接的产品名称,沿用微信官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 410dab3568..dc0276d225 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -8,6 +8,18 @@
{"id": "group-owner", "status": "proposed", "en": "Group Owner", "translations": {"zh-CN": "群主", "zh-TW": "群主", "ja": "グループオーナー", "ko": "그룹 소유자"}, "checkCase": false, "note": "Chat Server 的群角色,可由人或伙伴担任;不要与伙伴主人或分工负责人混同。群设置成员行英文可简写 Owner。"},
{"id": "group-admin", "status": "proposed", "en": "Group Admin", "translations": {"zh-CN": "群管理员", "zh-TW": "群管理員", "ja": "グループ管理者", "ko": "그룹 관리자"}, "checkCase": false, "note": "可管理群资料和成员,但不能替伙伴主人授权工具或私人资料。群设置内可简称管理员 / Admin。"},
{"id": "group-nickname", "status": "proposed", "en": "Group Nickname", "translations": {"zh-CN": "群昵称", "zh-TW": "群暱稱", "ja": "グループ内の名前", "ko": "그룹에서의 이름"}, "checkCase": false, "note": "仅在单个群中显示的名字。为空时使用账号显示名;不覆盖个人资料名字或稳定身份。"},
+ {
+ "id": "wallpaper-visibility",
+ "status": "proposed",
+ "en": "Wallpaper Visibility",
+ "translations": {
+ "zh-CN": "壁纸可见度",
+ "zh-TW": "桌布可見度",
+ "ja": "壁紙の表示濃度",
+ "ko": "배경화면 표시 강도"
+ },
+ "note": "壁纸背景层的实际可见程度,0% 隐藏,100% 原样显示;不改变文字或控件的不透明度。"
+ },
{
"id": "wallpaper",
"status": "proposed",