feat(appearance): 主题与壁纸搬到服务端(账号级)—— 回答"为什么背景存在本地"
用户质问:「为什么背景是保存在本地而不是服务器!」当时的实情是主题与壁纸只写 localStorage:换设备/换浏览器就没了,而且**多账号共用一份**(键是全局常量 `agentmail.background`)—— 同一台机器换账号背景不跟着走。而 localStorage 的 ~5MB 配额也解释了客户端那套"压到 2.4MB 以内"的限制本来就是为本地存储设计的。 现在:**服务端是权威(账号级),本地只是缓存**(首屏秒开、离线可用)。 ## 服务端 - 新表 `user_appearance`(两种方言),用**列**而不是 JSON:blob GC 要一眼看出 "这张图还有没有人用"。 - `/api/v1/me/appearance`:GET / PUT(主题+背景档)/ POST image(multipart)/ GET image / DELETE image。鉴权同其余 /me/*(cookie 或 Bearer)。 - 图片走**内容寻址的 blob 存储**(与附件同一套),库里只存 sha256;上限 4MB 兜底 (客户端会先压到 ~2.4MB),只收图片类型(非图片 415 —— 浏览器会把非图片渲染成 空白,用户只会看到"设置了却没变化"),超限 413 不静默截断。 - ★ **blob GC 的引用源加了这张表**:我在实现前先读了 `SweepUnreferencedBlobs`, 它只认 attachments / calendar_attachments。漏了这一处,壁纸会在下次 GC 时被当 孤儿删掉,而库里那行还在 —— 表现为"图 404、设置却显示已设置"。判据同时验了 壁纸存活**与**孤儿确实被清(否则"还在"可能只是因为 GC 没跑)。 ## 客户端 - `lib/appearance.ts`(纯函数:两侧形状换算、data URL→Blob)+ `stores/appearanceSync.ts` (pull / push / 去抖订阅 / 账号切换重新拉取)。 - 三条不变量都有判据:拉取以服务端为准;★ **拉取不会再推回去**(否则是自触发回环, 一次拉取顺带一次 PUT,服务端 updated_at 被无意义刷新);本地改动会推上去。 - 壁纸**只在换图时上传一次**(几 MB 不该每次 PUT 都跟着走)。 - 降级**必须可见**:未登录/不可达 → `local-only`,推失败 → `pending`,背景设置里 有徽标与说明("已同步 / 待同步 / 仅本机")。静默降级会让人以为已经同步, 然后在另一台机器上发现没有 —— 正是这次的缺陷。 - 图片用**带认证的 fetch** 取回再转 data URL:`<img src>` 发不出 Bearer,而 `?token=` 会把密钥写进历史记录与服务端日志(明确不做)。 ## 判据 - Go 10 条:往返、★多账号隔离、非法值归一、上传/取回字节一致、非图片 415、 超限 413、删除、未登录 401(五个端点)、★GC 存活 + 孤儿对照。 - 客户端 10 条:形状换算、image 无图退回 none、越界夹取、拉取生效、 ★拉取不推送、推送 payload、未登录/500 → local-only、推失败 → pending、 ★壁纸只上传一次。 - 全量:server 10 包全绿、客户端 249 通过(含打包一致性判据 —— 它先红后绿, 因为前端改了必须重打安装包,这条护栏是先前特意留下的)。 ## 线上验证与交付 - jianf 设置 → 回包 saved=true;**gui-lab 读到自己那份默认值**(隔离生效); gui-lab 上传 67B PNG → 取回 sha256 一致、`has_image=true`;DELETE 后 404。 - 网关已重打(WebUI 内嵌)并部署;Electron 安装包已重打(AppImage + deb)。 遗留:鸿蒙端还没有外观功能(数据已在服务端,将来可直接读);本地缓存仍在(离线可用)。
This commit is contained in:
@ -1,4 +1,6 @@
|
||||
import { Suspense, lazy, useEffect } from 'react';
|
||||
|
||||
import { initAppearanceSync, useAppearanceSync } from './stores/appearanceSync';
|
||||
import { connectSSE } from './api/sse';
|
||||
import { useAuthStore } from './stores/authStore';
|
||||
import { useAccountStore } from './stores/accountStore';
|
||||
@ -69,6 +71,16 @@ export default function App() {
|
||||
}
|
||||
}, [phase]);
|
||||
|
||||
// 外观同步(主题 + 壁纸):服务端是权威、本地是缓存。
|
||||
//
|
||||
// 订阅一次就够:它内部盯着 background/theme/账号切换三个来源。拉取放在
|
||||
// "已认证"之后 —— 在那之前没有令牌,拉了也只会把自己标成 local-only。
|
||||
useEffect(() => initAppearanceSync(), []);
|
||||
useEffect(() => {
|
||||
if (phase !== 'authenticated') return;
|
||||
void useAppearanceSync.getState().pull();
|
||||
}, [phase]);
|
||||
|
||||
// 登录态就绪后拉取数据 + SSE
|
||||
useEffect(() => {
|
||||
if (phase !== 'authenticated') return;
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
import { useRef, useState } from 'react';
|
||||
|
||||
import { useAppearanceSync } from '../stores/appearanceSync';
|
||||
import {
|
||||
DEFAULT_BACKGROUND,
|
||||
MAX_DATA_URL_BYTES,
|
||||
@ -64,6 +66,7 @@ export default function BackgroundPicker() {
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="text-sm font-medium text-gray-900">背景</h3>
|
||||
<SyncBadge />
|
||||
{active && (
|
||||
<button
|
||||
onClick={reset}
|
||||
@ -239,3 +242,42 @@ function Slider({
|
||||
|
||||
/** 「恢复默认」用到,导出以便测试断言默认值形状。 */
|
||||
export { DEFAULT_BACKGROUND };
|
||||
|
||||
/**
|
||||
* 同步状态徽标。
|
||||
*
|
||||
* 存在的理由:外观已经搬到服务端(账号级),但**服务端不可达/未登录时只能留在本机**。
|
||||
* 那种情况下必须让用户看见 —— 静默降级会让人以为"已经同步了",然后在另一台机器上
|
||||
* 发现没有,而这正是 2026-09-13 报的那个缺陷("为什么背景是保存在本地而不是服务器")。
|
||||
*/
|
||||
function SyncBadge() {
|
||||
const status = useAppearanceSync(s => s.status);
|
||||
if (status === 'idle') return null;
|
||||
const map: Record<string, { text: string; cls: string; title: string }> = {
|
||||
synced: {
|
||||
text: '已同步',
|
||||
cls: 'text-green-700 bg-green-50',
|
||||
title: '已保存到你的账号,换设备/换浏览器也在'
|
||||
},
|
||||
pending: {
|
||||
text: '待同步',
|
||||
cls: 'text-amber-700 bg-amber-50',
|
||||
title: '改动只在本机,服务端暂时没存上(网络或权限问题),稍后会自动重试'
|
||||
},
|
||||
'local-only': {
|
||||
text: '仅本机',
|
||||
cls: 'text-gray-600 bg-gray-100',
|
||||
title: '未登录或服务端不可达,这份外观只保存在这台设备上'
|
||||
}
|
||||
};
|
||||
const it = map[status];
|
||||
if (!it) return null;
|
||||
return (
|
||||
<span
|
||||
className={`ml-auto text-2xs px-1.5 py-0.5 rounded-full ${it.cls}`}
|
||||
title={it.title}
|
||||
>
|
||||
{it.text}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
171
client/electron/src/lib/appearance.ts
Normal file
171
client/electron/src/lib/appearance.ts
Normal file
@ -0,0 +1,171 @@
|
||||
/**
|
||||
* 外观(主题 + 壁纸)在**服务端**与本地之间的搬运。
|
||||
*
|
||||
* # 为什么有这一层
|
||||
*
|
||||
* 2026-09-13 用户的质问:「为什么背景是保存在本地而不是服务器!」当时的实情是
|
||||
* 主题与壁纸只写 localStorage:换设备/换浏览器就没了,而且**多账号共用一份**
|
||||
* (键是全局常量 `agentmail.background`)—— 同一台机器换账号,背景不跟着走。
|
||||
*
|
||||
* 现在的分工:
|
||||
* - **服务端**是权威(账号级,`/api/v1/me/appearance`);
|
||||
* - **本地**只是缓存:首屏秒开、离线可用、服务端不可达时降级;
|
||||
* - 降级**必须可见**(`syncStatus = 'local-only'`),否则用户会以为换设备也能带走,
|
||||
* 打开另一台机器才发现没有 —— 那正是这次的缺陷。
|
||||
*
|
||||
* 全部是纯函数 + 显式注入 fetch 的薄封装:可判据,且不把网络行为藏进 store。
|
||||
*/
|
||||
|
||||
import { fetchWithAuth } from '../api/config';
|
||||
|
||||
/** 服务端外观的形状(字段名与 handlers/appearance.go 的 JSON 一致)。 */
|
||||
export interface AppearanceResponse {
|
||||
theme?: string;
|
||||
bg_kind?: string;
|
||||
bg_preset_id?: string;
|
||||
bg_dim?: number;
|
||||
bg_blur?: number;
|
||||
has_image?: boolean;
|
||||
image_bytes?: number;
|
||||
image_url?: string;
|
||||
saved?: boolean;
|
||||
}
|
||||
|
||||
export interface AppearanceSnapshot {
|
||||
theme: 'light' | 'dark' | 'system';
|
||||
bgKind: 'none' | 'preset' | 'image';
|
||||
bgPresetId: string;
|
||||
bgDim: number;
|
||||
bgBlur: number;
|
||||
}
|
||||
|
||||
export const APPEARANCE_PATH = '/api/v1/me/appearance';
|
||||
export const APPEARANCE_IMAGE_PATH = '/api/v1/me/appearance/image';
|
||||
|
||||
const THEMES = new Set(['light', 'dark', 'system']);
|
||||
const KINDS = new Set(['none', 'preset', 'image']);
|
||||
|
||||
const clamp = (v: unknown, lo: number, hi: number, dflt: number): number => {
|
||||
const n = typeof v === 'number' && Number.isFinite(v) ? v : dflt;
|
||||
return Math.min(hi, Math.max(lo, Math.round(n)));
|
||||
};
|
||||
|
||||
/** 服务端回包 → 可直接灌进 store 的快照。认不出的值退回默认,不抛错。 */
|
||||
export function snapshotFromResponse(resp: AppearanceResponse | null | undefined): AppearanceSnapshot {
|
||||
const r = resp ?? {};
|
||||
return {
|
||||
theme: (THEMES.has(String(r.theme)) ? r.theme : 'system') as AppearanceSnapshot['theme'],
|
||||
bgKind: (KINDS.has(String(r.bg_kind)) ? r.bg_kind : 'none') as AppearanceSnapshot['bgKind'],
|
||||
bgPresetId: typeof r.bg_preset_id === 'string' && r.bg_preset_id ? r.bg_preset_id : 'aurora',
|
||||
bgDim: clamp(r.bg_dim, 0, 90, 12),
|
||||
bgBlur: clamp(r.bg_blur, 0, 40, 4)
|
||||
};
|
||||
}
|
||||
|
||||
/** 本地状态 → 服务端要的 JSON。`image` 档但没图时退回 none(服务端也这么归一)。 */
|
||||
export function payloadFromLocal(input: {
|
||||
theme: string;
|
||||
kind: string;
|
||||
presetId: string;
|
||||
imageDataUrl: string;
|
||||
dim: number;
|
||||
blur: number;
|
||||
}): Record<string, unknown> {
|
||||
const kind = KINDS.has(input.kind) ? input.kind : 'none';
|
||||
return {
|
||||
theme: THEMES.has(input.theme) ? input.theme : 'system',
|
||||
bg_kind: kind === 'image' && !input.imageDataUrl ? 'none' : kind,
|
||||
bg_preset_id: input.presetId || 'aurora',
|
||||
bg_dim: clamp(input.dim, 0, 90, 12),
|
||||
bg_blur: clamp(input.blur, 0, 40, 4)
|
||||
};
|
||||
}
|
||||
|
||||
/** data URL → Blob(上传要真字节,不能发字符串)。 */
|
||||
export function dataUrlToBlob(dataUrl: string): Blob {
|
||||
const m = /^data:([^;,]+)(;base64)?,(.*)$/.exec(dataUrl);
|
||||
if (!m) throw new Error('不是合法的 data URL');
|
||||
const [, ctype, b64, payload] = m;
|
||||
if (!b64) return new Blob([decodeURIComponent(payload)], { type: ctype });
|
||||
const bin = atob(payload);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
return new Blob([bytes], { type: ctype });
|
||||
}
|
||||
|
||||
export interface AppearanceAuth {
|
||||
base: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
/** 拉取:返回快照 + (若有)壁纸的 data URL。失败返回 null(调用方据此标 local-only)。 */
|
||||
export async function pullAppearance(
|
||||
auth: AppearanceAuth,
|
||||
fetchImpl: typeof fetchWithAuth = fetchWithAuth
|
||||
): Promise<{ snapshot: AppearanceSnapshot; imageDataUrl: string } | null> {
|
||||
if (!auth?.base || !auth?.token) return null;
|
||||
try {
|
||||
const res = await fetchImpl(auth, APPEARANCE_PATH);
|
||||
if (!res.ok) return null;
|
||||
const body = (await res.json()) as AppearanceResponse;
|
||||
const snapshot = snapshotFromResponse(body);
|
||||
let imageDataUrl = '';
|
||||
if (body?.has_image) {
|
||||
// 图片必须**带认证**取回来再转 data URL:`<img src>` 发不出 Bearer 头,
|
||||
// 而用 `?token=` 会把密钥写进历史记录与服务端日志(明确不做)。
|
||||
const img = await fetchImpl(auth, APPEARANCE_IMAGE_PATH);
|
||||
if (img.ok) {
|
||||
const blob = await img.blob();
|
||||
imageDataUrl = await blobToDataUrl(blob);
|
||||
}
|
||||
}
|
||||
return { snapshot, imageDataUrl };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 推送主题与背景档(不含图片)。返回是否成功 —— 失败要让调用方标成待同步/仅本地。 */
|
||||
export async function pushAppearance(
|
||||
auth: AppearanceAuth,
|
||||
payload: Record<string, unknown>,
|
||||
fetchImpl: typeof fetchWithAuth = fetchWithAuth
|
||||
): Promise<boolean> {
|
||||
if (!auth?.base || !auth?.token) return false;
|
||||
try {
|
||||
const res = await fetchImpl(auth, APPEARANCE_PATH, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传壁纸。返回是否成功。 */
|
||||
export async function uploadAppearanceImage(
|
||||
auth: AppearanceAuth,
|
||||
imageDataUrl: string,
|
||||
fetchImpl: typeof fetchWithAuth = fetchWithAuth
|
||||
): Promise<boolean> {
|
||||
if (!auth?.base || !auth?.token || !imageDataUrl) return false;
|
||||
try {
|
||||
const blob = dataUrlToBlob(imageDataUrl);
|
||||
const form = new FormData();
|
||||
form.append('file', blob, 'wallpaper');
|
||||
const res = await fetchImpl(auth, APPEARANCE_IMAGE_PATH, { method: 'POST', body: form });
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function blobToDataUrl(blob: Blob): Promise<string> {
|
||||
const buf = new Uint8Array(await blob.arrayBuffer());
|
||||
let bin = '';
|
||||
for (let i = 0; i < buf.length; i++) bin += String.fromCharCode(buf[i]);
|
||||
const ctype = blob.type || 'image/png';
|
||||
return `data:${ctype};base64,${btoa(bin)}`;
|
||||
}
|
||||
142
client/electron/src/stores/appearanceSync.ts
Normal file
142
client/electron/src/stores/appearanceSync.ts
Normal file
@ -0,0 +1,142 @@
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { activeAuth } from '../api/config';
|
||||
import {
|
||||
payloadFromLocal,
|
||||
pullAppearance,
|
||||
pushAppearance,
|
||||
uploadAppearanceImage,
|
||||
type AppearanceAuth
|
||||
} from '../lib/appearance';
|
||||
import { useAccountStore } from './accountStore';
|
||||
import { useBackgroundStore } from './backgroundStore';
|
||||
import { useThemeStore } from './themeStore';
|
||||
|
||||
/**
|
||||
* 外观同步:服务端是权威,本地是缓存。
|
||||
*
|
||||
* 三条不变量(都有判据):
|
||||
* 1. **登录后以服务端为准**(换设备/换浏览器能拿回来);
|
||||
* 2. **本地改动会推上去**(换设备再看还是这个外观);
|
||||
* 3. **拉下来的东西不会再推回去**(否则就是自己触发自己的回环 —— 一次拉取
|
||||
* 会连带 PUT 一次,服务端 updated_at 被无意义地刷新,还会掩盖真实的本地改动)。
|
||||
*
|
||||
* 服务端不可达时状态是 `local-only`,界面上**必须看得见** —— 静默失败会让用户
|
||||
* 以为"已经同步了",然后在另一台机器上发现没有,正是这次的缺陷。
|
||||
*/
|
||||
export type SyncStatus = 'idle' | 'synced' | 'pending' | 'local-only';
|
||||
|
||||
interface AppearanceSyncState {
|
||||
status: SyncStatus;
|
||||
/** 最近一次成功同步的时刻(ms)。0 = 从没成功过。 */
|
||||
lastSyncedAt: number;
|
||||
/** 正在把服务端的值灌进 store —— 此时不推回服务端。 */
|
||||
applyingRemote: boolean;
|
||||
pull: () => Promise<void>;
|
||||
push: () => Promise<void>;
|
||||
}
|
||||
|
||||
/** 上一次成功上传的壁纸(data URL)。相同就不重复上传几 MB。 */
|
||||
let lastUploadedImage = '';
|
||||
let pushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function currentAuth(): AppearanceAuth | null {
|
||||
const a = activeAuth();
|
||||
if (!a?.base || !a.token) return null;
|
||||
return { base: a.base, token: a.token };
|
||||
}
|
||||
|
||||
export const useAppearanceSync = create<AppearanceSyncState>((set) => ({
|
||||
status: 'idle',
|
||||
lastSyncedAt: 0,
|
||||
applyingRemote: false,
|
||||
|
||||
pull: async () => {
|
||||
const auth = currentAuth();
|
||||
if (!auth) {
|
||||
// 没登录(或还没选账号):本地就是全部,且要让用户知道。
|
||||
set({ status: 'local-only' });
|
||||
return;
|
||||
}
|
||||
const remote = await pullAppearance(auth);
|
||||
if (!remote) {
|
||||
set({ status: 'local-only' });
|
||||
return;
|
||||
}
|
||||
set({ applyingRemote: true });
|
||||
try {
|
||||
useThemeStore.getState().setPref(remote.snapshot.theme);
|
||||
const bg = useBackgroundStore.getState();
|
||||
// 背景档与参数以服务端为准;图片只在服务端有图时才覆盖本地
|
||||
// (服务端没图而本地有 = 本地还没推上去,别把用户的图擦掉)。
|
||||
if (remote.snapshot.bgKind === 'preset') bg.setPreset(remote.snapshot.bgPresetId);
|
||||
else if (remote.snapshot.bgKind === 'none') bg.setKind('none');
|
||||
else if (remote.snapshot.bgKind === 'image' && remote.imageDataUrl) bg.setImage(remote.imageDataUrl);
|
||||
if (remote.imageDataUrl) lastUploadedImage = remote.imageDataUrl;
|
||||
bg.setDim(remote.snapshot.bgDim);
|
||||
bg.setBlur(remote.snapshot.bgBlur);
|
||||
} finally {
|
||||
set({ applyingRemote: false });
|
||||
}
|
||||
set({ status: 'synced', lastSyncedAt: Date.now() });
|
||||
},
|
||||
|
||||
push: async () => {
|
||||
const auth = currentAuth();
|
||||
if (!auth) {
|
||||
set({ status: 'local-only' });
|
||||
return;
|
||||
}
|
||||
const theme = useThemeStore.getState().pref;
|
||||
const bg = useBackgroundStore.getState();
|
||||
const payload = payloadFromLocal({
|
||||
theme,
|
||||
kind: bg.kind,
|
||||
presetId: bg.presetId,
|
||||
imageDataUrl: bg.imageDataUrl,
|
||||
dim: bg.dim,
|
||||
blur: bg.blur
|
||||
});
|
||||
|
||||
let ok = await pushAppearance(auth, payload);
|
||||
// 壁纸本体单独传:几 MB 的图不该每次都跟着 PUT 走,只在换图时传一次。
|
||||
if (ok && bg.kind === 'image' && bg.imageDataUrl && bg.imageDataUrl !== lastUploadedImage) {
|
||||
const uploaded = await uploadAppearanceImage(auth, bg.imageDataUrl);
|
||||
if (uploaded) lastUploadedImage = bg.imageDataUrl;
|
||||
else ok = false;
|
||||
}
|
||||
set(ok ? { status: 'synced', lastSyncedAt: Date.now() } : { status: 'pending' });
|
||||
}
|
||||
}));
|
||||
|
||||
/** 本地一改就推(去抖),但**拉取期间不推**(见文件头第 3 条)。 */
|
||||
function schedulePush(): void {
|
||||
if (useAppearanceSync.getState().applyingRemote) return;
|
||||
if (pushTimer) clearTimeout(pushTimer);
|
||||
pushTimer = setTimeout(() => {
|
||||
pushTimer = null;
|
||||
void useAppearanceSync.getState().push();
|
||||
}, 600);
|
||||
}
|
||||
|
||||
/**
|
||||
* 接线:订阅两个 store 的改动,并在账号切换时重新拉取。
|
||||
*
|
||||
* 账号切换必须重新拉 —— 外观是**账号级**的,而 localStorage 里的缓存键是全局的
|
||||
* (这正是"放本地"时最直接的缺陷:同一台机器换账号背景不跟着走)。
|
||||
*
|
||||
* @returns 取消订阅(React 的 effect 清理用)
|
||||
*/
|
||||
export function initAppearanceSync(): () => void {
|
||||
const unsubBg = useBackgroundStore.subscribe(schedulePush);
|
||||
const unsubTheme = useThemeStore.subscribe(schedulePush);
|
||||
const unsubAccount = useAccountStore.subscribe((state, prev) => {
|
||||
if (state.activeId !== prev.activeId) void useAppearanceSync.getState().pull();
|
||||
});
|
||||
return () => {
|
||||
unsubBg();
|
||||
unsubTheme();
|
||||
unsubAccount();
|
||||
if (pushTimer) clearTimeout(pushTimer);
|
||||
};
|
||||
}
|
||||
148
client/electron/test/stores/appearanceSync.test.ts
Normal file
148
client/electron/test/stores/appearanceSync.test.ts
Normal file
@ -0,0 +1,148 @@
|
||||
/**
|
||||
* 外观同步的行为判据(2026-09-14)。
|
||||
*
|
||||
* 背景:用户质问「为什么背景是保存在本地而不是服务器!」⇒ 主题与壁纸搬到服务端
|
||||
* (账号级),本地只做缓存。这一层出错**不会抛异常**,只会表现为"设置看起来保存了,
|
||||
* 换设备却是别的样子"或"改动没存上却显示已同步" —— 所以必须逐条钉住:
|
||||
*
|
||||
* 1. 拉取以服务端为准(换设备能拿回来)
|
||||
* 2. ★ 拉取**不会**再推回去(否则自己触发自己:一次拉取顺带一次 PUT,
|
||||
* 服务端 updated_at 被无意义刷新,还会掩盖真实的本地改动)
|
||||
* 3. 本地改动会推上去(payload 形状要对)
|
||||
* 4. 推不上去要变成 pending,未登录/不可达是 local-only —— **降级可见**
|
||||
* 5. 壁纸只在换图时上传一次(几 MB 的东西不该每次 PUT 都跟着走)
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { setActiveAuth } from '../../src/api/config';
|
||||
import { useAppearanceSync } from '../../src/stores/appearanceSync';
|
||||
import { useBackgroundStore } from '../../src/stores/backgroundStore';
|
||||
import { useThemeStore } from '../../src/stores/themeStore';
|
||||
import { payloadFromLocal, snapshotFromResponse } from '../../src/lib/appearance';
|
||||
|
||||
type Call = { url: string; method: string; body?: any };
|
||||
|
||||
function fakeFetch(handler: (call: Call) => Response | Promise<Response>) {
|
||||
const calls: Call[] = [];
|
||||
globalThis.fetch = (async (input: any, init: any = {}) => {
|
||||
const url = String(input);
|
||||
const call: Call = { url, method: init.method || 'GET', body: init.body };
|
||||
calls.push(call);
|
||||
return handler(call);
|
||||
}) as any;
|
||||
return calls;
|
||||
}
|
||||
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
const REMOTE = {
|
||||
theme: 'dark',
|
||||
bg_kind: 'preset',
|
||||
bg_preset_id: 'dusk',
|
||||
bg_dim: 33,
|
||||
bg_blur: 7,
|
||||
has_image: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
setActiveAuth({ base: 'http://gw', token: 'tok' });
|
||||
useAppearanceSync.setState({ status: 'idle', lastSyncedAt: 0, applyingRemote: false });
|
||||
useThemeStore.getState().setPref('system');
|
||||
useBackgroundStore.setState({ kind: 'none', presetId: 'aurora', imageDataUrl: '', dim: 12, blur: 4 });
|
||||
});
|
||||
|
||||
describe('快照换算(纯函数)', () => {
|
||||
it('服务端的值能灌进本地形状,认不出的退回默认', () => {
|
||||
expect(snapshotFromResponse(REMOTE)).toEqual({
|
||||
theme: 'dark',
|
||||
bgKind: 'preset',
|
||||
bgPresetId: 'dusk',
|
||||
bgDim: 33,
|
||||
bgBlur: 7
|
||||
});
|
||||
expect(snapshotFromResponse({ theme: 'neon', bg_kind: 'video' } as any)).toMatchObject({
|
||||
theme: 'system',
|
||||
bgKind: 'none'
|
||||
});
|
||||
});
|
||||
|
||||
it('★ image 档但没图 → 退回 none(免得服务端存成"有图却没有")', () => {
|
||||
const p = payloadFromLocal({ theme: 'dark', kind: 'image', presetId: 'aurora', imageDataUrl: '', dim: 12, blur: 4 });
|
||||
expect(p.bg_kind).toBe('none');
|
||||
const q = payloadFromLocal({ theme: 'dark', kind: 'image', presetId: 'aurora', imageDataUrl: 'data:image/png;base64,AA', dim: 12, blur: 4 });
|
||||
expect(q.bg_kind).toBe('image');
|
||||
});
|
||||
|
||||
it('越界的 dim/blur 被夹住(服务端也会夹,但本地不该先送出脏值)', () => {
|
||||
const p = payloadFromLocal({ theme: 'light', kind: 'preset', presetId: 'aurora', imageDataUrl: '', dim: 999, blur: -3 });
|
||||
expect(p.bg_dim).toBe(90);
|
||||
expect(p.bg_blur).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('拉取与推送', () => {
|
||||
it('拉取以服务端为准(换设备能拿回来)', async () => {
|
||||
fakeFetch(() => json(REMOTE));
|
||||
await useAppearanceSync.getState().pull();
|
||||
expect(useThemeStore.getState().pref).toBe('dark');
|
||||
const bg = useBackgroundStore.getState();
|
||||
expect(bg.kind).toBe('preset');
|
||||
expect(bg.presetId).toBe('dusk');
|
||||
expect(bg.dim).toBe(33);
|
||||
expect(useAppearanceSync.getState().status).toBe('synced');
|
||||
});
|
||||
|
||||
it('★ 拉取不会再推回去(否则是自触发回环)', async () => {
|
||||
const calls = fakeFetch(() => json(REMOTE));
|
||||
await useAppearanceSync.getState().pull();
|
||||
const writes = calls.filter(c => c.method !== 'GET');
|
||||
expect(writes, `拉取期间不该有任何写请求:${JSON.stringify(writes)}`).toEqual([]);
|
||||
});
|
||||
|
||||
it('本地改动推上去,且 payload 形状对', async () => {
|
||||
const calls = fakeFetch(() => json({ saved: true }));
|
||||
useThemeStore.getState().setPref('light');
|
||||
useBackgroundStore.getState().setPreset('mint');
|
||||
await useAppearanceSync.getState().push();
|
||||
|
||||
const put = calls.find(c => c.method === 'PUT');
|
||||
expect(put, '应当发出 PUT').toBeTruthy();
|
||||
const body = JSON.parse(String(put!.body));
|
||||
expect(body).toMatchObject({ theme: 'light', bg_kind: 'preset', bg_preset_id: 'mint' });
|
||||
expect(useAppearanceSync.getState().status).toBe('synced');
|
||||
});
|
||||
|
||||
it('未登录 → local-only(降级必须可见)', async () => {
|
||||
setActiveAuth({ base: '', token: '' });
|
||||
fakeFetch(() => json(REMOTE));
|
||||
await useAppearanceSync.getState().pull();
|
||||
expect(useAppearanceSync.getState().status).toBe('local-only');
|
||||
});
|
||||
|
||||
it('服务端不可达 → local-only,不是"已同步"', async () => {
|
||||
fakeFetch(() => json({}, 500));
|
||||
await useAppearanceSync.getState().pull();
|
||||
expect(useAppearanceSync.getState().status).toBe('local-only');
|
||||
});
|
||||
|
||||
it('推送失败 → pending(稍后重试,而不是假装成功)', async () => {
|
||||
fakeFetch(() => json({}, 503));
|
||||
await useAppearanceSync.getState().push();
|
||||
expect(useAppearanceSync.getState().status).toBe('pending');
|
||||
});
|
||||
|
||||
it('★ 壁纸只在换图时上传一次(几 MB 不该每次 PUT 都跟着走)', async () => {
|
||||
const calls = fakeFetch(() => json({ has_image: true }));
|
||||
useBackgroundStore.getState().setImage('data:image/png;base64,AAAB');
|
||||
await useAppearanceSync.getState().push();
|
||||
const posts = () => calls.filter(c => c.method === 'POST').length;
|
||||
expect(posts(), '第一次推送应上传图片').toBe(1);
|
||||
|
||||
// 只改参数、不换图 → 不该再上传
|
||||
useBackgroundStore.getState().setDim(40);
|
||||
await useAppearanceSync.getState().push();
|
||||
expect(posts(), '没换图时不该重复上传').toBe(1);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user