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:
2026-09-14 08:32:22 +08:00
parent 1ec88866ac
commit 5b6fef764f
17 changed files with 1307 additions and 28 deletions

View File

@ -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;

View File

@ -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>
);
}

View 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)}`;
}

View 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);
};
}

View 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);
});
});

View File

@ -2,6 +2,8 @@ module homeagent-mail-bridge
go 1.25.0
require gitcode.com/JianFeeeee/homeagent-sdk v1.2.0
require gitcode.com/JianFeeeee/homeagent-sdk v1.3.0
replace gitcode.com/JianFeeeee/homeagent-sdk => /root/.homeagent/hmapdev/sdk/v1.2.0
replace gitcode.com/JianFeeeee/homeagent-sdk => /root/.homeagent/hmapdev/sdk/v1.3.0

View File

@ -3,7 +3,7 @@
"name_zh": "AgentMail 桥接",
"name_en": "homeagent",
"version": "0.2.2",
"sdk": "1.2.0",
"sdk": "1.3.0",
"description": "HomeAgent 接入 AgentMail邮件驱动的多智能体协作",
"author": "AgentMail",
"entry": "plugin.bin",

View File

@ -5,7 +5,7 @@
"name": "homeagent-mail-bridge",
"name_en": "homeagent",
"name_zh": "AgentMail 桥接",
"sdk": "1.2.0",
"sdk": "1.3.0",
"tags": [
"mail",
"agentmail"

View File

@ -174,6 +174,12 @@ func main() {
r.Delete("/me/attachments/{id}", handler.MeDeleteAttachment)
// 自己的客户端连接密钥(仅能用于 /me/* 与会话级接口,不可注册 Agent
// 用户外观(主题 + 壁纸):账号级,跨设备/跨客户端同一份
r.Get("/me/appearance", handler.GetAppearance)
r.Put("/me/appearance", handler.PutAppearance)
r.Post("/me/appearance/image", handler.UploadAppearanceImage)
r.Get("/me/appearance/image", handler.GetAppearanceImage)
r.Delete("/me/appearance/image", handler.DeleteAppearanceImage)
r.Post("/me/keys", handler.CreateMyKey)
r.Get("/me/keys", handler.ListMyKeys)
r.Delete("/me/keys/{id}", handler.DeleteMyKey)

View File

@ -24,6 +24,8 @@ type Config struct {
AttachmentDir string
// 单个附件上限(字节)。默认 25MB与常见邮箱附件限额一致
MaxAttachmentBytes int64
// MaxAppearanceBytes 是壁纸图片上限(客户端会先压到 ~2.4MB,这里是兜底)。
MaxAppearanceBytes int64
}
var C *Config
@ -46,6 +48,7 @@ func Load() *Config {
AttachmentDir: getEnv("AGENTMAIL_ATTACHMENT_DIR",
filepath.Join(getEnv("AGENTMAIL_DATA_DIR", "data"), "attachments")),
MaxAttachmentBytes: getEnvInt64("AGENTMAIL_MAX_ATTACHMENT_BYTES", 25<<20),
MaxAppearanceBytes: getEnvInt64("AGENTMAIL_MAX_APPEARANCE_BYTES", 4<<20),
}
return C
}

View File

@ -457,3 +457,19 @@ CREATE TABLE IF NOT EXISTS app_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL DEFAULT ''
);
-- 用户外观(主题 + 壁纸):与 init_sqlite.sql 同一张表、同一份语义
-- (为什么放服务端、为什么用列而不是 JSON见那边的注释
CREATE TABLE IF NOT EXISTS user_appearance (
user_id TEXT NOT NULL,
theme TEXT NOT NULL DEFAULT 'system',
bg_kind TEXT NOT NULL DEFAULT 'none',
bg_preset_id TEXT NOT NULL DEFAULT '',
bg_dim INTEGER NOT NULL DEFAULT 12,
bg_blur INTEGER NOT NULL DEFAULT 4,
image_sha256 TEXT NOT NULL DEFAULT '',
image_type TEXT NOT NULL DEFAULT '',
image_bytes INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ DEFAULT NOW(),
PRIMARY KEY (user_id)
);

View File

@ -509,3 +509,27 @@ CREATE TABLE IF NOT EXISTS app_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL DEFAULT ''
);
-- ─── 用户外观(主题 + 壁纸)────────────────────────────────────────────
--
-- 为什么放服务端2026-09-13 用户报的缺陷):「为什么背景是保存在本地而不是服务器!」
-- 原先主题与壁纸都只存在浏览器 localStorage 里:换设备/换浏览器就没了,而且**多账号
-- 共用一份**(键是全局常量 agentmail.background—— 同一台机器换账号,背景不跟着走。
--
-- 用**列**而不是一坨 JSON因为 blob GC 要一眼看出"这张图还有没有人用"
-- (见 repo.SweepUnreferencedBlobs 的引用源列表)。塞进 JSON 就得在 SQL 里解析 JSON
-- 两种方言写法还不一样。
CREATE TABLE IF NOT EXISTS user_appearance (
user_id TEXT NOT NULL,
theme TEXT NOT NULL DEFAULT 'system',
bg_kind TEXT NOT NULL DEFAULT 'none',
bg_preset_id TEXT NOT NULL DEFAULT '',
bg_dim INTEGER NOT NULL DEFAULT 12,
bg_blur INTEGER NOT NULL DEFAULT 4,
-- 壁纸图片内容寻址sha256文件本身在 blob 存储里
image_sha256 TEXT NOT NULL DEFAULT '',
image_type TEXT NOT NULL DEFAULT '',
image_bytes INTEGER NOT NULL DEFAULT 0,
updated_at DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%f','now')),
PRIMARY KEY (user_id)
);

View File

@ -0,0 +1,223 @@
package handler
import (
"errors"
"fmt"
"net/http"
"strconv"
"github.com/agentmail/gateway/internal/blob"
"github.com/agentmail/gateway/internal/config"
"github.com/agentmail/gateway/internal/middleware"
"github.com/agentmail/gateway/internal/models"
"github.com/agentmail/gateway/internal/repo"
)
/*
用户外观(主题 + 壁纸)—— /api/v1/me/appearance
# 为什么要有这套端点
2026-09-13 用户的质问:「为什么背景是保存在本地而不是服务器!」
当时的实情:主题与壁纸只写浏览器 localStorage于是换设备/换浏览器就没了,
更糟的是**多账号共用一份**(存储键是全局常量)—— 同一台机器换账号,背景不跟着走。
而 localStorage 只有 ~5MB 配额,客户端不得不把手机照片压到 2.4MB 以内(那套限制
本身就是"为本地存储而设计"的痕迹)。
放服务端之后:账号级、跟设备无关、多账号各自一份;客户端保留本地缓存用于秒开与离线。
# 图片为什么不塞进 JSON
图片走**内容寻址的 blob 存储**(与附件同一套),库里只存 sha256 —— 这样
`repo.SweepUnreferencedBlobs` 能一眼看出这张图还有没有人用(它读的就是这张表)。
塞进 JSON 的话 GC 就得在 SQL 里解析 JSON而两种方言写法还不一样。
# 鉴权
与其余 /me/* 一样要求登录cookie 或 Bearer。图片 GET 也要求 —— 客户端用
带认证的 fetch 取回来再转 object URL**不接受 `?token=`**(那会进日志与历史记录)。
*/
// GET /api/v1/me/appearance
func GetAppearance(w http.ResponseWriter, r *http.Request) {
user := middleware.GetUser(r)
if user == nil {
Error(w, http.StatusUnauthorized, "not authenticated")
return
}
a, exists, err := repo.GetAppearance(r.Context(), user.Username)
if err != nil {
Error(w, http.StatusInternalServerError, "Failed to load appearance")
return
}
JSON(w, http.StatusOK, appearanceResponse(a, exists))
}
func appearanceResponse(a models.Appearance, exists bool) map[string]any {
resp := map[string]any{
"theme": a.Theme,
"bg_kind": a.BgKind,
"bg_preset_id": a.BgPresetID,
"bg_dim": a.BgDim,
"bg_blur": a.BgBlur,
"has_image": a.ImageSHA256 != "",
"image_bytes": a.ImageBytes,
"saved": exists,
}
if a.UpdatedAt != "" {
resp["updated_at"] = a.UpdatedAt
}
if a.ImageSHA256 != "" {
// 给 URL 而不是把图塞进 JSON壁纸最大几 MB塞进去每次读设置都要传一遍。
resp["image_url"] = "/api/v1/me/appearance/image"
}
return resp
}
// PUT /api/v1/me/appearance —— 主题与背景档(不含图片)
func PutAppearance(w http.ResponseWriter, r *http.Request) {
user := middleware.GetUser(r)
if user == nil {
Error(w, http.StatusUnauthorized, "not authenticated")
return
}
var req models.Appearance
if !DecodeBody(w, r, &req) {
return
}
a := models.NormalizeAppearance(req)
if err := repo.UpsertAppearance(r.Context(), user.Username, a); err != nil {
Error(w, http.StatusInternalServerError, "Failed to save appearance")
return
}
saved, _, err := repo.GetAppearance(r.Context(), user.Username)
if err != nil {
Error(w, http.StatusInternalServerError, "Failed to reload appearance")
return
}
JSON(w, http.StatusOK, appearanceResponse(saved, true))
}
// POST /api/v1/me/appearance/image —— 上传壁纸multipart字段名 file
func UploadAppearanceImage(w http.ResponseWriter, r *http.Request) {
user := middleware.GetUser(r)
if user == nil {
Error(w, http.StatusUnauthorized, "not authenticated")
return
}
max := appearanceMaxBytes()
// 双层限制:外层卡整个请求体(含 multipart 边界blob.Put 卡文件内容本身。
// 少了外层,超大 multipart 头就能把内存拖满(与附件上传同一套做法)。
r.Body = http.MaxBytesReader(w, r.Body, max+1<<20)
if err := r.ParseMultipartForm(8 << 20); err != nil {
Error(w, http.StatusBadRequest, "解析 multipart 失败(是否超过大小上限?)")
return
}
defer func() {
if r.MultipartForm != nil {
r.MultipartForm.RemoveAll()
}
}()
file, header, err := r.FormFile("file")
if err != nil {
Error(w, http.StatusBadRequest, "缺少 file 字段")
return
}
defer file.Close()
name := sanitizeFilename(header.Filename)
ctype := detectContentType(header.Header.Get("Content-Type"), name)
// 只收图片:这个端点不是通用文件柜,而浏览器会把非图片当壁纸渲染成空白,
// 用户只会看到"设置了却什么也没变"。
if !isImageContentType(ctype) {
Error(w, http.StatusUnsupportedMediaType,
"壁纸必须是图片image/png、image/jpeg、image/webp、image/gif")
return
}
// 先落盘再入库(顺序不能反,否则会出现"库里有记录、磁盘没文件"的 404
sum, size, err := Blobs.Put(file, max)
if errors.Is(err, blob.ErrTooLarge) {
Error(w, http.StatusRequestEntityTooLarge,
fmt.Sprintf("壁纸超过上限 %.1f MB客户端会先压缩这个上限是兜底", float64(max)/(1<<20)))
return
}
if err != nil {
Error(w, http.StatusInternalServerError, "保存壁纸失败")
return
}
if err := repo.SetAppearanceImage(r.Context(), user.Username, sum, ctype, size); err != nil {
Error(w, http.StatusInternalServerError, "登记壁纸失败")
return
}
a, _, err := repo.GetAppearance(r.Context(), user.Username)
if err != nil {
Error(w, http.StatusInternalServerError, "Failed to reload appearance")
return
}
JSON(w, http.StatusOK, appearanceResponse(a, true))
}
// GET /api/v1/me/appearance/image —— 取壁纸本体
func GetAppearanceImage(w http.ResponseWriter, r *http.Request) {
user := middleware.GetUser(r)
if user == nil {
Error(w, http.StatusUnauthorized, "not authenticated")
return
}
a, _, err := repo.GetAppearance(r.Context(), user.Username)
if err != nil {
Error(w, http.StatusInternalServerError, "Failed to load appearance")
return
}
if a.ImageSHA256 == "" {
Error(w, http.StatusNotFound, "尚未设置壁纸")
return
}
f, err := Blobs.Open(a.ImageSHA256)
if err != nil {
// 库里说有条目、磁盘上却没有这不该发生GC 会把这张表当引用源)。
// 明确报错而不是回空图,否则客户端只会显示"设置了但没效果"。
Error(w, http.StatusNotFound, "壁纸文件缺失")
return
}
defer f.Close()
w.Header().Set("Content-Type", a.ImageType)
w.Header().Set("Content-Length", strconv.FormatInt(a.ImageBytes, 10))
// 内容寻址 ⇒ 同一 sha256 的内容永不改变,可以长缓存;换图会换 URL 语义
// (客户端拿到的 image_url 不变,所以这里只做短缓存,避免缓存穿透到"旧图")。
w.Header().Set("Cache-Control", "private, max-age=60")
_, _ = f.WriteTo(w)
}
// DELETE /api/v1/me/appearance/image
func DeleteAppearanceImage(w http.ResponseWriter, r *http.Request) {
user := middleware.GetUser(r)
if user == nil {
Error(w, http.StatusUnauthorized, "not authenticated")
return
}
if err := repo.ClearAppearanceImage(r.Context(), user.Username); err != nil {
Error(w, http.StatusInternalServerError, "Failed to clear image")
return
}
// blob 文件不在这里删:内容寻址可能被别的记录引用,交给 SweepUnreferencedBlobs。
JSON(w, http.StatusOK, map[string]any{"has_image": false})
}
func appearanceMaxBytes() int64 {
if config.C != nil && config.C.MaxAppearanceBytes > 0 {
return config.C.MaxAppearanceBytes
}
return 4 << 20
}
func isImageContentType(ct string) bool {
switch ct {
case "image/png", "image/jpeg", "image/webp", "image/gif":
return true
}
return false
}

View File

@ -0,0 +1,360 @@
package handler
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"github.com/agentmail/gateway/internal/blob"
"github.com/agentmail/gateway/internal/config"
"github.com/agentmail/gateway/internal/db"
"github.com/agentmail/gateway/internal/middleware"
"github.com/agentmail/gateway/internal/models"
"github.com/agentmail/gateway/internal/repo"
)
/*
用户外观(主题 + 壁纸)落在服务端 —— 2026-09-14。
用户原话:「为什么背景是保存在本地而不是服务器!」当时的实情是主题与壁纸只写
localStorage换设备就没了而且**多账号共用一份**(键是全局常量)。这组判据钉住
四件事:
1. 存下来了、读得回来(账号级);
2. ★ 两个账号互不干扰(就是上面那条缺陷);
3. 图片走 blob**换设备能拿到**GET image 真返回字节);
4. ★ blob GC 不会把壁纸当孤儿删掉 —— 我在实现前先查了 GC它只认
attachments / calendar_attachments漏了那张表就会表现为"图 404、设置却显示已设置"。
*/
// setupAppearanceDB 起一个带真实用户与 blob 目录的测试库。
func setupAppearanceDB(t *testing.T) {
t.Helper()
dir := t.TempDir()
if err := db.Connect(context.Background(), "sqlite://"+filepath.Join(dir, "t.db")); err != nil {
t.Fatalf("connect: %v", err)
}
if err := db.Migrate(context.Background()); err != nil {
t.Fatalf("migrate: %v", err)
}
// 两个用户:多账号隔离是这组判据的重点
for _, u := range []string{"alice", "bob"} {
if _, err := db.DB.ExecContext(context.Background(),
`INSERT INTO users (username, password_hash, role) VALUES ($1, 'x', 'user')`, u); err != nil {
t.Fatalf("建用户 %s: %v", u, err)
}
}
// 真实 blob 目录(壁纸上传统统落到这里)
Blobs = mustBlobStore(t, filepath.Join(dir, "blobs"))
t.Cleanup(func() { db.Close() })
}
func mustBlobStore(t *testing.T, root string) *blob.Store {
t.Helper()
st, err := blob.New(root)
if err != nil {
t.Fatalf("blob store: %v", err)
}
return st
}
func asUser(r *http.Request, username string) *http.Request {
ctx := context.WithValue(r.Context(), middleware.UserKey, &models.User{Username: username})
return r.WithContext(ctx)
}
func putAppearance(t *testing.T, username string, body map[string]any) *httptest.ResponseRecorder {
t.Helper()
raw, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPut, "/api/v1/me/appearance", bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
resp := httptest.NewRecorder()
PutAppearance(resp, asUser(req, username))
return resp
}
func getAppearance(t *testing.T, username string) map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/api/v1/me/appearance", nil)
resp := httptest.NewRecorder()
GetAppearance(resp, asUser(req, username))
if resp.Code != http.StatusOK {
t.Fatalf("GET appearance = %d%s", resp.Code, resp.Body.String())
}
var out map[string]any
if err := json.Unmarshal(resp.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
return out
}
/** 一张最小的合法 PNG1×1 透明)。 */
func pngBytes() []byte {
return []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41,
0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00,
0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00,
0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
0x42, 0x60, 0x82,
}
}
func uploadAppearanceImage(t *testing.T, username string, content []byte, filename, ctype string) *httptest.ResponseRecorder {
t.Helper()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
fw, err := mw.CreatePart(map[string][]string{
"Content-Disposition": {fmt.Sprintf(`form-data; name="file"; filename="%s"`, filename)},
"Content-Type": {ctype},
})
if err != nil {
t.Fatal(err)
}
if _, err := fw.Write(content); err != nil {
t.Fatal(err)
}
mw.Close()
req := httptest.NewRequest(http.MethodPost, "/api/v1/me/appearance/image", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
resp := httptest.NewRecorder()
UploadAppearanceImage(resp, asUser(req, username))
return resp
}
func TestAppearanceRoundTrip(t *testing.T) {
setupAppearanceDB(t)
// 没设置过:默认值 + saved=false"从没设置过"不是错误,不该 404
fresh := getAppearance(t, "alice")
if fresh["saved"] != false {
t.Fatalf("没设置过时 saved 应为 false实际 %v", fresh["saved"])
}
if fresh["bg_kind"] != "none" {
t.Fatalf("默认背景档应为 none实际 %v", fresh["bg_kind"])
}
resp := putAppearance(t, "alice", map[string]any{
"theme": "dark", "bg_kind": "preset", "bg_preset_id": "aurora", "bg_dim": 30, "bg_blur": 6,
})
if resp.Code != http.StatusOK {
t.Fatalf("PUT = %d%s", resp.Code, resp.Body.String())
}
got := getAppearance(t, "alice")
if got["theme"] != "dark" || got["bg_kind"] != "preset" || got["bg_dim"].(float64) != 30 {
t.Fatalf("读回的值不对:%v", got)
}
}
// ★ 多账号各一份 —— 这是"放本地"时最直接的缺陷(同一台机器换账号背景不跟着走)。
func TestAppearanceIsPerAccount(t *testing.T) {
setupAppearanceDB(t)
putAppearance(t, "alice", map[string]any{"theme": "dark", "bg_kind": "preset", "bg_preset_id": "ocean"})
putAppearance(t, "bob", map[string]any{"theme": "light", "bg_kind": "none"})
a, b := getAppearance(t, "alice"), getAppearance(t, "bob")
if a["bg_preset_id"] != "ocean" || a["theme"] != "dark" {
t.Fatalf("alice 的外观被串了:%v", a)
}
if b["theme"] != "light" {
t.Fatalf("★ bob 的外观受 alice 影响:%v", b)
}
}
// 越界/非法值必须被夹住:这些值最终会写进 CSS 变量,越界会让界面不可读。
func TestAppearanceNormalizesBadInput(t *testing.T) {
setupAppearanceDB(t)
putAppearance(t, "alice", map[string]any{
"theme": "neon", "bg_kind": "video", "bg_dim": 999, "bg_blur": -5,
})
got := getAppearance(t, "alice")
if got["theme"] != "system" || got["bg_kind"] != "none" {
t.Fatalf("认不出的 theme/kind 应退回默认,实际 %v / %v", got["theme"], got["bg_kind"])
}
if got["bg_dim"].(float64) != 90 || got["bg_blur"].(float64) != 0 {
t.Fatalf("dim/blur 应被夹进范围,实际 %v / %v", got["bg_dim"], got["bg_blur"])
}
}
// 壁纸本体:上传后**换设备也能拿到同样的字节**(这就是"放服务器"的意义)。
func TestAppearanceImageUploadAndFetch(t *testing.T) {
setupAppearanceDB(t)
data := pngBytes()
resp := uploadAppearanceImage(t, "alice", data, "wall.png", "image/png")
if resp.Code != http.StatusOK {
t.Fatalf("上传 = %d%s", resp.Code, resp.Body.String())
}
got := getAppearance(t, "alice")
if got["has_image"] != true {
t.Fatalf("上传后 has_image 应为 true%v", got)
}
if got["image_url"] != "/api/v1/me/appearance/image" {
t.Fatalf("应给出 image_url实际 %v", got["image_url"])
}
req := httptest.NewRequest(http.MethodGet, "/api/v1/me/appearance/image", nil)
rec := httptest.NewRecorder()
GetAppearanceImage(rec, asUser(req, "alice"))
if rec.Code != http.StatusOK {
t.Fatalf("取图 = %d", rec.Code)
}
if !bytes.Equal(rec.Body.Bytes(), data) {
t.Fatalf("取回的字节与上传的不一致(%d vs %d 字节)", rec.Body.Len(), len(data))
}
if ct := rec.Header().Get("Content-Type"); ct != "image/png" {
t.Fatalf("Content-Type = %q", ct)
}
}
// 非图片要当场拒(浏览器会把非图片渲染成空白,用户只会看到"设置了却没变化")。
func TestAppearanceImageRejectsNonImage(t *testing.T) {
setupAppearanceDB(t)
resp := uploadAppearanceImage(t, "alice", []byte("#!/bin/sh\necho hi\n"), "evil.sh", "text/x-shellscript")
if resp.Code != http.StatusUnsupportedMediaType {
t.Fatalf("非图片应为 415实际 %d%s", resp.Code, resp.Body.String())
}
if getAppearance(t, "alice")["has_image"] != false {
t.Fatal("被拒的上传不该留下记录")
}
}
// 超过上限:明确 413不静默截断截断的图会以损坏文件的形式存下来
func TestAppearanceImageSizeLimit(t *testing.T) {
setupAppearanceDB(t)
// config.C 由 main 在启动时装载,单测里可能是 nil —— 先保证有一个可改的实例,
// 跑完再复原(改全局是有代价的,所以只在这条判据里、且立刻还原)。
if config.C == nil {
config.C = &config.Config{}
defer func() { config.C = nil }()
}
saved := config.C.MaxAppearanceBytes
config.C.MaxAppearanceBytes = 1024
defer func() { config.C.MaxAppearanceBytes = saved }()
big := append(pngBytes(), bytes.Repeat([]byte{0}, 4096)...)
resp := uploadAppearanceImage(t, "alice", big, "big.png", "image/png")
if resp.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("超限应为 413实际 %d%s", resp.Code, resp.Body.String())
}
}
// 删除壁纸:记录清空,且读图变 404。
func TestAppearanceImageDelete(t *testing.T) {
setupAppearanceDB(t)
if resp := uploadAppearanceImage(t, "alice", pngBytes(), "w.png", "image/png"); resp.Code != http.StatusOK {
t.Fatalf("上传 = %d", resp.Code)
}
req := httptest.NewRequest(http.MethodDelete, "/api/v1/me/appearance/image", nil)
rec := httptest.NewRecorder()
DeleteAppearanceImage(rec, asUser(req, "alice"))
if rec.Code != http.StatusOK {
t.Fatalf("删除 = %d", rec.Code)
}
if getAppearance(t, "alice")["has_image"] != false {
t.Fatal("删除后 has_image 应为 false")
}
req2 := httptest.NewRequest(http.MethodGet, "/api/v1/me/appearance/image", nil)
rec2 := httptest.NewRecorder()
GetAppearanceImage(rec2, asUser(req2, "alice"))
if rec2.Code != http.StatusNotFound {
t.Fatalf("删除后取图应为 404实际 %d", rec2.Code)
}
}
// 未登录一律 401壁纸是个人内容不能匿名读
func TestAppearanceRequiresAuth(t *testing.T) {
setupAppearanceDB(t)
for name, fn := range map[string]func(http.ResponseWriter, *http.Request){
"GET": GetAppearance, "PUT": PutAppearance,
"POST image": UploadAppearanceImage, "GET image": GetAppearanceImage,
"DELETE image": DeleteAppearanceImage,
} {
method := http.MethodGet
if name == "PUT" {
method = http.MethodPut
} else if name == "POST image" {
method = http.MethodPost
} else if name == "DELETE image" {
method = http.MethodDelete
}
rec := httptest.NewRecorder()
fn(rec, httptest.NewRequest(method, "/api/v1/me/appearance", nil))
if rec.Code != http.StatusUnauthorized {
t.Errorf("%s 未登录应为 401实际 %d", name, rec.Code)
}
}
}
// ★ 壁纸不能被 blob GC 当成孤儿删掉。
//
// 实现前特意先读了 SweepUnreferencedBlobs它只认 attachments / calendar_attachments
// 两张引用表。漏掉 user_appearance 的话,壁纸文件会在下一次 GC 时消失,而库里那行
// 还在 —— 表现为"图 404、设置却显示已设置"。
func TestAppearanceImageSurvivesBlobGC(t *testing.T) {
setupAppearanceDB(t)
data := pngBytes()
if resp := uploadAppearanceImage(t, "alice", data, "wall.png", "image/png"); resp.Code != http.StatusOK {
t.Fatalf("上传 = %d", resp.Code)
}
sum := sha256.Sum256(data)
sha := hex.EncodeToString(sum[:])
if !Blobs.Exists(sha) {
t.Fatal("上传后 blob 应当存在")
}
// minAge=0让 GC 立刻把"无人引用"的文件当孤儿(正是要验的窗口)
if _, err := repo.SweepUnreferencedBlobs(context.Background(), Blobs, 0); err != nil {
t.Fatalf("GC: %v", err)
}
if !Blobs.Exists(sha) {
t.Fatal("★ 壁纸被 GC 删掉了 —— SweepUnreferencedBlobs 的引用源少了 user_appearance")
}
// 反向对照:一个谁都没引用的文件必须被清掉,否则说明 GC 其实没在干活
// (这条判据就没有分辨率 —— "壁纸还在"可能只是因为 GC 根本没跑)。
// 孤儿用 store 自己的 Put 造:手拼路径不合 blob 的布局,会得到一个假失败。
orphanSum, _, err := Blobs.Put(bytes.NewReader([]byte("nobody references me")), 1024)
if err != nil {
t.Fatal(err)
}
if !Blobs.Exists(orphanSum) {
t.Fatal("孤儿文件应当先被写进去")
}
if _, err := repo.SweepUnreferencedBlobs(context.Background(), Blobs, 0); err != nil {
t.Fatalf("GC(2): %v", err)
}
if Blobs.Exists(orphanSum) {
t.Fatal("孤儿文件应当被清掉否则这条判据无法区分「被保护」与「GC 没跑」)")
}
if !Blobs.Exists(sha) {
t.Fatal("第二轮 GC 之后壁纸仍必须存在")
}
}
// 读图端点必须原样吐字节(不能只回长度就完事)。
func TestAppearanceImageServesBytes(t *testing.T) {
setupAppearanceDB(t)
data := pngBytes()
uploadAppearanceImage(t, "alice", data, "w.png", "image/png")
req := httptest.NewRequest(http.MethodGet, "/api/v1/me/appearance/image", nil)
rec := httptest.NewRecorder()
GetAppearanceImage(rec, asUser(req, "alice"))
body, _ := io.ReadAll(rec.Body)
if !bytes.Equal(body, data) {
t.Fatalf("取回 %d 字节,期望 %d", len(body), len(data))
}
}

View File

@ -138,21 +138,21 @@ func (u User) CanUsePath(path string) bool {
// Mail 是会话中的一封邮件
type Mail struct {
ID uuid.UUID `json:"mail_id"`
SessionID uuid.UUID `json:"session_id"`
ParentMailID *uuid.UUID `json:"parent_mail_id"`
FromName string `json:"from_name"`
FromWorkspace string `json:"from_workspace"`
ToName string `json:"to_name"`
ToWorkspace string `json:"to_workspace"`
CCList []Address `json:"cc_list"`
Subject string `json:"subject"`
Body string `json:"body"`
MailType string `json:"mail_type"`
PermOptions []string `json:"permission_options,omitempty"`
PermResult string `json:"permission_result,omitempty"`
PermissionKind string `json:"permission_kind,omitempty"`
PermissionMulti bool `json:"permission_multi_select,omitempty"`
ID uuid.UUID `json:"mail_id"`
SessionID uuid.UUID `json:"session_id"`
ParentMailID *uuid.UUID `json:"parent_mail_id"`
FromName string `json:"from_name"`
FromWorkspace string `json:"from_workspace"`
ToName string `json:"to_name"`
ToWorkspace string `json:"to_workspace"`
CCList []Address `json:"cc_list"`
Subject string `json:"subject"`
Body string `json:"body"`
MailType string `json:"mail_type"`
PermOptions []string `json:"permission_options,omitempty"`
PermResult string `json:"permission_result,omitempty"`
PermissionKind string `json:"permission_kind,omitempty"`
PermissionMulti bool `json:"permission_multi_select,omitempty"`
// PermissionExpiresAt 是这条权限待办的失效时刻(仅仍未决策的 permission_request 有)。
//
@ -162,9 +162,9 @@ type Mail struct {
//
// 由读路径按 CreatedAt 推导后填充,**不落库** —— 它是时间的函数,存下来会失真。
PermissionExpiresAt *time.Time `json:"permission_expires_at,omitempty"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
HopLimit int `json:"hop_limit"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
HopLimit int `json:"hop_limit"`
SessionAlias string `json:"session_alias,omitempty"`
@ -223,12 +223,12 @@ type Mail struct {
// PermissionRequest 是 Agent 向人类发起的权限请求
type PermissionRequest struct {
ID uuid.UUID `json:"request_id"`
MailID uuid.UUID `json:"mail_id"`
SessionID uuid.UUID `json:"session_id"`
AgentName string `json:"agent_name"`
Question string `json:"question"`
Options []string `json:"options"`
ID uuid.UUID `json:"request_id"`
MailID uuid.UUID `json:"mail_id"`
SessionID uuid.UUID `json:"session_id"`
AgentName string `json:"agent_name"`
Question string `json:"question"`
Options []string `json:"options"`
Context string `json:"context"`
Kind string `json:"kind"` // permission | question
MultiSelect bool `json:"multi_select"` // 仅 question 使用
@ -319,3 +319,59 @@ type Attachment struct {
SHA256 string `json:"sha256"`
CreatedAt time.Time `json:"created_at"`
}
// Appearance 是**账号级**的用户外观(主题 + 壁纸)。
//
// 背景的取值范围刻意收窄kind 三值、dim/blur 有上限),因为服务端要
// 兜住"客户端被改坏"的情况:这些值最终会写进 CSS 变量,越界值会让界面不可读。
type Appearance struct {
Theme string `json:"theme"` // light / dark / system
BgKind string `json:"bg_kind"` // none / preset / image
BgPresetID string `json:"bg_preset_id"`
BgDim int `json:"bg_dim"` // 遮罩强度 %0-90
BgBlur int `json:"bg_blur"` // 照片模糊 px0-40
ImageSHA256 string `json:"-"`
ImageType string `json:"-"`
ImageBytes int64 `json:"image_bytes"`
UpdatedAt string `json:"updated_at,omitempty"`
}
// DefaultAppearance 是"从没设置过"时的外观 —— 与客户端 backgroundStore /
// themeStore 的默认值一致dim 12、blur 4 是 2026-09-13 壁纸修复后的取值)。
func DefaultAppearance() Appearance {
return Appearance{Theme: "system", BgKind: "none", BgPresetID: "aurora", BgDim: 12, BgBlur: 4}
}
// NormalizeAppearance 把客户端传来的值夹进合法范围。
// 认不出的 kind/theme 一律退回默认 —— 静默接受非法值会让界面白屏且无从排查。
func NormalizeAppearance(a Appearance) Appearance {
switch a.Theme {
case "light", "dark", "system":
default:
a.Theme = "system"
}
switch a.BgKind {
case "none", "preset", "image":
default:
a.BgKind = "none"
}
if a.BgPresetID == "" {
a.BgPresetID = "aurora"
}
if len(a.BgPresetID) > 64 {
a.BgPresetID = a.BgPresetID[:64]
}
if a.BgDim < 0 {
a.BgDim = 0
}
if a.BgDim > 90 {
a.BgDim = 90
}
if a.BgBlur < 0 {
a.BgBlur = 0
}
if a.BgBlur > 40 {
a.BgBlur = 40
}
return a
}

View File

@ -0,0 +1,70 @@
package repo
import (
"context"
"database/sql"
"errors"
"github.com/agentmail/gateway/internal/db"
"github.com/agentmail/gateway/internal/models"
)
// 用户外观(主题 + 壁纸)的读写。
//
// 为什么放服务端:原先主题与壁纸只存在浏览器 localStorage 里,换设备/换浏览器就没了,
// 而且**多账号共用一份**(键是全局常量)—— 同一台机器换账号背景不跟着走。
// 语义是**账号级**(跟账号走,不跟设备走)。
// GetAppearance 读某个用户的外观。没有记录时返回**默认值 + false**(不是错误):
// 「从没设置过」是正常状态,调用方不该为此处理 404。
func GetAppearance(ctx context.Context, userID string) (models.Appearance, bool, error) {
a := models.DefaultAppearance()
var updated sql.NullString
err := db.DB.QueryRowContext(ctx, `
SELECT theme, bg_kind, bg_preset_id, bg_dim, bg_blur,
image_sha256, image_type, image_bytes, CAST(updated_at AS TEXT)
FROM user_appearance WHERE user_id = $1`, userID).
Scan(&a.Theme, &a.BgKind, &a.BgPresetID, &a.BgDim, &a.BgBlur,
&a.ImageSHA256, &a.ImageType, &a.ImageBytes, &updated)
if errors.Is(err, sql.ErrNoRows) {
return models.DefaultAppearance(), false, nil
}
if err != nil {
return models.Appearance{}, false, err
}
a.UpdatedAt = updated.String
return a, true, nil
}
// UpsertAppearance 写入主题与背景档(不含图片本身,图片见 SetAppearanceImage
func UpsertAppearance(ctx context.Context, userID string, a models.Appearance) error {
_, err := db.DB.ExecContext(ctx, `
INSERT INTO user_appearance (user_id, theme, bg_kind, bg_preset_id, bg_dim, bg_blur, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, NOW())
ON CONFLICT (user_id) DO UPDATE SET
theme = $2, bg_kind = $3, bg_preset_id = $4, bg_dim = $5, bg_blur = $6, updated_at = NOW()`,
userID, a.Theme, a.BgKind, a.BgPresetID, a.BgDim, a.BgBlur)
return err
}
// SetAppearanceImage 记下这张壁纸(文件已落 blob 存储)。
func SetAppearanceImage(ctx context.Context, userID, sha256, contentType string, sizeBytes int64) error {
_, err := db.DB.ExecContext(ctx, `
INSERT INTO user_appearance (user_id, image_sha256, image_type, image_bytes, updated_at)
VALUES ($1, $2, $3, $4, NOW())
ON CONFLICT (user_id) DO UPDATE SET
image_sha256 = $2, image_type = $3, image_bytes = $4, updated_at = NOW()`,
userID, sha256, contentType, sizeBytes)
return err
}
// ClearAppearanceImage 清掉壁纸记录。
//
// **不删 blob 文件**:内容寻址意味着同一张图可能被别的记录引用,而且删除是不可逆的
// —— 交给 SweepUnreferencedBlobs 在确认无人引用后再收(它会读这张表)。
func ClearAppearanceImage(ctx context.Context, userID string) error {
_, err := db.DB.ExecContext(ctx, `
UPDATE user_appearance SET image_sha256 = '', image_type = '', image_bytes = 0, updated_at = NOW()
WHERE user_id = $1`, userID)
return err
}

View File

@ -276,6 +276,10 @@ func SweepUnreferencedBlobs(ctx context.Context, blobs BlobLister, minAge time.D
for _, q := range []string{
`SELECT sha256 FROM attachments`,
`SELECT sha256 FROM calendar_attachments`,
// 用户壁纸也是 blob 存储里的内容文件。漏掉这一张表,用户的壁纸会在
// 下一次 GC 时被当成"没人引用的孤儿"删掉 —— 而库里那行还在,
// 表现为"图片 404、设置却显示已设置"2026-09-14 新增功能时特意先查了 GC
`SELECT image_sha256 FROM user_appearance WHERE image_sha256 <> ''`,
} {
rows, qErr := db.DB.QueryContext(ctx, q)
if qErr != nil {