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。

fix(desktop): share wallpaper preferences across profile accounts

DavidShene8bed8c633e1
diff --git a/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts b/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts
new file mode 100644
index 0000000000..ca94df8bd5
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/appearanceWallpaperShared.test.ts
@@ -0,0 +1,109 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({ dir: '', owner: 'a', pending: false }));
+vi.mock('electron', () => ({ app: { getPath: () => h.dir } }));
+vi.mock('../appSessionState.js', () => ({
+ getActiveAppSession: () => ({ dataOwnerId: h.owner }),
+ isAppSessionBoundaryPending: () => h.pending,
+ ownerScopedUserDataPath: (name: string) => path.join(h.dir, h.owner, name),
+}));
+vi.mock('../logger.js', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));
+vi.mock('../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: { child: () => ({ info: vi.fn(), warn: vi.fn() }) },
+}));
+vi.mock('../device-link/crossProcessLock.js', () => ({
+ withCrossProcessLock: async (_path: string, _options: unknown, action: Function) =>
+ action({ held: true }),
+}));
+import { customWallpaperStore, readCustomWallpaperUrl } from '../custom-wallpaper-settings';
+import {
+ readAppearanceSettings,
+ resetAppearanceSettings,
+ writeAppearanceSettingsPatch,
+} from '../appearance-settings-store';
+
+const urlA = `cindy-media://blobs/${'a'.repeat(64)}.webp`;
+const urlB = `cindy-media://blobs/${'b'.repeat(64)}.webp`;
+beforeEach(() => {
+ h.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wallpaper-shared-'));
+ h.owner = 'a';
+ h.pending = false;
+});
+afterEach(() => fs.rmSync(h.dir, { recursive: true, force: true }));
+
+function seedLegacy(owner: string, url: string) {
+ fs.mkdirSync(path.join(h.dir, owner), { recursive: true });
+ fs.writeFileSync(path.join(h.dir, owner, 'custom-wallpaper.json'), JSON.stringify({ url }));
+}
+
+describe('profile-wide wallpaper preference', () => {
+ it('shares selection, replacement and reset across accounts, including sign-out', async () => {
+ await customWallpaperStore.writePatchAtomic({ url: urlA });
+ await writeAppearanceSettingsPatch({ wallpaperId: 'custom' });
+ for (const owner of ['b', '']) {
+ h.owner = owner;
+ h.pending = true;
+ expect(readAppearanceSettings()).toMatchObject({
+ wallpaperId: 'custom',
+ customWallpaperUrl: urlA,
+ });
+ }
+ h.owner = 'b';
+ h.pending = false;
+ await customWallpaperStore.writePatchAtomic({ url: urlB });
+ h.owner = 'a';
+ expect(readAppearanceSettings()).toMatchObject({
+ wallpaperId: 'custom',
+ customWallpaperUrl: urlB,
+ });
+ await resetAppearanceSettings();
+ h.owner = 'b';
+ expect(readAppearanceSettings()).toMatchObject({
+ wallpaperId: 'none',
+ customWallpaperUrl: urlB,
+ });
+ await writeAppearanceSettingsPatch({ wallpaperId: 'cindy-dream' });
+ h.owner = 'a';
+ expect(readAppearanceSettings().wallpaperId).toBe('cindy-dream');
+ });
+
+ it('adopts the active preview image once, and never resurrects removed images from another account', async () => {
+ seedLegacy('a', urlA);
+ seedLegacy('b', urlB);
+ await writeAppearanceSettingsPatch({ wallpaperId: 'custom' });
+ expect(readAppearanceSettings()).toMatchObject({
+ wallpaperId: 'custom',
+ customWallpaperUrl: urlA,
+ });
+ h.owner = 'b';
+ expect(readCustomWallpaperUrl()).toBe(urlA);
+ await customWallpaperStore.writePatchAtomic({ url: '' }, { preserveDefaults: true });
+ h.owner = 'a';
+ expect(readAppearanceSettings()).toMatchObject({ wallpaperId: 'none', customWallpaperUrl: '' });
+ expect(JSON.parse(fs.readFileSync(path.join(h.dir, 'custom-wallpaper.json'), 'utf8'))).toEqual({
+ url: '',
+ });
+ });
+
+ it('waits for a settled active account before adopting a preview image', () => {
+ seedLegacy('a', urlA);
+ h.pending = true;
+ expect(readCustomWallpaperUrl()).toBe('');
+ h.pending = false;
+ expect(readCustomWallpaperUrl()).toBe(urlA);
+ });
+
+ it('preserves unreadable shared settings instead of replacing them with a legacy image', async () => {
+ seedLegacy('a', urlA);
+ const target = path.join(h.dir, 'custom-wallpaper.json');
+ fs.writeFileSync(target, '{broken');
+ expect(readCustomWallpaperUrl()).toBe('');
+ await expect(customWallpaperStore.writePatchAtomic({ url: urlB })).rejects.toThrow(
+ 'unreadable',
+ );
+ expect(fs.readFileSync(target, 'utf8')).toBe('{broken');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/customWallpaper.test.ts b/apps/desktop/src/main/__tests__/customWallpaper.test.ts
index 55683633aa..045cc90ffd 100644
--- a/apps/desktop/src/main/__tests__/customWallpaper.test.ts
+++ b/apps/desktop/src/main/__tests__/customWallpaper.test.ts
@@ -6,7 +6,6 @@ const h = vi.hoisted(() => ({
read: vi.fn(),
ingest: vi.fn(),
write: vi.fn(),
- reset: vi.fn(),
remove: vi.fn(),
removeId: vi.fn(),
keep: vi.fn(),
@@ -31,7 +30,7 @@ vi.mock('../cindy-media/ledger.js', () => ({
removeRefsExceptId: h.keep,
}));
vi.mock('../custom-wallpaper-settings.js', () => ({
- customWallpaperStore: { writePatchAtomic: h.write, resetAtomic: h.reset },
+ customWallpaperStore: { writePatchAtomic: h.write },
}));
import {
importCustomWallpaper,
@@ -53,7 +52,7 @@ beforeEach(async () => {
});
describe('custom wallpaper import', () => {
- it('lets another owner remove their image while the old owner picker remains open', async () => {
+ it('lets another owner remove the shared image while the old owner picker remains open', async () => {
let closePicker!: (value: { canceled: boolean; filePaths: string[] }) => void;
h.picker.mockReturnValueOnce(new Promise(resolve => { closePicker = resolve; }));
const oldImport = importCustomWallpaper({} as never);
@@ -62,7 +61,7 @@ describe('custom wallpaper import', () => {
h.snapshot = { client: { drizzle: {} }, userId: 'other', clientEpoch: 2 };
const removal = removeCustomWallpaper();
try {
- await vi.waitFor(() => expect(h.reset).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(h.write).toHaveBeenCalledOnce());
} finally {
closePicker({ canceled: true, filePaths: [] });
await rejected;
@@ -79,11 +78,11 @@ describe('custom wallpaper import', () => {
await vi.waitFor(() => expect(h.picker).toHaveBeenCalledOnce());
const removal = removeCustomWallpaper();
await Promise.resolve();
- expect(h.reset).not.toHaveBeenCalled();
+ expect(h.write).not.toHaveBeenCalled();
closePicker({ canceled: true, filePaths: [] });
await importing;
await removal;
- expect(h.reset).toHaveBeenCalledOnce();
+ expect(h.write).toHaveBeenCalledOnce();
});
it('decodes and pins the image before publishing, then removes only older wallpaper refs', async () => {
expect(await importCustomWallpaper({} as never)).toBe(true);
@@ -149,8 +148,9 @@ describe('custom wallpaper import', () => {
});
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'));
+ expect(h.write).toHaveBeenCalledWith({ url: '' }, { preserveDefaults: true });
+ expect(h.write.mock.invocationCallOrder[0]).toBeLessThan(h.remove.mock.invocationCallOrder[0]);
+ h.write.mockRejectedValue(new Error('disk'));
h.remove.mockClear();
await expect(removeCustomWallpaper()).rejects.toThrow('disk');
expect(h.remove).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts b/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts
index 1e28ebe9f5..211482e809 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts
@@ -55,6 +55,7 @@ afterAll(() => {
beforeEach(() => {
db = freshDb();
+ fs.writeFileSync(path.join(tmpUserData, 'custom-wallpaper.json'), JSON.stringify({ url: '' }));
fs.rmSync(path.join(tmpUserData, 'cindy-media'), { recursive: true, force: true });
legacyRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-storage-legacy-'));
});
@@ -67,11 +68,11 @@ const OLD_MS = 100 * 60 * 60 * 1000;
async function seedBlob(
content: string,
- opts?: { isCache?: boolean; aged?: boolean },
+ opts?: { isCache?: boolean; aged?: boolean; mimeType?: string },
): Promise<{ hash: string; ext: string; bytes: number; url: string }> {
const written = await blobStore.writeBlob({
buffer: Buffer.from(content),
- mimeType: 'image/png',
+ mimeType: opts?.mimeType ?? 'image/png',
});
await ledger.recordBlob(
{
@@ -191,6 +192,32 @@ describe('scan(清理预检:三个暂存区保护贯通)', () => {
});
describe('cleanup(执行:全类别 + 执行时重新取证)', () => {
+ it.each([false, true])('protects the shared wallpaper without any owner-local ref (cache=%s)', async (isCache) => {
+ const image = await seedBlob('shared-wallpaper', { aged: true, isCache, mimeType: 'image/webp' });
+ const handlers = makeHandlers();
+ // Another account selected this blob after the cleanup preview. Its pin is
+ // absent from this account's ledger; the host preference must protect it.
+ await handlers.scan({ draftUrls: [] });
+ fs.writeFileSync(path.join(tmpUserData, 'custom-wallpaper.json'), JSON.stringify({ url: image.url }));
+ const result = await handlers.cleanup({
+ draftUrls: [], zeroRefHashes: [image.hash], evictCacheHashes: [image.hash],
+ deadDirNames: [], cleanTmpFiles: false,
+ });
+ expect(result.freedBytes).toBe(0);
+ const scan = await handlers.scan({ draftUrls: [] });
+ expect(scan.zeroRef.hashes).not.toContain(image.hash);
+ expect(scan.cache.evictable.map((item) => item.hash)).not.toContain(image.hash);
+ expect((await handlers.stats()).blobs.totalCount).toBe(1);
+ // Verify the bytes as well as the ledger, then explicitly forget the image.
+ expect(fs.existsSync(blobStore.resolveSafe(image.url).absPath)).toBe(true);
+ fs.writeFileSync(path.join(tmpUserData, 'custom-wallpaper.json'), JSON.stringify({ url: '' }));
+ const removed = await handlers.cleanup({
+ draftUrls: [], zeroRefHashes: [image.hash], evictCacheHashes: [image.hash],
+ deadDirNames: [], cleanTmpFiles: false,
+ });
+ expect(removed.freedBytes).toBe(image.bytes);
+ });
+
it('零引用/缓存逐出/死目录/tmp 一次执行,汇总释放量', async () => {
const doomed = await seedBlob('clean-doomed', { aged: true });
const cacheBlob = await seedBlob('clean-cache', { isCache: true });
diff --git a/apps/desktop/src/main/cindy-media/storageIpc.ts b/apps/desktop/src/main/cindy-media/storageIpc.ts
index f3acfb289d..1268fd3fba 100644
--- a/apps/desktop/src/main/cindy-media/storageIpc.ts
+++ b/apps/desktop/src/main/cindy-media/storageIpc.ts
@@ -20,6 +20,7 @@
*/
import { createLogger } from '../logger';
+import { readCustomWallpaperUrl } from '../custom-wallpaper-settings';
import { throwIpcError } from '../utils/ipcValidate';
import * as blobStore from './blobStore';
import * as ledger from './ledger';
@@ -135,7 +136,8 @@ const EMPTY_CACHE: recycler.CacheScan = {
async function collectLive(deps: StorageIpcDeps, draftUrls: string[]): Promise<Set<string>> {
const sources: LiveHashSources = {
// 发起窗口随参带的 + 全窗口登记表的并集(多窗口草稿全豁免)。
- draftUrls: [...draftUrls, ...(deps.getRegisteredDraftUrls?.() ?? [])],
+ // The profile-wide wallpaper may be pinned only in a different owner's ledger.
+ draftUrls: [...draftUrls, ...(deps.getRegisteredDraftUrls?.() ?? []), readCustomWallpaperUrl()],
inMemoryQueueTexts: deps.getQueueScanTexts,
snapshotPayloads: deps.loadSnapshotPayloads,
};
diff --git a/apps/desktop/src/main/custom-wallpaper-settings.ts b/apps/desktop/src/main/custom-wallpaper-settings.ts
index acedb00a46..1869eef833 100644
--- a/apps/desktop/src/main/custom-wallpaper-settings.ts
+++ b/apps/desktop/src/main/custom-wallpaper-settings.ts
@@ -1,6 +1,8 @@
+import { app } from 'electron';
+import fs from 'node:fs';
+import path from 'node:path';
import { normalizeCustomWallpaperUrl } from '../shared/appearanceSettings.js';
import {
- activeOwnerScopeKey,
getActiveAppSession,
isAppSessionBoundaryPending,
ownerScopedUserDataPath,
@@ -8,12 +10,15 @@ import {
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.
+const filePath = () => path.join(app.getPath('userData'), 'custom-wallpaper.json');
+
+// Like theme preferences, the image is shared by accounts in this Desktop profile.
export const customWallpaperStore = createOverrideSettingsFile<{ url: string }>({
- filePath: () => ownerScopedUserDataPath('custom-wallpaper.json'),
- scopeKey: activeOwnerScopeKey,
+ filePath,
defaults: { url: '' },
- normalize: (raw) => ({ url: normalizeCustomWallpaperUrl((raw as { url?: unknown })?.url) }),
+ normalize: (raw) => ({
+ url: normalizeCustomWallpaperUrl((raw as { url?: unknown })?.url),
+ }),
log: createLogger('custom-wallpaper-settings'),
label: 'custom-wallpaper',
maxBytes: 4096,
@@ -22,8 +27,25 @@ export const customWallpaperStore = createOverrideSettingsFile<{ url: string }>(
logReadErrorDetails: false,
});
+function migratePreviewPreference(): void {
+ const target = filePath();
+ if (fs.existsSync(target) || !getActiveAppSession().dataOwnerId || isAppSessionBoundaryPending())
+ return;
+ // Adopt only the active account's pre-release preference; never scan other accounts.
+ // Exclusive creation cannot overwrite another process's shared preference.
+ // Removal retains an empty file so old preferences cannot reappear.
+ try {
+ const source = ownerScopedUserDataPath('custom-wallpaper.json');
+ if (!fs.existsSync(source) || fs.statSync(source).size > 4096) return;
+ const url = normalizeCustomWallpaperUrl(JSON.parse(fs.readFileSync(source, 'utf8'))?.url);
+ if (url) fs.writeFileSync(target, JSON.stringify({ url }), { encoding: 'utf8', flag: 'wx' });
+ } catch {
+ // Preserve unreadable legacy files and never log their private contents.
+ }
+}
+
export function readCustomWallpaperUrl(): string {
- if (!getActiveAppSession().dataOwnerId || isAppSessionBoundaryPending()) return '';
+ migratePreviewPreference();
customWallpaperStore.invalidateIfChanged();
return customWallpaperStore.read().url;
}
diff --git a/apps/desktop/src/main/custom-wallpaper.ts b/apps/desktop/src/main/custom-wallpaper.ts
index ac29fbc616..7363fb0503 100644
--- a/apps/desktop/src/main/custom-wallpaper.ts
+++ b/apps/desktop/src/main/custom-wallpaper.ts
@@ -128,7 +128,7 @@ export async function removeCustomWallpaper(): Promise<void> {
return serialize(async () => {
scope.assertValid();
// Forget the preference before unpinning; never delete shared media bytes here.
- await customWallpaperStore.resetAtomic();
+ await customWallpaperStore.writePatchAtomic({ url: '' }, { preserveDefaults: true });
try {
await removeRefs(REF, scope.db);
} catch {
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
index e5c5951674..63dec070a1 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
+++ b/apps/desktop/src/renderer/hooks/__tests__/useWallpaperSettings.test.tsx
@@ -31,7 +31,7 @@ afterEach(() => {
});
describe('application wallpaper lifecycle', () => {
- it('restores custom artwork from the current owner after the synchronous bootstrap and clears it on sign-out', async () => {
+ it('restores shared artwork and keeps it visible throughout an account switch', async () => {
const url = `cindy-media://blobs/${'b'.repeat(64)}.webp`;
let authChanged: () => void = () => {};
const get = vi
@@ -61,10 +61,10 @@ describe('application wallpaper lifecycle', () => {
),
);
expect(document.querySelector('video')).toBeNull();
- get.mockResolvedValue({ value: DEFAULT_APPEARANCE_SETTINGS });
act(() => authChanged());
- expect(document.documentElement.dataset.wallpaperActive).toBeUndefined();
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-image')).toContain(url);
await waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-image')).toContain(url);
});
it('does not enable transparent surfaces for a missing custom image', () => {
vi.stubGlobal('electronAPI', {
diff --git a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
index 101122ac44..f3877958e8 100644
--- a/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
+++ b/apps/desktop/src/renderer/hooks/useWallpaperSettings.tsx
@@ -133,8 +133,7 @@ export function WallpaperSettingsProvider({ children }: { children: ReactNode })
.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: '' });
+ // Wallpaper is a profile-wide preference, like the theme. Keep it visible.
refresh();
});
refresh();
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 27b08fb08b..b58901ec71 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -81,7 +81,13 @@ 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
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.
+in the managed media store. Wallpaper selection and the custom image reference
+are shared within the Desktop profile, just like theme preferences (user decision,
+2026-10-02). Switching accounts keeps the same wallpaper. Media cleanup by any
+account must protect the shared image. Font-only utility renderers never receive
+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.