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): add custom wallpaper picker and managed image storage

DavidShenf21f7823cc67
diff --git a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
index 3721397022..e6f22bb8a0 100644
--- a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
+++ b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
@@ -12,10 +12,23 @@ const mocks = vi.hoisted(() => ({
writeAppearanceSettingsPatch: vi.fn(),
resetAppearanceSettings: vi.fn(),
updateAppearanceSettingsAtomic: vi.fn(),
+ owner: 'owner-a:1',
+ boundaryPending: false,
+ importWallpaper: vi.fn(),
+ removeWallpaper: vi.fn(),
+}));
+
+vi.mock('../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => mocks.owner,
+ isAppSessionBoundaryPending: () => mocks.boundaryPending,
+}));
+vi.mock('../custom-wallpaper.js', () => ({
+ importCustomWallpaper: mocks.importWallpaper,
+ removeCustomWallpaper: mocks.removeWallpaper,
}));
vi.mock('electron', () => ({
- BrowserWindow: { getAllWindows: () => mocks.allWindows },
+ BrowserWindow: { getAllWindows: () => mocks.allWindows, fromWebContents: () => ({}) },
ipcMain: { on: mocks.ipcOn, handle: mocks.ipcHandle },
}));
@@ -48,6 +61,47 @@ const persisted = {
};
describe('appearance settings IPC authorization', () => {
+ it.each(['appearance-settings:import-wallpaper', 'appearance-settings:remove-wallpaper'])(
+ 'rejects %s when the owner changes during module loading',
+ async (channel) => {
+ const handler = mocks.ipcHandle.mock.calls.find(([name]) => name === channel)?.[1];
+ const pending = handler({ sender: {} });
+ mocks.owner = 'owner-b:2';
+ await expect(pending).rejects.toThrow('Unable to');
+ expect(mocks.importWallpaper).not.toHaveBeenCalled();
+ expect(mocks.removeWallpaper).not.toHaveBeenCalled();
+ },
+ );
+ it.each(['appearance-settings:import-wallpaper', 'appearance-settings:remove-wallpaper'])(
+ 'rejects %s while the owner boundary is pending',
+ async (channel) => {
+ const handler = mocks.ipcHandle.mock.calls.find(([name]) => name === channel)?.[1];
+ const pending = handler({ sender: {} });
+ mocks.boundaryPending = true;
+ await expect(pending).rejects.toThrow('Unable to');
+ expect(mocks.importWallpaper).not.toHaveBeenCalled();
+ expect(mocks.removeWallpaper).not.toHaveBeenCalled();
+ },
+ );
+ it('does not let a renderer inject a path or media URL through the generic preference channel', () => {
+ expect(__testing.parsePatch({ wallpaperId: 'custom' })).toEqual({ wallpaperId: 'custom' });
+ expect(() =>
+ __testing.parsePatch({ customWallpaperUrl: `cindy-media://blobs/${'a'.repeat(64)}.webp` }),
+ ).toThrow('unknown appearance field');
+ expect(() => __testing.parsePatch({ wallpaperPath: '/private.png' })).toThrow(
+ 'unknown appearance field',
+ );
+ });
+ it.each(['appearance-settings:import-wallpaper', 'appearance-settings:remove-wallpaper'])(
+ 'rejects untrusted callers before %s can access a picker or media',
+ async (channel) => {
+ mocks.assertTrustedAppRendererEvent.mockImplementation(() => {
+ throw new Error('untrusted');
+ });
+ const handler = mocks.ipcHandle.mock.calls.find(([name]) => name === channel)?.[1];
+ await expect(handler({})).rejects.toThrow('untrusted');
+ },
+ );
it('validates motion choices and preserves the static default for old settings', () => {
expect(normalizeAppearanceSettings({ wallpaperId: 'cindy-window' }).wallpaperMotion).toBe(
'static',
@@ -65,6 +119,10 @@ describe('appearance settings IPC authorization', () => {
});
beforeEach(() => {
+ mocks.owner = 'owner-a:1';
+ mocks.boundaryPending = false;
+ mocks.importWallpaper.mockReset();
+ mocks.removeWallpaper.mockReset();
mocks.allWindows.length = 0;
mocks.trustedRead.mockReset();
mocks.trustedReadWindow.mockReset().mockReturnValue(false);
@@ -99,7 +157,7 @@ describe('appearance settings IPC authorization', () => {
([channel]) => channel === 'appearance-settings:reset',
)?.[1] as (event: unknown) => Promise<unknown>;
- mocks.readAppearanceSettingsState.mockReturnValue({ settings: persisted, overrides: {} });
+ mocks.readAppearanceSettingsState.mockReturnValue({ value: persisted, overrides: {} });
mocks.writeAppearanceSettingsPatch.mockResolvedValue(persisted);
mocks.resetAppearanceSettings.mockResolvedValue(persisted);
@@ -157,7 +215,7 @@ describe('appearance settings IPC authorization', () => {
wallpaperOverlay: 0.35,
});
});
- it.each(['cindy', 'cindy-portrait', 'aurora', 'sunset', 'paper', 'custom'])(
+ it.each(['cindy', 'cindy-portrait', 'aurora', 'sunset', 'paper'])(
'rejects retired wallpaper %s at the write boundary',
async (wallpaperId) => {
const setHandler = mocks.ipcHandle.mock.calls.find(
diff --git a/apps/desktop/src/main/__tests__/customWallpaper.test.ts b/apps/desktop/src/main/__tests__/customWallpaper.test.ts
new file mode 100644
index 0000000000..ce61de7e65
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/customWallpaper.test.ts
@@ -0,0 +1,125 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import sharp from 'sharp';
+
+const h = vi.hoisted(() => ({
+ picker: vi.fn(),
+ read: vi.fn(),
+ ingest: vi.fn(),
+ write: vi.fn(),
+ reset: vi.fn(),
+ remove: vi.fn(),
+ removeId: vi.fn(),
+ keep: vi.fn(),
+ valid: vi.fn(),
+ snapshot: { client: { drizzle: {} }, userId: 'test', clientEpoch: 1 },
+}));
+vi.mock('electron', () => ({ dialog: { showOpenDialog: h.picker } }));
+vi.mock('../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+vi.mock('../utils/readBoundedFile.js', () => ({ readBoundedFileNoFollow: h.read }));
+vi.mock('../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => h.snapshot }));
+vi.mock('../appSessionState.js', () => ({ ownerScopedUserDataPath: () => 'test-lock' }));
+vi.mock('../device-link/crossProcessLock.js', () => ({
+ withCrossProcessLock: (_p: string, _o: unknown, fn: Function) => fn({ held: true }),
+}));
+vi.mock('../cindy-media/refCompensationJournal.js', () => ({
+ captureMediaRefCompensationScope: () => ({ assertStillValid: h.valid }),
+}));
+vi.mock('../cindy-media/ingest.js', () => ({ ingestMedia: h.ingest }));
+vi.mock('../cindy-media/ledger.js', () => ({
+ removeRefById: h.removeId,
+ removeRefs: h.remove,
+ removeRefsExceptId: h.keep,
+}));
+vi.mock('../custom-wallpaper-settings.js', () => ({
+ customWallpaperStore: { writePatchAtomic: h.write, resetAtomic: h.reset },
+}));
+import {
+ importCustomWallpaper,
+ prepareWallpaperImage,
+ removeCustomWallpaper,
+} from '../custom-wallpaper';
+
+const url = `cindy-media://blobs/${'a'.repeat(64)}.webp`;
+beforeEach(async () => {
+ vi.resetAllMocks();
+ h.picker.mockResolvedValue({ canceled: false, filePaths: ['chosen-image'] });
+ h.read.mockResolvedValue(
+ await sharp({ create: { width: 8, height: 4, channels: 3, background: 'blue' } })
+ .png()
+ .toBuffer(),
+ );
+ h.ingest.mockResolvedValue({ url, hash: 'a'.repeat(64), refIds: ['new-ref'] });
+});
+
+describe('custom wallpaper import', () => {
+ it('decodes and pins the image before publishing, then removes only older wallpaper refs', async () => {
+ expect(await importCustomWallpaper({} as never)).toBe(true);
+ expect(h.ingest).toHaveBeenCalledWith(
+ expect.objectContaining({
+ mimeType: 'image/webp',
+ isCache: false,
+ refs: [{ refKind: 'import', refId: 'desktop-custom-wallpaper', originKind: 'user' }],
+ assertStillValid: expect.any(Function),
+ }),
+ h.snapshot.client.drizzle,
+ );
+ const metadata = await sharp(h.ingest.mock.calls[0][0].buffer).metadata();
+ expect(metadata).toMatchObject({ format: 'webp', width: 8, height: 4 });
+ expect(metadata.exif).toBeUndefined();
+ expect(h.write).toHaveBeenCalledWith({ url });
+ expect(h.keep).toHaveBeenCalledWith(
+ { refKind: 'import', refId: 'desktop-custom-wallpaper', keepId: 'new-ref' },
+ h.snapshot.client.drizzle,
+ );
+ expect(h.ingest.mock.invocationCallOrder[0]).toBeLessThan(h.write.mock.invocationCallOrder[0]);
+ expect(h.write.mock.invocationCallOrder[0]).toBeLessThan(h.keep.mock.invocationCallOrder[0]);
+ });
+ it('cancels without changing the preference or media', async () => {
+ h.picker.mockResolvedValue({ canceled: true, filePaths: [] });
+ expect(await importCustomWallpaper({} as never)).toBe(false);
+ expect(h.read).not.toHaveBeenCalled();
+ expect(h.write).not.toHaveBeenCalled();
+ });
+ it('rejects invalid or unsupported files without publishing', async () => {
+ h.read.mockResolvedValue(
+ Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"></svg>'),
+ );
+ await expect(importCustomWallpaper({} as never)).rejects.toThrow('INVALID_PARAMS');
+ expect(h.ingest).not.toHaveBeenCalled();
+ await expect(prepareWallpaperImage(Buffer.from('not an image'))).rejects.toThrow(
+ 'INVALID_PARAMS',
+ );
+ h.read.mockResolvedValue(null);
+ await expect(importCustomWallpaper({} as never)).rejects.toThrow('INVALID_PARAMS');
+ });
+ it('compensates only the new reference when saving fails', async () => {
+ h.write.mockRejectedValue(new Error('disk'));
+ await expect(importCustomWallpaper({} as never)).rejects.toThrow('disk');
+ expect(h.removeId).toHaveBeenCalledWith('new-ref', h.snapshot.client.drizzle);
+ expect(h.keep).not.toHaveBeenCalled();
+ });
+ it('does not clear a successfully published image if old-reference cleanup fails', async () => {
+ h.keep.mockRejectedValue(new Error('db'));
+ expect(await importCustomWallpaper({} as never)).toBe(true);
+ expect(h.removeId).not.toHaveBeenCalled();
+ });
+ it('rejects an owner switch while the picker is open', async () => {
+ h.picker.mockImplementation(async () => {
+ h.valid.mockImplementation(() => {
+ throw new Error('owner changed');
+ });
+ return { canceled: false, filePaths: ['chosen-image'] };
+ });
+ await expect(importCustomWallpaper({} as never)).rejects.toThrow('owner changed');
+ expect(h.read).not.toHaveBeenCalled();
+ expect(h.ingest).not.toHaveBeenCalled();
+ });
+ it('forgets the preference before removing its references', async () => {
+ await removeCustomWallpaper();
+ expect(h.reset.mock.invocationCallOrder[0]).toBeLessThan(h.remove.mock.invocationCallOrder[0]);
+ h.reset.mockRejectedValue(new Error('disk'));
+ h.remove.mockClear();
+ await expect(removeCustomWallpaper()).rejects.toThrow('disk');
+ expect(h.remove).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/appearance-settings-ipc.ts b/apps/desktop/src/main/appearance-settings-ipc.ts
index b881031394..1ed2203601 100644
--- a/apps/desktop/src/main/appearance-settings-ipc.ts
+++ b/apps/desktop/src/main/appearance-settings-ipc.ts
@@ -1,4 +1,6 @@
import { BrowserWindow, ipcMain } from 'electron';
+import { extractIpcError } from '../shared/ipcError.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from './appSessionState.js';
import {
APPEARANCE_LIMITS,
@@ -32,6 +34,17 @@ export const APPEARANCE_SETTINGS_CHANGED_CHANNEL = 'appearance-settings:changed'
let registered = false;
+function captureWallpaperOwner(): () => void {
+ const owner = activeOwnerScopeKey();
+ const assertValid = () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner) {
+ throwIpcError('INTERNAL', 'Wallpaper owner changed');
+ }
+ };
+ assertValid();
+ return assertValid;
+}
+
export function registerAppearanceSettingsIpc(): void {
if (registered) return;
registered = true;
@@ -46,7 +59,47 @@ export function registerAppearanceSettingsIpc(): void {
ipcMain.handle('appearance-settings:get', (event) => {
assertTrustedAppRendererEvent(event);
- return readAppearanceSettingsState();
+ const state = readAppearanceSettingsState();
+ broadcast(state.value);
+ return state;
+ });
+
+ // Local Desktop appearance only: no remote allowlist and no renderer-supplied path.
+ ipcMain.handle('appearance-settings:import-wallpaper', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const parent = BrowserWindow.fromWebContents(event.sender);
+ if (!parent) throwIpcError('INVALID_PARAMS', 'Wallpaper picker requires an application window');
+ const assertOwner = captureWallpaperOwner();
+ try {
+ const { importCustomWallpaper } = await import('./custom-wallpaper.js');
+ assertOwner();
+ if (!(await importCustomWallpaper(parent))) return null;
+ assertOwner();
+ const settings = readAppearanceSettings();
+ broadcast(settings);
+ return settings;
+ } catch (error) {
+ throwIpcError(
+ extractIpcError(error)?.code === 'INVALID_PARAMS' ? 'INVALID_PARAMS' : 'INTERNAL',
+ 'Unable to import wallpaper image',
+ );
+ }
+ });
+
+ ipcMain.handle('appearance-settings:remove-wallpaper', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const assertOwner = captureWallpaperOwner();
+ try {
+ const { removeCustomWallpaper } = await import('./custom-wallpaper.js');
+ assertOwner();
+ await removeCustomWallpaper();
+ assertOwner();
+ const settings = readAppearanceSettings();
+ broadcast(settings);
+ return settings;
+ } catch {
+ throwIpcError('INTERNAL', 'Unable to remove wallpaper image');
+ }
});
ipcMain.handle('appearance-settings:set-patch', async (event, rawPatch: unknown) => {
diff --git a/apps/desktop/src/main/appearance-settings-store.ts b/apps/desktop/src/main/appearance-settings-store.ts
index f692a11f2a..151ed1f698 100644
--- a/apps/desktop/src/main/appearance-settings-store.ts
+++ b/apps/desktop/src/main/appearance-settings-store.ts
@@ -1,5 +1,6 @@
import { app } from 'electron';
import path from 'node:path';
+import { readCustomWallpaperUrl } from './custom-wallpaper-settings.js';
import {
DEFAULT_APPEARANCE_SETTINGS,
@@ -30,28 +31,36 @@ const store = createOverrideSettingsFile<AppearanceSettings>({
});
export function readAppearanceSettings(): AppearanceSettings {
- return store.read();
+ const value = store.read();
+ const customWallpaperUrl = readCustomWallpaperUrl();
+ return {
+ ...value,
+ customWallpaperUrl,
+ wallpaperId: value.wallpaperId === 'custom' && !customWallpaperUrl ? 'none' : value.wallpaperId,
+ };
}
export function readAppearanceSettingsState(): OverrideSettingsState<AppearanceSettings> {
- return store.readState();
+ return { ...store.readState(), value: readAppearanceSettings() };
}
export async function writeAppearanceSettingsPatch(
patch: AppearanceOverrides,
): Promise<AppearanceSettings> {
await store.writePatchAtomic(patch);
- return store.read();
+ return readAppearanceSettings();
}
export async function updateAppearanceSettingsAtomic(
updater: (current: AppearanceSettings) => AppearanceOverrides,
): Promise<AppearanceSettings> {
- return store.updateAtomic((current) => updater(current.value));
+ await store.updateAtomic((current) => updater(current.value));
+ return readAppearanceSettings();
}
export async function resetAppearanceSettings(): Promise<AppearanceSettings> {
- return store.resetAtomic();
+ await store.resetAtomic();
+ return readAppearanceSettings();
}
export const __testing = {
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
index 391dca5da3..8e3f9cc771 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
@@ -64,6 +64,25 @@ async function seedSession(id: string, status: 'active' | 'archived' | 'deleted'
}
describe('recordBlob(幂等入账)', () => {
+ it('retains the newly published wallpaper pin and unrelated owners when deduplicating refs', async () => {
+ await seedBlob(HASH_A);
+ await seedBlob(HASH_B);
+ const owner = { refKind: 'import' as const, refId: 'desktop-custom-wallpaper' };
+ await ledger.addRef({ ...owner, hash: HASH_A, id: 'older' }, db);
+ await ledger.addRef({ ...owner, hash: HASH_B, id: 'duplicate' }, db);
+ await ledger.addRef({ ...owner, hash: HASH_B, id: 'keep' }, db);
+ await ledger.addRef({ ...owner, refId: 'unrelated', hash: HASH_A, id: 'other' }, db);
+ expect(await ledger.removeRefsExceptId({ ...owner, keepId: 'keep' }, db)).toBe(2);
+ expect(
+ db
+ .select()
+ .from(schema.mediaRefs)
+ .all()
+ .map((row) => row.id)
+ .sort(),
+ ).toEqual(['keep', 'other']);
+ expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(2);
+ });
it('首次入账写全量字段,重复入账不炸只刷 lastAccess', async () => {
await seedBlob(HASH_A);
await expect(seedBlob(HASH_A)).resolves.toBeUndefined();
diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.ts
index 69c050d7d1..7bec42690b 100644
--- a/apps/desktop/src/main/cindy-media/ledger.ts
+++ b/apps/desktop/src/main/cindy-media/ledger.ts
@@ -338,6 +338,24 @@ export async function removeRefsExceptHash(
return result.changes;
}
+/** Retain one newly published ref, including when importing the same hash again. */
+export async function removeRefsExceptId(
+ params: { refKind: MediaRefKind; refId: string; keepId: string },
+ db: LedgerDb = defaultDb(),
+): Promise<number> {
+ const result = await db
+ .delete(mediaRefs)
+ .where(
+ and(
+ eq(mediaRefs.refKind, params.refKind),
+ eq(mediaRefs.refId, params.refId),
+ ne(mediaRefs.id, params.keepId),
+ ),
+ )
+ .run();
+ return result.changes;
+}
+
/** 删除某引用方名下的全部引用(删会话 / 卸载意识时由业务代码调用)。 */
export async function removeRefs(
params: { refKind: MediaRefKind; refId: string },
diff --git a/apps/desktop/src/main/custom-wallpaper-settings.ts b/apps/desktop/src/main/custom-wallpaper-settings.ts
new file mode 100644
index 0000000000..acedb00a46
--- /dev/null
+++ b/apps/desktop/src/main/custom-wallpaper-settings.ts
@@ -0,0 +1,29 @@
+import { normalizeCustomWallpaperUrl } from '../shared/appearanceSettings.js';
+import {
+ activeOwnerScopeKey,
+ getActiveAppSession,
+ isAppSessionBoundaryPending,
+ ownerScopedUserDataPath,
+} from './appSessionState.js';
+import { createOverrideSettingsFile } from './maker-host/override-settings-file.js';
+import { createLogger } from './logger.js';
+
+// Artwork is private to the active data owner, unlike the machine's theme/font choices.
+export const customWallpaperStore = createOverrideSettingsFile<{ url: string }>({
+ filePath: () => ownerScopedUserDataPath('custom-wallpaper.json'),
+ scopeKey: activeOwnerScopeKey,
+ defaults: { url: '' },
+ normalize: (raw) => ({ url: normalizeCustomWallpaperUrl((raw as { url?: unknown })?.url) }),
+ log: createLogger('custom-wallpaper-settings'),
+ label: 'custom-wallpaper',
+ maxBytes: 4096,
+ preserveUnreadableFile: true,
+ logLoadedValue: false,
+ logReadErrorDetails: false,
+});
+
+export function readCustomWallpaperUrl(): string {
+ if (!getActiveAppSession().dataOwnerId || isAppSessionBoundaryPending()) return '';
+ customWallpaperStore.invalidateIfChanged();
+ return customWallpaperStore.read().url;
+}
diff --git a/apps/desktop/src/main/custom-wallpaper.ts b/apps/desktop/src/main/custom-wallpaper.ts
new file mode 100644
index 0000000000..ac04cdff07
--- /dev/null
+++ b/apps/desktop/src/main/custom-wallpaper.ts
@@ -0,0 +1,135 @@
+import { dialog, type BrowserWindow } from 'electron';
+import sharp from 'sharp';
+
+import { readBoundedFileNoFollow } from './utils/readBoundedFile.js';
+import { throwIpcError } from './utils/ipcValidate.js';
+import { getCurrentDbClientSnapshot } from './localDb/client/current.js';
+import { captureMediaRefCompensationScope } from './cindy-media/refCompensationJournal.js';
+import { ingestMedia } from './cindy-media/ingest.js';
+import { removeRefById, removeRefs, removeRefsExceptId } from './cindy-media/ledger.js';
+import { customWallpaperStore } from './custom-wallpaper-settings.js';
+import { createLogger } from './logger.js';
+import { ownerScopedUserDataPath } from './appSessionState.js';
+import { withCrossProcessLock } from './device-link/crossProcessLock.js';
+
+const log = createLogger('custom-wallpaper');
+const REF = { refKind: 'import' as const, refId: 'desktop-custom-wallpaper' };
+const MAX_BYTES = 20 * 1024 * 1024;
+let queue: Promise<unknown> = Promise.resolve();
+
+function captureScope() {
+ const snapshot = getCurrentDbClientSnapshot();
+ if (!snapshot) throwIpcError('INTERNAL', 'Wallpaper storage is not ready');
+ const compensation = captureMediaRefCompensationScope();
+ const assertValid = () => {
+ compensation.assertStillValid();
+ if (getCurrentDbClientSnapshot() !== snapshot)
+ throwIpcError('INTERNAL', 'Wallpaper owner changed');
+ };
+ return { db: snapshot.client.drizzle, compensation, assertValid };
+}
+
+function serialize<T>(action: () => Promise<T>): Promise<T> {
+ const lockPath = ownerScopedUserDataPath('custom-wallpaper-operation.lock');
+ const result = queue
+ .catch(() => undefined)
+ .then(() =>
+ withCrossProcessLock(
+ lockPath,
+ { label: 'custom-wallpaper', waitMs: 12_000 },
+ async (status) => {
+ if (!status.held)
+ throwIpcError('INTERNAL', 'Wallpaper is being changed in another window');
+ return action();
+ },
+ ),
+ );
+ queue = result;
+ return result;
+}
+
+/** Decode real raster bytes, apply orientation, strip metadata and retain a static 4K preview. */
+export async function prepareWallpaperImage(bytes: Buffer): Promise<Buffer> {
+ if (!bytes.length || bytes.length > MAX_BYTES)
+ throwIpcError('INVALID_PARAMS', 'Choose a PNG, JPEG or WebP image up to 20 MB');
+ try {
+ const image = sharp(bytes, { limitInputPixels: 40_000_000 });
+ const metadata = await image.metadata();
+ if (!['png', 'jpeg', 'webp'].includes(metadata.format ?? ''))
+ throw new Error('Unsupported image');
+ return await image
+ .rotate()
+ .resize({ width: 3840, height: 3840, fit: 'inside', withoutEnlargement: true })
+ .webp({ quality: 90 })
+ .toBuffer();
+ } catch {
+ throwIpcError('INVALID_PARAMS', 'Choose a valid PNG, JPEG or WebP image up to 40 megapixels');
+ }
+}
+
+/** Paths come only from this native picker, never from the renderer or remote peers. */
+export async function importCustomWallpaper(parent: BrowserWindow): Promise<boolean> {
+ const scope = captureScope();
+ return serialize(async () => {
+ scope.assertValid();
+ const selected = await dialog.showOpenDialog(parent, {
+ properties: ['openFile'],
+ filters: [{ name: 'PNG / JPEG / WebP', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],
+ });
+ scope.assertValid();
+ if (selected.canceled || !selected.filePaths[0]) return false;
+ let bytes: Buffer;
+ try {
+ const read = await readBoundedFileNoFollow(selected.filePaths[0], MAX_BYTES, {
+ nonBlocking: true,
+ });
+ if (!read) throw new Error('Unreadable image');
+ bytes = read;
+ } catch {
+ throwIpcError('INVALID_PARAMS', 'Cannot read image; choose a local image up to 20 MB');
+ }
+ const buffer = await prepareWallpaperImage(bytes);
+ scope.assertValid();
+ const media = await ingestMedia(
+ {
+ buffer,
+ mimeType: 'image/webp',
+ isCache: false,
+ refs: [{ ...REF, originKind: 'user' }],
+ assertStillValid: scope.assertValid,
+ refCompensationScope: scope.compensation,
+ },
+ scope.db,
+ );
+ try {
+ scope.assertValid();
+ await customWallpaperStore.writePatchAtomic({ url: media.url });
+ } catch (error) {
+ await Promise.allSettled(media.refIds.map((id) => removeRefById(id, scope.db)));
+ throw error;
+ }
+ // Publication succeeded. Cleanup failure must retain the new selection and its pin.
+ try {
+ await removeRefsExceptId({ ...REF, keepId: media.refIds[0] }, scope.db);
+ } catch {
+ log.warn('Previous wallpaper reference cleanup deferred');
+ }
+ scope.assertValid();
+ return true;
+ });
+}
+
+export async function removeCustomWallpaper(): Promise<void> {
+ const scope = captureScope();
+ return serialize(async () => {
+ scope.assertValid();
+ // Forget the preference before unpinning; never delete shared media bytes here.
+ await customWallpaperStore.resetAtomic();
+ try {
+ await removeRefs(REF, scope.db);
+ } catch {
+ log.warn('Removed wallpaper reference cleanup deferred');
+ }
+ scope.assertValid();
+ });
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 2fb764b265..b465afeb0c 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1130,6 +1130,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
pageZoomReset: (): Promise<{ ok: true; zoomFactor: number }> =>
ipcRenderer.invoke('page-zoom:reset'),
appearanceSettings: {
+ importWallpaper: () => ipcRenderer.invoke('appearance-settings:import-wallpaper'),
+ removeWallpaper: () => ipcRenderer.invoke('appearance-settings:remove-wallpaper'),
getSync: (): AppearanceSettings | null => appearanceSettingsInfo,
get: (): Promise<unknown> => ipcRenderer.invoke('appearance-settings:get'),
setPatch: (patch: Partial<AppearanceSettings>): Promise<AppearanceSettings> =>
diff --git a/apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts b/apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts
index 8df9ddc8f9..0fc7f34571 100644
--- a/apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts
+++ b/apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts
@@ -5,6 +5,7 @@ export default {
id: 'AppearanceSection',
order: 30,
entries: [
+ { id: 'settings.appearance.wallpaper.customChoose', fallbackTargetId: 'settings-search-target-general-appearance', tab: 'general', targetId: 'settings-search-settings-appearance-wallpaper', titleKey: 'settings.appearance.wallpaper.options.custom', sectionKey: 'settings.sections.appearance', descriptionKey: 'settings.appearance.wallpaper.customHint' },
{ id: 'settings.appearance.modeLabel', fallbackTargetId: 'settings-search-target-general-appearance', tab: 'general', targetId: 'settings-search-settings-appearance-modeLabel', titleKey: 'settings.appearance.modeLabel', sectionKey: 'settings.sections.appearance' },
{ id: 'settings.appearance.themeLabel', fallbackTargetId: 'settings-search-target-general-appearance', tab: 'general', targetId: 'settings-search-settings-appearance-themeLabel', titleKey: 'settings.appearance.themeLabel', sectionKey: 'settings.sections.appearance' },
{ id: 'settings.appearance.wallpaper.title', fallbackTargetId: 'settings-search-target-general-appearance', tab: 'general', targetId: 'settings-search-settings-appearance-wallpaper', titleKey: 'settings.appearance.wallpaper.title', sectionKey: 'settings.sections.appearance', descriptionKey: 'settings.appearance.wallpaper.description' },
diff --git a/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx b/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
index 09c998f437..31153078c6 100644
--- a/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
@@ -1,5 +1,7 @@
import { useTranslation } from 'react-i18next';
-import { RotateCcw } from 'lucide-react';
+import { RotateCcw, ImagePlus } from 'lucide-react';
+import { useState } from 'react';
+import { extractIpcError } from '@/utils/ipcError';
import { Button } from '@/components/ui/button';
import { SegmentedControl } from '@/components/ui/segmented-control';
@@ -22,15 +24,48 @@ const WALLPAPER_OPTIONS: Array<{ id: WallpaperId }> = [
export function WallpaperSection() {
const { t } = useTranslation();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState('');
const {
wallpaperId,
wallpaperOverlay,
wallpaperMotion,
+ customWallpaperUrl,
setWallpaper,
setOverlay,
setMotion,
resetWallpaper,
} = useWallpaperSettings();
+ const chooseImage = async () => {
+ setBusy(true);
+ setError('');
+ try {
+ const selected = await window.electronAPI.appearanceSettings.importWallpaper();
+ if (selected) setWallpaper('custom');
+ } catch (error) {
+ setError(
+ t(
+ extractIpcError(error)?.code === 'INVALID_PARAMS'
+ ? 'settings.appearance.wallpaper.customInvalid'
+ : 'settings.appearance.wallpaper.customFailed',
+ ),
+ );
+ } finally {
+ setBusy(false);
+ }
+ };
+ const removeImage = async () => {
+ setBusy(true);
+ setError('');
+ try {
+ await window.electronAPI.appearanceSettings.removeWallpaper();
+ if (wallpaperId === 'custom') setWallpaper('none');
+ } catch {
+ setError(t('settings.appearance.wallpaper.customFailed'));
+ } finally {
+ setBusy(false);
+ }
+ };
return (
<div
@@ -56,9 +91,10 @@ export function WallpaperSection() {
type="button"
onClick={resetWallpaper}
disabled={
- wallpaperId === DEFAULT_APPEARANCE_SETTINGS.wallpaperId &&
- wallpaperOverlay === DEFAULT_APPEARANCE_SETTINGS.wallpaperOverlay &&
- wallpaperMotion === DEFAULT_APPEARANCE_SETTINGS.wallpaperMotion
+ busy ||
+ (wallpaperId === DEFAULT_APPEARANCE_SETTINGS.wallpaperId &&
+ wallpaperOverlay === DEFAULT_APPEARANCE_SETTINGS.wallpaperOverlay &&
+ wallpaperMotion === DEFAULT_APPEARANCE_SETTINGS.wallpaperMotion)
}
>
<RotateCcw size={14} />
@@ -71,9 +107,12 @@ export function WallpaperSection() {
role="radiogroup"
aria-label={t('settings.appearance.wallpaper.aria')}
>
- {WALLPAPER_OPTIONS.map((option) => {
+ {[...WALLPAPER_OPTIONS, { id: 'custom' as const }].map((option) => {
const selected = wallpaperId === option.id;
- const background = getBuiltinWallpaperBackground(option.id);
+ const background =
+ option.id === 'custom' && customWallpaperUrl
+ ? `url("${customWallpaperUrl}")`
+ : getBuiltinWallpaperBackground(option.id);
return (
<button
key={option.id}
@@ -81,7 +120,12 @@ export function WallpaperSection() {
role="radio"
aria-checked={selected}
aria-label={t('settings.appearance.wallpaper.options.' + option.id)}
- onClick={() => setWallpaper(option.id)}
+ disabled={busy}
+ onClick={() =>
+ option.id === 'custom' && !customWallpaperUrl
+ ? void chooseImage()
+ : setWallpaper(option.id)
+ }
className={cn(
'flex min-w-0 flex-col gap-2 rounded-xl text-left transition-colors',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--settings-theme-icon-active)]',
@@ -101,6 +145,11 @@ export function WallpaperSection() {
backgroundSize: 'cover',
}}
>
+ {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" />
+ </span>
+ ) : null}
{option.id === 'none' ? (
<span className="absolute inset-0 flex items-center justify-center text-12 text-[var(--settings-section-sublabel)]">
{t('settings.appearance.wallpaper.nonePreview')}
@@ -122,6 +171,38 @@ export function WallpaperSection() {
})}
</div>
+ <div className="flex flex-wrap items-center gap-3">
+ <Button
+ variant="secondary"
+ type="button"
+ disabled={busy}
+ onClick={() => void chooseImage()}
+ >
+ <ImagePlus size={14} aria-hidden="true" />
+ {t(
+ `settings.appearance.wallpaper.${busy ? 'customBusy' : customWallpaperUrl ? 'customReplace' : 'customChoose'}`,
+ )}
+ </Button>
+ {customWallpaperUrl && (
+ <Button
+ variant="secondary"
+ type="button"
+ disabled={busy}
+ onClick={() => void removeImage()}
+ >
+ {t('settings.appearance.wallpaper.customRemove')}
+ </Button>
+ )}
+ <p className="text-12 text-[var(--settings-section-sublabel)]">
+ {t('settings.appearance.wallpaper.customHint')}
+ </p>
+ </div>
+ {error && (
+ <p role="alert" className="text-12 text-[var(--text-primary)]">
+ {error}
+ </p>
+ )}
+
<div className="h-px bg-[var(--settings-input-border)]" />
<div className="flex flex-col gap-3">
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 b78192f0f0..e9add62349 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
@@ -101,6 +101,7 @@ describe('AppearanceSection accessibility', () => {
'settings.appearance.wallpaper.options.cindy-window',
'settings.appearance.wallpaper.options.cindy-studio',
'settings.appearance.wallpaper.options.cindy-dream',
+ 'settings.appearance.wallpaper.options.custom',
]);
expect(
screen.getByRole('spinbutton', { name: 'settings.appearance.font.uiSize.label' }),
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
index 9e5623d240..e5c5951674 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
+++ b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
@@ -31,6 +31,59 @@ afterEach(() => {
});
describe('application wallpaper lifecycle', () => {
+ it('restores custom artwork from the current owner after the synchronous bootstrap and clears it on sign-out', async () => {
+ const url = `cindy-media://blobs/${'b'.repeat(64)}.webp`;
+ let authChanged: () => void = () => {};
+ const get = vi
+ .fn()
+ .mockResolvedValue({
+ value: { ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'custom', customWallpaperUrl: url },
+ });
+ vi.stubGlobal('electronAPI', {
+ onAuthStateChange: (fn: () => void) => {
+ authChanged = fn;
+ return () => {};
+ },
+ appearanceSettings: {
+ getSync: () => DEFAULT_APPEARANCE_SETTINGS,
+ get,
+ onChanged: () => () => {},
+ },
+ });
+ render(
+ <WallpaperSettingsProvider>
+ <Controls />
+ </WallpaperSettingsProvider>,
+ );
+ await waitFor(() =>
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-image')).toContain(
+ url,
+ ),
+ );
+ expect(document.querySelector('video')).toBeNull();
+ get.mockResolvedValue({ value: DEFAULT_APPEARANCE_SETTINGS });
+ act(() => authChanged());
+ expect(document.documentElement.dataset.wallpaperActive).toBeUndefined();
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ });
+ it('does not enable transparent surfaces for a missing custom image', () => {
+ vi.stubGlobal('electronAPI', {
+ appearanceSettings: {
+ getSync: () => ({
+ ...DEFAULT_APPEARANCE_SETTINGS,
+ wallpaperId: 'custom',
+ customWallpaperUrl: 'file:///private.png',
+ }),
+ onChanged: () => () => {},
+ },
+ });
+ render(
+ <WallpaperSettingsProvider>
+ <Controls />
+ </WallpaperSettingsProvider>,
+ );
+ expect(document.documentElement.dataset.wallpaperActive).toBeUndefined();
+ });
it.each(['cindy-window', 'cindy-studio', 'cindy-dream'] as const)(
'keeps %s as one full-window scene across pane and theme changes',
async (wallpaperId) => {
diff --git a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
index 32d00778b2..101122ac44 100644
--- a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
+++ b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
@@ -17,6 +17,7 @@ import {
type AppearanceSettings,
type WallpaperId,
type WallpaperMotion,
+ normalizeCustomWallpaperUrl,
} from '@/../shared/appearanceSettings';
import { getBuiltinWallpaperBackground } from '@/lib/wallpaper';
@@ -27,6 +28,7 @@ export interface WallpaperSettings {
wallpaperId: WallpaperId;
wallpaperOverlay: number;
wallpaperMotion: WallpaperMotion;
+ customWallpaperUrl?: string;
}
interface WallpaperSettingsContextValue extends WallpaperSettings {
@@ -56,6 +58,7 @@ function pickWallpaperSettings(settings: AppearanceSettings): WallpaperSettings
wallpaperId: settings.wallpaperId,
wallpaperOverlay: settings.wallpaperOverlay,
wallpaperMotion: settings.wallpaperMotion,
+ customWallpaperUrl: settings.customWallpaperUrl,
};
}
@@ -66,13 +69,17 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
// app windows, without changing the layout tree or stacking order of its panes.
useLayoutEffect(() => {
const root = document.documentElement;
- const active = settings.wallpaperId !== 'none';
+ const customUrl = normalizeCustomWallpaperUrl(settings.customWallpaperUrl);
+ const background =
+ settings.wallpaperId === 'custom'
+ ? customUrl
+ ? `url("${customUrl}")`
+ : undefined
+ : getBuiltinWallpaperBackground(settings.wallpaperId);
+ const active = Boolean(background);
if (active) {
root.dataset.wallpaperActive = 'true';
- root.style.setProperty(
- '--app-wallpaper-image',
- getBuiltinWallpaperBackground(settings.wallpaperId)!,
- );
+ 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;
root.style.setProperty('--app-wallpaper-veil', `${veil}%`);
@@ -92,7 +99,9 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
useEffect(() => {
const bridge = getBridge();
if (!bridge?.onChanged) return;
- return bridge.onChanged((next) => {
+ let disposed = false;
+ let revision = 0;
+ const apply = (next: AppearanceSettings) => {
const confirmed = pickWallpaperSettings(normalizeAppearanceSettings(next));
confirmedRef.current = confirmed;
const optimistic = pendingRef.current.reduce(
@@ -101,7 +110,39 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
);
settingsRef.current = optimistic;
setSettings(optimistic);
+ };
+ const unsubscribe = bridge.onChanged((next) => {
+ revision++;
+ apply(next);
+ });
+ const refresh = () => {
+ const request = ++revision;
+ void bridge
+ .get?.()
+ .then((state) => {
+ if (
+ !disposed &&
+ revision === request &&
+ state &&
+ typeof state === 'object' &&
+ 'value' in state
+ ) {
+ apply(normalizeAppearanceSettings(state.value));
+ }
+ })
+ .catch(() => undefined);
+ };
+ const unsubscribeAuth = window.electronAPI?.onAuthStateChange?.(() => {
+ // Clear private artwork immediately; do not show an outgoing owner's image.
+ apply({ ...DEFAULT_APPEARANCE_SETTINGS, ...settingsRef.current, customWallpaperUrl: '' });
+ refresh();
});
+ refresh();
+ return () => {
+ disposed = true;
+ unsubscribe();
+ unsubscribeAuth?.();
+ };
}, []);
const patch = useCallback((next: Partial<WallpaperSettings>) => {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index ede60727fc..5a22fd11a0 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -878,7 +878,7 @@
},
"wallpaper": {
"title": "Wallpaper",
- "description": "Choose a Cindy scene for the whole app, with static or dynamic display.",
+ "description": "Choose a Cindy scene or your own image for the whole app, independently of the theme.",
"reset": "Reset",
"aria": "Wallpaper selection",
"nonePreview": "None",
@@ -886,14 +886,22 @@
"none": "None",
"cindy-window": "Cindy · Window Companion",
"cindy-studio": "Cindy · Future Atelier",
- "cindy-dream": "Cindy · Dream Voyage"
+ "cindy-dream": "Cindy · Dream Voyage",
+ "custom": "Custom wallpaper"
},
"overlayLabel": "Overlay",
"overlayAria": "Wallpaper overlay strength",
"motionLabel": "Display",
"motionHint": "Still by default. Motion pauses when hidden and follows your reduced-motion preference.",
"motionStatic": "Static",
- "motionDynamic": "Dynamic"
+ "motionDynamic": "Dynamic",
+ "customChoose": "Choose image",
+ "customReplace": "Replace image",
+ "customRemove": "Remove image",
+ "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).",
+ "customFailed": "Could not save the wallpaper. Please try again."
},
"layout": {
"label": "Panel layout",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 2f5700d836..032b44324e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -878,7 +878,7 @@
},
"wallpaper": {
"title": "壁紙",
- "description": "アプリ全体に表示する Cindy の壁紙を選び、静止画と動画を切り替えられます。",
+ "description": "アプリ全体に Cindy の壁紙や自分の画像を設定できます。テーマは独立して選べます。",
"reset": "デフォルトに戻す",
"aria": "壁紙の選択",
"nonePreview": "なし",
@@ -886,14 +886,22 @@
"none": "なし",
"cindy-window": "Cindy · 窓辺のひととき",
"cindy-studio": "Cindy · 未来のアトリエ",
- "cindy-dream": "Cindy · 夢の旅"
+ "cindy-dream": "Cindy · 夢の旅",
+ "custom": "カスタム壁紙"
},
"overlayLabel": "オーバーレイ",
"overlayAria": "壁紙オーバーレイの強さ",
"motionLabel": "表示方法",
"motionHint": "初期設定は静止画です。非表示時は停止し、システムの視差効果を減らす設定に従います。",
"motionStatic": "静止画",
- "motionDynamic": "動画"
+ "motionDynamic": "動画",
+ "customChoose": "画像を選択",
+ "customReplace": "画像を変更",
+ "customRemove": "画像を削除",
+ "customBusy": "処理中…",
+ "customHint": "PNG・JPEG・WebP、最大 20 MB。この端末にのみ保存し、静止画として表示します。",
+ "customInvalid": "有効な PNG・JPEG・WebP 画像を選択してください(最大 20 MB・4000 万画素)。",
+ "customFailed": "壁紙を保存できませんでした。もう一度お試しください。"
},
"layout": {
"label": "パネルレイアウト",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index dab4618493..9328c72934 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -878,7 +878,7 @@
},
"wallpaper": {
"title": "배경화면",
- "description": "앱 전체에 적용할 Cindy 배경을 선택하고 정적 또는 동적 표시로 전환할 수 있습니다。",
+ "description": "앱 전체에 Cindy 배경이나 내 이미지를 적용하세요. 테마는 별도로 선택할 수 있습니다.",
"reset": "기본값으로 복원",
"aria": "배경화면 선택",
"nonePreview": "없음",
@@ -886,14 +886,22 @@
"none": "없음",
"cindy-window": "Cindy · 창가의 휴식",
"cindy-studio": "Cindy · 미래의 아틀리에",
- "cindy-dream": "Cindy · 꿈속 여행"
+ "cindy-dream": "Cindy · 꿈속 여행",
+ "custom": "사용자 지정 배경화면"
},
"overlayLabel": "오버레이",
"overlayAria": "배경화면 오버레이 강도",
"motionLabel": "표시 방식",
"motionHint": "기본값은 정적입니다. 창이 숨겨지면 일시 정지하며 시스템의 동작 줄이기 설정을 따릅니다.",
"motionStatic": "정적",
- "motionDynamic": "동적"
+ "motionDynamic": "동적",
+ "customChoose": "이미지 선택",
+ "customReplace": "이미지 교체",
+ "customRemove": "이미지 제거",
+ "customBusy": "처리 중…",
+ "customHint": "PNG, JPEG, WebP, 최대 20 MB. 이 기기에만 저장되며 정지 이미지로 표시됩니다.",
+ "customInvalid": "올바른 PNG, JPEG 또는 WebP 이미지를 선택하세요(최대 20 MB, 4천만 화소).",
+ "customFailed": "배경화면을 저장하지 못했습니다. 다시 시도하세요."
},
"layout": {
"label": "패널 레이아웃",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 7f26c9fbfd..5811920aaa 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -878,7 +878,7 @@
},
"wallpaper": {
"title": "壁纸",
- "description": "为整个应用选择一款 Cindy 场景壁纸,支持静态或动态展示。",
+ "description": "为整个应用选择 Cindy 场景或自己的图片,主题保持独立。",
"reset": "恢复默认",
"aria": "壁纸选择",
"nonePreview": "无",
@@ -886,14 +886,22 @@
"none": "无",
"cindy-window": "Cindy · 窗边陪伴",
"cindy-studio": "Cindy · 未来工作室",
- "cindy-dream": "Cindy · 梦境漫游"
+ "cindy-dream": "Cindy · 梦境漫游",
+ "custom": "自定义壁纸"
},
"overlayLabel": "遮罩",
"overlayAria": "壁纸遮罩强度",
"motionLabel": "展示方式",
"motionHint": "默认静态;动态在窗口隐藏时暂停,并遵循系统减少动效设置。",
"motionStatic": "静态",
- "motionDynamic": "动态"
+ "motionDynamic": "动态",
+ "customChoose": "选择图片",
+ "customReplace": "替换图片",
+ "customRemove": "移除图片",
+ "customBusy": "处理中…",
+ "customHint": "PNG、JPEG、WebP,最大 20 MB。仅保存在此设备,静态展示。",
+ "customInvalid": "请选择有效的 PNG、JPEG 或 WebP 图片(不超过 20 MB、4000 万像素)。",
+ "customFailed": "未能保存壁纸,请重试。"
},
"layout": {
"label": "面板布局",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index f38a058715..2943c6ee7d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -878,7 +878,7 @@
},
"wallpaper": {
"title": "桌布",
- "description": "為整個應用程式選擇一款 Cindy 場景桌布,支援靜態或動態顯示。",
+ "description": "為整個應用程式選擇 Cindy 場景或自己的圖片,主題保持獨立。",
"reset": "恢復預設",
"aria": "桌布選擇",
"nonePreview": "無",
@@ -886,14 +886,22 @@
"none": "無",
"cindy-window": "Cindy · 窗邊陪伴",
"cindy-studio": "Cindy · 未來工作室",
- "cindy-dream": "Cindy · 夢境漫遊"
+ "cindy-dream": "Cindy · 夢境漫遊",
+ "custom": "自訂桌布"
},
"overlayLabel": "遮罩",
"overlayAria": "桌布遮罩強度",
"motionLabel": "展示方式",
"motionHint": "預設靜態;動態在視窗隱藏時暫停,並遵循系統減少動態效果設定。",
"motionStatic": "靜態",
- "motionDynamic": "動態"
+ "motionDynamic": "動態",
+ "customChoose": "選擇圖片",
+ "customReplace": "替換圖片",
+ "customRemove": "移除圖片",
+ "customBusy": "處理中…",
+ "customHint": "PNG、JPEG、WebP,最大 20 MB。僅儲存在此裝置,靜態顯示。",
+ "customInvalid": "請選擇有效的 PNG、JPEG 或 WebP 圖片(不超過 20 MB、4000 萬像素)。",
+ "customFailed": "無法儲存桌布,請重試。"
},
"layout": {
"label": "面板佈局",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 1f24b24a05..8a02f8c99f 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1220,6 +1220,8 @@ interface ElectronAPI {
pageZoomOut: () => Promise<{ ok: true; zoomFactor: number }>;
pageZoomReset: () => Promise<{ ok: true; zoomFactor: number }>;
appearanceSettings: {
+ importWallpaper: () => Promise<import('../shared/appearanceSettings').AppearanceSettings | null>;
+ removeWallpaper: () => Promise<import('../shared/appearanceSettings').AppearanceSettings>;
getSync: () => import('../shared/appearanceSettings').AppearanceSettings | null;
get: () => Promise<unknown>;
setPatch: (
diff --git a/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts b/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts
index e905a6627e..da7d79c057 100644
--- a/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts
+++ b/apps/desktop/src/shared/__tests__/appearanceWallpaper.test.ts
@@ -2,7 +2,24 @@ import { describe, expect, it } from 'vitest';
import { normalizeAppearanceSettings } from '../appearanceSettings';
describe('wallpaper catalog compatibility', () => {
- it.each(['cindy', 'cindy-portrait', 'aurora', 'sunset', 'paper', 'custom'])(
+ it('accepts only canonical host-owned custom artwork and never legacy paths or CSS', () => {
+ const url = `cindy-media://blobs/${'a'.repeat(64)}.webp`;
+ expect(
+ normalizeAppearanceSettings({ wallpaperId: 'custom', customWallpaperUrl: url }),
+ ).toMatchObject({ wallpaperId: 'custom', customWallpaperUrl: url });
+ for (const value of [
+ 'file:///private.png',
+ 'https://example.com/image.webp',
+ 'data:image/png;base64,abc',
+ `${url}"),url(https://example.com)`,
+ 1,
+ ]) {
+ expect(normalizeAppearanceSettings({ customWallpaperUrl: value }).customWallpaperUrl).toBe(
+ '',
+ );
+ }
+ });
+ it.each(['cindy', 'cindy-portrait', 'aurora', 'sunset', 'paper'])(
'disables retired %s without resetting other appearance preferences',
(wallpaperId) => {
const settings = normalizeAppearanceSettings({
@@ -19,6 +36,7 @@ describe('wallpaper catalog compatibility', () => {
});
expect(settings).toEqual({
wallpaperId: 'none',
+ customWallpaperUrl: '',
wallpaperMotion: 'dynamic',
wallpaperOverlay: 0.35,
uiFamily: 'Example Sans',
diff --git a/apps/desktop/src/shared/appearanceSettings.ts b/apps/desktop/src/shared/appearanceSettings.ts
index 5ff81654fc..ff250fb36f 100644
--- a/apps/desktop/src/shared/appearanceSettings.ts
+++ b/apps/desktop/src/shared/appearanceSettings.ts
@@ -29,6 +29,8 @@ export interface AppearanceSettings {
wallpaperId: WallpaperId;
wallpaperOverlay: number;
wallpaperMotion: WallpaperMotion;
+ /** Read-only, host-owned media reference; never accepted by set-patch. */
+ customWallpaperUrl?: string;
}
export const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings = {
@@ -40,6 +42,7 @@ export const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings = {
wallpaperId: 'none',
wallpaperOverlay: 0.2,
wallpaperMotion: 'static',
+ customWallpaperUrl: '',
};
export const APPEARANCE_LIMITS = {
@@ -49,9 +52,21 @@ export const APPEARANCE_LIMITS = {
wallpaperOverlay: { min: 0, max: 0.6, step: 0.05 },
} as const;
-export const WALLPAPER_IDS = ['none', 'cindy-window', 'cindy-studio', 'cindy-dream'] as const;
+export const WALLPAPER_IDS = [
+ 'none',
+ 'cindy-window',
+ 'cindy-studio',
+ 'cindy-dream',
+ 'custom',
+] as const;
export type WallpaperId = (typeof WALLPAPER_IDS)[number];
+export function normalizeCustomWallpaperUrl(value: unknown): string {
+ return typeof value === 'string' && /^cindy-media:\/\/blobs\/[0-9a-f]{64}\.webp$/.test(value)
+ ? value
+ : '';
+}
+
export function clampAppearanceWallpaperOverlay(
value: number,
fallback = DEFAULT_APPEARANCE_SETTINGS.wallpaperOverlay,
@@ -127,6 +142,7 @@ export function normalizeAppearanceSettings(raw: unknown): AppearanceSettings {
? clampAppearanceWallpaperOverlay(value.wallpaperOverlay)
: DEFAULT_APPEARANCE_SETTINGS.wallpaperOverlay,
wallpaperMotion: value.wallpaperMotion === 'dynamic' ? 'dynamic' : 'static',
+ customWallpaperUrl: normalizeCustomWallpaperUrl(value.customWallpaperUrl),
};
}
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 369f536b57..a8aceb6b81 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -76,9 +76,16 @@ align with the same wallpaper instead of introducing an opaque footer rectangle.
Built-in SVG wallpapers are decorative assets, not new semantic UI colors.
Verify actual Light/Dark screenshots across host pages and the expanded tool pane.
-The wallpaper catalog contains only Window Companion, Future Atelier and Dream
+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).
-Remove the previous arrow, standalone portrait, gradient, paper and custom-image
+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
+20 MB and 40 megapixels, store a metadata-free static image up to 3840 pixels
+in the managed media store, and keep the reference private to the active owner.
+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.
+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,
so do not expose a fit selector that cannot affect them.