WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
feat: frosted-glass theme supports video wallpapers
zwy29907ebefbff
diff --git a/README.md b/README.mdindex 62877f4..fd5eb8e 100644--- a/README.md+++ b/README.md@@ -26,7 +26,7 @@ CodeBuddy 支持范围为 **Electron 智能体窗口**,不包含 VS Code 编- **自动化任务**:从 GitHub / Gitee 公开仓库发现并导入任务,或用自然语言让 WorkBuddy 创建任务;支持编辑、手动、事件和定时触发,以及运行日志、停止任务和 JSON / ZIP 导出。- **权限弹窗免打扰**:真正的零决策弹窗弹出,可以放心开启任务后睡觉。- **暂存提示词**:输入框边上一键把草稿「暂存」到待发送队列——图片 / 文件 / 引用原样保留,择机发送。-- **切换精美主题**:WorkBuddy 的「接管主题」提供跟随系统、浅色、深色、护眼绿、赛博紫、毛玻璃六种外观;「跟随系统」监听操作系统的深浅色模式变化自动切换,毛玻璃支持预设和自定义壁纸,关闭接管后恢复客户端原生主题。+- **切换精美主题**:WorkBuddy 的「接管主题」提供跟随系统、浅色、深色、护眼绿、赛博紫、毛玻璃六种外观;「跟随系统」监听操作系统的深浅色模式变化自动切换,毛玻璃支持预设壁纸、自定义图片壁纸和视频壁纸(MP4 / WebM,静音循环、窗口切后台自动暂停),关闭接管后恢复客户端原生主题。- **账号间会话迁移**:自动或手动跨账号复制会话,跨账号继续接龙。- **会话分支**:在「增强」页开启后,任意一条回复都能从此处开始新会话——复制到该条回复为止的聊天内容,原会话保持不变,可在当前工作区继续聊。- **模型切换更便捷**:解决 WorkBuddy 不支持添加多个同名模型的问题。diff --git a/README_en.md b/README_en.mdindex c9c91a1..3d48072 100644--- a/README_en.md+++ b/README_en.md@@ -52,7 +52,7 @@ CodeBuddy support targets its **Electron agent window**, not the VS Code editor- **Automation tasks:** discover and import tasks from public GitHub and Gitee repositories, or describe what you need and let WorkBuddy create a task. Supports manual, event, and scheduled triggers, run logs, stopping tasks, and JSON / ZIP export.- **Quiet approval mode:** automatically handle supported permission prompts while you are away.- **Stash prompts:** send drafts to WorkBuddy's pending message queue while preserving images, files, and quotes for later use.-- **Themes:** WorkBuddy’s Manage theme switch offers Follow system, Light, Dark, Eye-care green, Cyber purple, and Frosted glass. “Follow system” tracks the operating system’s dark/light mode and switches automatically. Frosted glass supports preset and custom wallpapers; turning management off restores the client’s native appearance.+- **Themes:** WorkBuddy’s Manage theme switch offers Follow system, Light, Dark, Eye-care green, Cyber purple, and Frosted glass. “Follow system” tracks the operating system’s dark/light mode and switches automatically. Frosted glass supports preset wallpapers, custom image wallpapers, and video wallpapers (MP4 / WebM, muted loop, paused while the window is in the background); turning management off restores the client’s native appearance.- **Session migration:** copy sessions between accounts automatically or manually and continue working where you left off.- **Session branching:** once enabled under Enhance, any reply can start a new conversation that keeps the chat up to that reply, while the original conversation stays untouched.- **Model tools:** manage and switch models more easily, including multiple configurations with the same model name.diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 205f5bc..c0c602e 100644--- a/scripts/build-mac-dmg.sh+++ b/scripts/build-mac-dmg.sh@@ -65,7 +65,7 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"echo "==> 应用图标已同步(背景 #e1e1e1)"# 2) 覆盖运行时代码和主题配置,保留 launcher/Info.plist/壁纸/node_modules/theme-audit.js。-for f in daemon.js account-identity.js session-copy-error.js persona.js markdown-preview.js renderer-api-bridge.js codebuddy-native.js codebuddy-native-recovery.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-account-sync.js official-automation-sync.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js wallpaper-rotation.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js client-launch-settings.js client-temp.js workbuddy-launch-env.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do+for f in daemon.js account-identity.js session-copy-error.js persona.js markdown-preview.js renderer-api-bridge.js codebuddy-native.js codebuddy-native-recovery.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-account-sync.js official-automation-sync.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js wallpaper-rotation.js wallpaper-video.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js client-launch-settings.js client-temp.js workbuddy-launch-env.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"done# Theme tokens are source code too; the reusable shell may contain older colors.diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 7d1b99d..5d5039d 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -36,6 +36,11 @@ const {createCodeBuddyFiles} = require('./codebuddy-files.js');const { createAccountCreditCache } = require('./account-credit-cache.js');const { spawn, spawnSync, execFile } = require('child_process');const { createWallpaperRotation, updateWallpaperInRenderer, pickWallpaperDirectory } = require('./wallpaper-rotation');+const {+ VIDEO_MAX_BYTES, VIDEO_HEAD_BYTES, VIDEO_LAYER_CSS,+ sniffVideo, resolveVideoFile, videoRootBackground,+ updateVideoInRenderer, disposeVideoInRenderer,+} = require('./wallpaper-video');const { readClientLaunchSettings, setClientLaunchSettings, getClientLaunchArgs } = require('./client-launch-settings.js');const { getWorkBuddyLaunchEnv } = require('./workbuddy-launch-env.js');const { inspectClientTemp, requestClientTempCleanup, runPendingClientTempCleanup } = require('./client-temp.js');@@ -537,9 +542,11 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.2.65:兼容空会话同步、自定义模型和重定向备份目录,工作目录恢复退避重试。// 1.2.66:刷新凭据按原信封加密保存,同账号刷新去重,过期账号保留手动切换。// 1.2.67:Windows 重启 GUI 客户端时不再请求隐藏主窗口,与冷启动保持一致。+// 1.2.69:毛玻璃主题支持视频壁纸(MP4 / WebM),与图片壁纸共用蒙版与背景毛玻璃。// #507: explicit cleanup of old Windows client temp files, only before a verified cold launch.-const DAEMON_VERSION = '1.2.80';-const DAEMON_BUILD_ID = 'release-1.2.80-session-sync-shared-windows-target';+// 1.2.81:在共享目标分支加入视频壁纸及失败重试、主题路径边界修复。+const DAEMON_VERSION = '1.2.81';+const DAEMON_BUILD_ID = 'release-1.2.81-video-wallpaper';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -8935,6 +8942,174 @@ function readBackgroundBlur() {return blur;}+/** 当前挂载在页面里的视频壁纸标识(主题 + 文件名 + 大小 + 修改时间)。+ * 空字符串表示「页面里没有视频层」,用来决定下一次应用要不要多跑一次清理。 */+let lastVideoKey = '';++/** 把视频壁纸装进渲染进程。key 命中时渲染进程直接复用已加载的 blob。 */+async function applyVideoWallpaperByCdp(video, id) {+ if (!cdp.connected) return false;+ const key = [id, video.name, video.size, Math.round(video.mtime)].join(':');+ try {+ const r = await cdpSend('Runtime.evaluate', {+ expression: '(' + updateVideoInRenderer.toString() + ')(' + JSON.stringify({+ // v= 让 daemon 与浏览器缓存都以文件修改时间为准,换视频后不会放旧片+ url: `http://${HOST}:${ACTUAL_PORT}/api/theme-video?id=${encodeURIComponent(id)}&v=${Math.round(video.mtime)}`,+ token: API_TOKEN,+ key,+ // 视频层自带样式表,不随主题样式重写+ css: VIDEO_LAYER_CSS,+ }) + ')',+ awaitPromise: true, returnByValue: true, timeout: 30000,+ });+ const ok = !!(r && r.result && r.result.value === true);+ if (ok) lastVideoKey = key;+ else log('[theme] 视频壁纸未能挂载: ' + key);+ return ok;+ } catch (e) {+ log('[theme] 视频壁纸应用失败: ' + (e && e.message));+ return false;+ }+}++/** 摘掉视频层(切回图片壁纸 / 关闭接管 / 该主题没有视频)。 */+async function disposeVideoWallpaperByCdp() {+ lastVideoKey = '';+ if (!cdp.connected) return false;+ try {+ await cdpSend('Runtime.evaluate', {+ expression: '(' + disposeVideoInRenderer.toString() + ')()',+ returnByValue: true, timeout: 5000,+ });+ return true;+ } catch (_) {+ return false;+ }+}++/** 主题元数据文件位置:兼容 themes/<id>.json(扁平)与 themes/<id>/theme.json 两种布局。 */+function themeMetaFile(rawId) {+ const safeId = String(rawId || '').replace(/[^A-Za-z0-9_-]/g, '_');+ if (!safeId) return null;+ const dir = path.join(THEMES_DIR, safeId);+ const flat = path.join(THEMES_DIR, safeId + '.json');+ return { id: safeId, dir, file: fs.existsSync(flat) ? flat : path.join(dir, 'theme.json') };+}++/** 把请求体流式落盘(不整段进内存:视频可以有几十上百 MB)。返回文件头用于格式校验。 */+function streamBodyToFile(req, dest, maxBytes) {+ return new Promise((resolve, reject) => {+ const headChunks = [];+ let headBytes = 0;+ let size = 0;+ let failure = null;+ let settled = false;+ const finish = (fn, arg) => { if (!settled) { settled = true; fn(arg); } };+ const stream = fs.createWriteStream(dest, { mode: 0o600 });+ stream.on('error', (e) => { failure = failure || e; });+ req.on('data', (chunk) => {+ size += chunk.length;+ if (size > maxBytes) {+ failure = failure || new Error('视频不能超过 ' + Math.round(maxBytes / 1048576) + 'MB');+ req.destroy();+ stream.destroy();+ return;+ }+ if (headBytes < VIDEO_HEAD_BYTES) {+ const take = chunk.subarray(0, VIDEO_HEAD_BYTES - headBytes);+ headChunks.push(take);+ headBytes += take.length;+ }+ if (failure) return;+ stream.write(chunk);+ });+ req.on('aborted', () => {+ failure = failure || new Error('视频上传已中断');+ stream.destroy();+ });+ req.on('error', (e) => { failure = failure || e; stream.destroy(); });+ req.on('end', () => {+ stream.end(() => {+ if (failure) { fs.promises.rm(dest, { force: true }).catch(() => {}); return finish(reject, failure); }+ finish(resolve, { size, head: Buffer.concat(headChunks) });+ });+ });+ // req.destroy() 之后 end 不一定触发,用它兜住超限/中断的分支+ stream.on('close', () => {+ if (failure) { fs.promises.rm(dest, { force: true }).catch(() => {}); finish(reject, failure); }+ });+ });+}++async function handleThemeVideoUpload(req, res, url) {+ const meta = themeMetaFile(url.searchParams.get('id'));+ if (!meta) return json(res, 400, { ok: false, error: '缺少主题 id' });+ if (['default', 'dark', 'light', 'system'].includes(meta.id)) {+ return json(res, 400, { ok: false, error: '官方浅色/深色主题不支持壁纸,请先切到毛玻璃主题' });+ }+ const existing = getTheme(meta.id);+ if (!existing || !existing.colors) return json(res, 400, { ok: false, error: '主题不存在: ' + meta.id });+ const declared = Number(req.headers['content-length'] || 0);+ if (!Number.isFinite(declared) || declared <= 0) return json(res, 411, { ok: false, error: '缺少 Content-Length' });+ if (declared > VIDEO_MAX_BYTES) return json(res, 413, { ok: false, error: '视频不能超过 ' + Math.round(VIDEO_MAX_BYTES / 1048576) + 'MB' });++ fs.mkdirSync(meta.dir, { recursive: true });+ const tmp = path.join(meta.dir, 'upload-' + Date.now().toString(36) + '.part');+ const { size, head } = await streamBodyToFile(req, tmp, VIDEO_MAX_BYTES);+ // 格式只认文件头:前端给的文件名/类型都可以伪造,落盘扩展名必须由魔数决定+ const format = sniffVideo(head);+ if (!format) {+ await fs.promises.rm(tmp, { force: true }).catch(() => {});+ return json(res, 400, { ok: false, error: '仅支持 MP4 / WebM 视频' });+ }+ const fileName = 'background.' + format.ext;+ for (const ext of ['mp4', 'webm']) {+ const old = path.join(meta.dir, 'background.' + ext);+ try { if (fs.existsSync(old)) fs.rmSync(old, { force: true }); } catch (_) {}+ }+ fs.renameSync(tmp, path.join(meta.dir, fileName));+ writeThemeMeta(meta, { video: fileName }, existing);+ try {+ fs.writeFileSync(path.join(DATA_DIR, 'current-theme.json'), JSON.stringify({ id: meta.id, at: new Date().toISOString() }, null, 2));+ } catch (_) {}+ // 视频与图片随机轮换互斥:抢的是同一层背景+ await wallpaperRotation.configure({ mode: 'manual' }).catch(() => {});+ log(`[theme] 上传视频壁纸 -> ${meta.id}/${fileName} (${size}B)`);+ const applied = await applyThemeByCdp(meta.id).then(() => true).catch(() => false);+ return json(res, 200, { ok: true, video: fileName, size, mime: format.mime, applied, id: meta.id });+}++async function handleThemeVideoDelete(res, url) {+ const meta = themeMetaFile(url.searchParams.get('id'));+ if (!meta) return json(res, 400, { ok: false, error: '缺少主题 id' });+ let removed = false;+ for (const ext of ['mp4', 'webm']) {+ const file = path.join(meta.dir, 'background.' + ext);+ try { if (fs.existsSync(file)) { fs.rmSync(file, { force: true }); removed = true; } } catch (_) {}+ }+ try {+ if (fs.existsSync(meta.file)) {+ const theme = JSON.parse(fs.readFileSync(meta.file, 'utf8')) || {};+ if (theme.video) { delete theme.video; fs.writeFileSync(meta.file, JSON.stringify(theme, null, 2)); removed = true; }+ }+ } catch (_) {}+ if (removed) log('[theme] 移除视频壁纸 -> ' + meta.id);+ const applied = await applyThemeByCdp(meta.id).then(() => true).catch(() => false);+ return json(res, 200, { ok: true, removed, applied, id: meta.id });+}++function writeThemeMeta(meta, patch, fallback) {+ let theme = null;+ try { if (fs.existsSync(meta.file)) theme = JSON.parse(fs.readFileSync(meta.file, 'utf8')) || null; } catch (_) { theme = null; }+ // 主题文件不存在时用 getTheme 的结果兜底(内置主题被显式改过的场景),+ // 存在时只打补丁——不要把 getTheme 补出来的瞬态变量写回用户主题。+ if (!theme) theme = { ...(fallback || {}) };+ Object.assign(theme, patch);+ fs.mkdirSync(path.dirname(meta.file), { recursive: true });+ fs.writeFileSync(meta.file, JSON.stringify(theme, null, 2));+ return theme;+}+async function applyThemeByCdp(id, options = {}) {const nativeOnly = options.nativeOnly === true || PROFILE.capabilities.nativeComposer === true;if (!PROFILE.capabilities.theme || (PROFILE.capabilities.themeTakeover === false && !nativeOnly)) throw new Error(`${PROFILE.name} 暂不支持毛玻璃主题`);@@ -8962,7 +9137,7 @@ async function applyThemeByCdp(id, options = {}) {if (id === 'nebula' && takeoverEnabled) {// 分开两个 CDP 回合:释放自定义 CSS/守护,让官方深色真正渲染,再接管毛玻璃。// 不改持久化接管开关,避免中途失败或并发操作留下错误的用户设置。- await applyThemeByCdp('dark', { ...options, nativeOnly: true });+ await applyThemeByCdp('dark', { ...options, nativeOnly: true, videoPreflight: true });if (applyGeneration !== themeApplyGeneration || readSessionState().themeTakeoverEnabled === false) return { applied: false, cancelled: true };// Electron 后台窗口会节流 setTimeout/暂停 rAF;由 daemon 等待,// 再同步检查官方底色,不能让开关响应依赖 renderer 的下一帧。@@ -9000,70 +9175,91 @@ async function applyThemeByCdp(id, options = {}) {}const extrasCss = themeExtrasCss(id);const isDark = !!(theme && theme.dark);- // 背景图:主题 JSON 带 image 字段时,从 themes/<id>/<image> 读取转 data URL(WBSS 方案:#root 背景 + 容器透明化)+ // 背景层:主题里带 video 且文件在时优先视频壁纸(#root 只留蒙版,画面交给 z-index:-1 的+ // <video> 层,见 wallpaper-video.js);否则沿用图片方案:#root 背景 = data URL + 容器透明化。let bgCssStr = '';- if (theme && theme.image) {+ let themeVideo = null;+ if (theme && theme.video) {try {- const safeId = String(theme.id || id).replace(/[^A-Za-z0-9_-]/g, '_');- const candidates = [- path.join(THEMES_DIR, safeId, String(theme.image).replace(/^\.\.?[/\\]/, '')),- path.join(THEMES_DIR, safeId, 'background.' + String(theme.image).split('.').pop()),- path.join(THEMES_DIR, String(theme.image).replace(/^\.\.?[/\\]/, '')),- ];- let imgPath = null;- for (const c of candidates) {- if (fs.existsSync(c)) { imgPath = c; break; }- }- // 兜底:按文件名在 themes 所有子目录里搜索(兼容旧 build 上传时目录 id 与主题 id 不一致的情况)- if (!imgPath) {- try {- const wanted = String(theme.image).split('/').pop().split('\\').pop();- for (const sub of fs.readdirSync(THEMES_DIR)) {- const p = path.join(THEMES_DIR, sub, wanted);- if (fs.existsSync(p)) { imgPath = p; break; }- }- } catch (_) {}+ const videoPath = resolveVideoFile(THEMES_DIR, theme.id || id, theme.video);+ if (videoPath) {+ const stat = fs.statSync(videoPath);+ themeVideo = { path: videoPath, name: String(theme.video), size: stat.size, mtime: stat.mtimeMs };+ } else {+ log('[theme] 视频壁纸文件缺失,回落到图片背景: ' + theme.video);}- if (imgPath) {- const buf = fs.readFileSync(imgPath);- const ext = path.extname(imgPath).toLowerCase().replace('.jpeg', '.jpg');- const mime = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';- const dataUrl = 'data:' + mime + ';base64,' + buf.toString('base64');- // WBSS 背景图方案:背景图铺 #root,容器透明 + 半透明毛玻璃让底图透出- // 遮罩/半透明度调低(40%/34%/30%):背景图偏暗时让图更透出,毛玻璃更可见- // 全局黑色蒙版(默认 0.3,面板主题页可调):rgba(0,0,0,α) 压在最上层,让背景图更沉、文字更可读- // 注意:opacity=0 是合法的「关闭蒙版」,不能用 || 兜底(0 会被当成 falsy 变成 0.1)- const maskFile = path.join(DATA_DIR, 'mask.json');- let mask = 0.3;- try {- if (fs.existsSync(maskFile)) {- const v = parseFloat(JSON.parse(fs.readFileSync(maskFile, 'utf8')).opacity);- if (!Number.isNaN(v)) mask = Math.min(1, Math.max(0, v));- }- } catch (_) {}- const blur = readBackgroundBlur();- const blurPx = Math.round(blur * MAX_BACKGROUND_BLUR_PX * 10) / 10;- const blurCss = blurPx > 0- ? 'backdrop-filter:blur(' + blurPx + 'px);-webkit-backdrop-filter:blur(' + blurPx + 'px);'- : 'backdrop-filter:none;-webkit-backdrop-filter:none;';- bgCssStr = [- '#root{background:',- 'linear-gradient(rgba(0,0,0,' + mask + '),rgba(0,0,0,' + mask + ')),',- 'linear-gradient(90deg,color-mix(in srgb,var(--wb-bg-primary) 40%,transparent) 0 18%,transparent 42%),',- 'linear-gradient(180deg,transparent 0 58%,color-mix(in srgb,var(--wb-bg-primary) 50%,transparent) 100%),',- 'var(--wbs-wallpaper-image,url(' + dataUrl + ')) right center / cover no-repeat fixed !important;}',- 'body[data-vscode-theme-name] .teams-container,body[data-vscode-theme-name] .teams-container.is-mac{background:transparent !important;' + blurCss + '}',- 'body[data-vscode-theme-name] [data-view-id]{background:transparent !important}',- 'body[data-vscode-theme-name] .main-content{background:transparent !important}',- // 左侧菜单(会话列表)透明(用户 08-30 00:46 要求去掉毛玻璃,连同子组件全透明,背景图直接透出)- 'body[data-vscode-theme-name] .conversation-list,body[data-vscode-theme-name] [data-view-id=sidebar]{background:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important}',- // 输入框区域:毛玻璃背景(用户要求加回:半透明 + 模糊,背景图透出)- // 注意:聊天页 [class*="input-area-container"] 父容器改为透明(patch-40 处理),- // 主页 .wb-home-composer 也改为透明(patch-37),毛玻璃只保留在输入框主体 _mainArea(patch-40)。- 'body[data-vscode-theme-name] [class*="chat-input"]{background:color-mix(in srgb,var(--wb-bg-primary) 40%,transparent) !important;backdrop-filter:blur(20px) saturate(1.15);-webkit-backdrop-filter:blur(20px) saturate(1.15)}',- // 主内容区底部渐变保证可读- 'body[data-vscode-theme-name] [data-view-id=main-content]{background:linear-gradient(180deg,transparent 0 38%,color-mix(in srgb,var(--wb-bg-primary) 55%,transparent) 100%) !important}',- ].join('');+ } catch (_) {}+ }+ if (themeVideo || (theme && theme.image)) {+ try {+ // 全局黑色蒙版(默认 0.3,面板主题页可调):rgba(0,0,0,α) 压在最上层,让背景更沉、文字更可读+ // 注意:opacity=0 是合法的「关闭蒙版」,不能用 || 兜底(0 会被当成 falsy 变成 0.1)+ const maskFile = path.join(DATA_DIR, 'mask.json');+ let mask = 0.3;+ try {+ if (fs.existsSync(maskFile)) {+ const v = parseFloat(JSON.parse(fs.readFileSync(maskFile, 'utf8')).opacity);+ if (!Number.isNaN(v)) mask = Math.min(1, Math.max(0, v));+ }+ } catch (_) {}+ const blur = readBackgroundBlur();+ const blurPx = Math.round(blur * MAX_BACKGROUND_BLUR_PX * 10) / 10;+ const blurCss = blurPx > 0+ ? 'backdrop-filter:blur(' + blurPx + 'px);-webkit-backdrop-filter:blur(' + blurPx + 'px);'+ : 'backdrop-filter:none;-webkit-backdrop-filter:none;';+ // 容器透明化对图片与视频完全一致:底层是什么都必须能透出来+ const containerCss = [+ 'body[data-vscode-theme-name] .teams-container,body[data-vscode-theme-name] .teams-container.is-mac{background:transparent !important;' + blurCss + '}',+ 'body[data-vscode-theme-name] [data-view-id]{background:transparent !important}',+ 'body[data-vscode-theme-name] .main-content{background:transparent !important}',+ // 左侧菜单(会话列表)透明(用户 08-30 00:46 要求去掉毛玻璃,连同子组件全透明,背景图直接透出)+ 'body[data-vscode-theme-name] .conversation-list,body[data-vscode-theme-name] [data-view-id=sidebar]{background:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important}',+ // 输入框区域:毛玻璃背景(用户要求加回:半透明 + 模糊,背景图透出)+ // 注意:聊天页 [class*="input-area-container"] 父容器改为透明(patch-40 处理),+ // 主页 .wb-home-composer 也改为透明(patch-37),毛玻璃只保留在输入框主体 _mainArea(patch-40)。+ 'body[data-vscode-theme-name] [class*="chat-input"]{background:color-mix(in srgb,var(--wb-bg-primary) 40%,transparent) !important;backdrop-filter:blur(20px) saturate(1.15);-webkit-backdrop-filter:blur(20px) saturate(1.15)}',+ // 主内容区底部渐变保证可读+ 'body[data-vscode-theme-name] [data-view-id=main-content]{background:linear-gradient(180deg,transparent 0 38%,color-mix(in srgb,var(--wb-bg-primary) 55%,transparent) 100%) !important}',+ ].join('');+ if (themeVideo) {+ bgCssStr = videoRootBackground(mask) + containerCss;+ } else {+ const safeId = String(theme.id || id).replace(/[^A-Za-z0-9_-]/g, '_');+ const candidates = [+ path.join(THEMES_DIR, safeId, String(theme.image).replace(/^\.\.?[/\\]/, '')),+ path.join(THEMES_DIR, safeId, 'background.' + String(theme.image).split('.').pop()),+ path.join(THEMES_DIR, String(theme.image).replace(/^\.\.?[/\\]/, '')),+ ];+ let imgPath = null;+ for (const c of candidates) {+ if (fs.existsSync(c)) { imgPath = c; break; }+ }+ // 兜底:按文件名在 themes 所有子目录里搜索(兼容旧 build 上传时目录 id 与主题 id 不一致的情况)+ if (!imgPath) {+ try {+ const wanted = String(theme.image).split('/').pop().split('\\').pop();+ for (const sub of fs.readdirSync(THEMES_DIR)) {+ const p = path.join(THEMES_DIR, sub, wanted);+ if (fs.existsSync(p)) { imgPath = p; break; }+ }+ } catch (_) {}+ }+ if (imgPath) {+ const buf = fs.readFileSync(imgPath);+ const ext = path.extname(imgPath).toLowerCase().replace('.jpeg', '.jpg');+ const mime = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';+ const dataUrl = 'data:' + mime + ';base64,' + buf.toString('base64');+ // WBSS 背景图方案:背景图铺 #root,容器透明 + 半透明毛玻璃让底图透出+ // 遮罩/半透明度调低(40%/34%/30%):背景图偏暗时让图更透出,毛玻璃更可见+ bgCssStr = [+ '#root{background:',+ 'linear-gradient(rgba(0,0,0,' + mask + '),rgba(0,0,0,' + mask + ')),',+ 'linear-gradient(90deg,color-mix(in srgb,var(--wb-bg-primary) 40%,transparent) 0 18%,transparent 42%),',+ 'linear-gradient(180deg,transparent 0 58%,color-mix(in srgb,var(--wb-bg-primary) 50%,transparent) 100%),',+ 'var(--wbs-wallpaper-image,url(' + dataUrl + ')) right center / cover no-repeat fixed !important;}',+ containerCss,+ ].join('');+ }}} catch (e) {log('[theme] 背景图加载失败: ' + e.message);@@ -9071,6 +9267,11 @@ async function applyThemeByCdp(id, options = {}) {}const expr = `(function(){if (window.__wbsWallpaperRuntime) window.__wbsWallpaperRuntime.dispose();+ // 主题里没有视频就顺手摘掉视频层:daemon 重启后 lastVideoKey 是空的,+ // 靠这一步兜住"页面里还挂着上一版视频"的情况,不必依赖 daemon 的内存状态。+ // nebula 的官方深色预置(videoPreflight)不能摘:紧跟着就会重新挂载,+ // 提前摘掉会让几十 MB 的视频重下一遍。+ ${themeVideo || options.videoPreflight ? '' : 'if (window.__wbsVideoRuntime) window.__wbsVideoRuntime.dispose();'}var h = document.documentElement, b = document.body;if (!h || !b) return { pending: true };try {@@ -9418,7 +9619,15 @@ async function applyThemeByCdp(id, options = {}) {log('[theme] 应用主题失败: ' + detail);throw new Error('应用主题失败: ' + detail);}- if (id === 'nebula' && takeoverEnabled && wallpaperRotation.status().mode === 'random') {+ // 视频壁纸层在主题 CSS 之后挂载/摘除:此刻 #root 已经只留蒙版,视频到位即可见。+ // 同一个视频重复应用(拖蒙版、改毛玻璃)命中 key,不会重新拉流。+ if (takeoverEnabled && themeVideo) {+ await applyVideoWallpaperByCdp(themeVideo, id);+ } else if (lastVideoKey && !options.videoPreflight) {+ await disposeVideoWallpaperByCdp();+ }+ // 视频壁纸下不启用图片随机轮换:两者抢同一层背景。+ if (!themeVideo && id === 'nebula' && takeoverEnabled && wallpaperRotation.status().mode === 'random') {wallpaperRotation.restore().catch(() => {});}// 浅色成功恢复官方样式时 applied=false(无自定义覆盖),仍须启动轮询并更新基线。@@ -11685,6 +11894,70 @@ function handleApi(req, res) {}}+ // 视频壁纸(毛玻璃主题的背景层,方案见 scripts/wallpaper-video.js)+ // GET /api/theme-video?id=<主题 id>[&v=<mtime>] 字节流;渲染进程 fetch 成 blob 交给 <video>+ // POST /api/theme-video/upload?id=<主题 id> 裸流上传,落盘 themes/<id>/background.<mp4|webm>+ // DELETE /api/theme-video?id=<主题 id> 移除视频,自动回落到图片背景+ if (p === '/api/theme-video' || p === '/api/theme-video/upload') {+ if (!PROFILE.capabilities.theme || PROFILE.capabilities.themeTakeover === false) {+ return json(res, 400, { ok: false, error: '当前客户端不支持视频壁纸' });+ }+ }+ if (req.method === 'GET' && p === '/api/theme-video') {+ try {+ const themeId = String(url.searchParams.get('id') || readSavedThemeId() || '');+ const theme = getTheme(themeId);+ const file = theme && theme.video ? resolveVideoFile(THEMES_DIR, theme.id || themeId, theme.video) : null;+ if (!file) return json(res, 404, { ok: false, error: '当前主题没有视频壁纸' });+ const stat = fs.statSync(file);+ const ext = path.extname(file).toLowerCase();+ const mime = ext === '.webm' ? 'video/webm' : 'video/mp4';+ const headers = {+ 'Content-Type': mime, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',+ 'Accept-Ranges': 'bytes',+ };+ if (res.__wbsCorsOrigin) { headers['Access-Control-Allow-Origin'] = res.__wbsCorsOrigin; headers.Vary = 'Origin'; }+ // Range:渲染进程目前整段 fetch,但保留分段能力,便于之后直接给 <video src> 用。+ const range = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range || ''));+ let start = 0;+ let end = stat.size - 1;+ let status = 200;+ if (range && stat.size > 0) {+ const rawStart = range[1] === '' ? null : parseInt(range[1], 10);+ const rawEnd = range[2] === '' ? null : parseInt(range[2], 10);+ if (rawStart === null && rawEnd !== null) { start = Math.max(0, stat.size - rawEnd); }+ else if (rawStart !== null) { start = rawStart; if (rawEnd !== null) end = Math.min(rawEnd, stat.size - 1); }+ if (start > end || start >= stat.size) {+ res.writeHead(416, { 'Content-Range': `bytes */${stat.size}` });+ return res.end();+ }+ status = 206;+ headers['Content-Range'] = `bytes ${start}-${end}/${stat.size}`;+ }+ headers['Content-Length'] = end - start + 1;+ if (res.destroyed) return;+ res.writeHead(status, headers);+ const stream = fs.createReadStream(file, { start, end });+ res.on('close', () => stream.destroy());+ stream.on('error', () => res.destroy());+ stream.pipe(res);+ return;+ } catch (e) {+ if (!res.headersSent) return json(res, 500, { ok: false, error: e.message });+ return;+ }+ }+ if (req.method === 'POST' && p === '/api/theme-video/upload') {+ return handleThemeVideoUpload(req, res, url).catch((e) => {+ if (!res.headersSent) json(res, 500, { ok: false, error: e.message });+ });+ }+ if (req.method === 'DELETE' && p === '/api/theme-video') {+ return handleThemeVideoDelete(res, url).catch((e) => {+ if (!res.headersSent) json(res, 500, { ok: false, error: e.message });+ });+ }+// 官方背景图库列表(themes/wallpapers/*.webp),供面板「主题」页预览切换。// 附带 currentWallpaper:当前主题 background.webp 内容哈希匹配到的图库文件名(供面板高亮当前壁纸)// 附带 customWallpapers:用户上传的自定义壁纸(custom-*.webp),供面板分开展示@@ -11697,15 +11970,23 @@ function handleApi(req, res) {const custom = files.filter((f) => /^custom-/i.test(f));// 当前背景 = 当前主题目录的 background.webp(哈希对比图库)let currentWallpaper = null;+ // 视频壁纸在生效时占据整个背景层,图片选中态不再具有意义+ let currentVideo = null;try {const cur = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'current-theme.json'), 'utf8')).id || '';- const bg = path.join(THEMES_DIR, String(cur).replace(/[^A-Za-z0-9_-]/g, '_'), 'background.webp');- if (fs.existsSync(bg)) {- const crypto = require('crypto');- const want = crypto.createHash('md5').update(fs.readFileSync(bg)).digest('hex');- for (const f of files) {- const p2 = path.join(WALLPAPERS_DIR, f);- if (crypto.createHash('md5').update(fs.readFileSync(p2)).digest('hex') === want) { currentWallpaper = f; break; }+ const curTheme = getTheme(cur);+ const videoFile = curTheme && curTheme.video ? resolveVideoFile(THEMES_DIR, curTheme.id || cur, curTheme.video) : null;+ if (videoFile) {+ currentVideo = { name: path.basename(videoFile), title: path.basename(videoFile), size: fs.statSync(videoFile).size };+ } else {+ const bg = path.join(THEMES_DIR, String(cur).replace(/[^A-Za-z0-9_-]/g, '_'), 'background.webp');+ if (fs.existsSync(bg)) {+ const crypto = require('crypto');+ const want = crypto.createHash('md5').update(fs.readFileSync(bg)).digest('hex');+ for (const f of files) {+ const p2 = path.join(WALLPAPERS_DIR, f);+ if (crypto.createHash('md5').update(fs.readFileSync(p2)).digest('hex') === want) { currentWallpaper = f; break; }+ }}}} catch (_) {}@@ -11714,6 +11995,7 @@ function handleApi(req, res) {wallpapers: official.map((f) => ({ name: f, title: '官方壁纸 ' + String(f.replace(/\.webp$/i, '')).replace(/^wallpaper-?0*/, '') })),customWallpapers: custom.map((f) => ({ name: f, title: '自定义壁纸 ' + String(f.replace(/\.webp$/i, '')).replace(/^custom-/, '') })),currentWallpaper,+ currentVideo,});} catch (e) {return json(res, 500, { ok: false, error: e.message });@@ -12683,9 +12965,15 @@ function handleApi(req, res) {try {const t = JSON.parse(fs.readFileSync(tf, 'utf8'));t.image = 'background.webp';+ // 选图片就说明不要视频了:video 字段留着会让视频层继续压住这张图+ delete t.video;fs.writeFileSync(tf, JSON.stringify(t, null, 2));} catch (_) {}}+ // 顺手清掉视频文件,避免磁盘里留一份再也不会被引用的片子+ for (const ext of ['mp4', 'webm']) {+ try { fs.rmSync(path.join(dir, 'background.' + ext), { force: true }); } catch (_) {}+ }// 记录当前主题并应用(reload 后 1.5s 恢复的就是这张新图,不再"切回最早背景图")try {fs.writeFileSync(path.join(DATA_DIR, 'current-theme.json'), JSON.stringify({ id, at: new Date().toISOString() }, null, 2));diff --git a/scripts/inject.js b/scripts/inject.jsindex 7751e5f..38780a6 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -1844,6 +1844,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'导出账号': 'Export accounts', '导入账号': 'Import accounts', '导出会话': 'Export sessions', '导入会话': 'Import sessions', '导出快捷短语': 'Export quick phrases', '导入快捷短语': 'Import quick phrases', '同步选中到其他账号': 'Sync selected to another account', '删除选中': 'Delete selected', '操作会话': 'Session actions', '连通测试': 'Test connection', '编辑模型': 'Edit model', '模型已保存': 'Model saved', '模型已启用': 'Model enabled', '模型已复制': 'Model copied', '模型配置已共用': 'Model configuration shared', '与 {name} 共用模型配置': 'Model configuration shared with {name}', '当前模型': 'Current model', '备选模型': 'Backup models', '模型加载失败:': 'Failed to load models: ', '保存模型失败:': 'Failed to save model: ', '删除当前模型失败:': 'Failed to delete current model: ', '启用模型失败:': 'Failed to enable model: ', '连通测试失败:': 'Connection test failed: ','请选择壁纸文件夹': 'Choose a wallpaper folder', '壁纸模式': 'Wallpaper mode', '手动应用': 'Manual', '文件夹随机': 'Shuffle folder', '壁纸文件夹': 'Wallpaper folder', '选择或填写文件夹路径': 'Choose or enter a folder path', '选择文件夹': 'Choose folder', '切换间隔': 'Change every', '1 分钟': '1 minute', '3 分钟': '3 minutes', '5 分钟': '5 minutes', '10 分钟': '10 minutes', '30 分钟': '30 minutes', '1 小时': '1 hour', '自定义': 'Custom', '分钟': 'minutes', '自定义切换间隔(分钟)': 'Custom interval (minutes)', '立即换一张': 'Next wallpaper', '已暂停,恢复毛玻璃主题后继续': 'Paused until the frosted theme resumes', '当前:': 'Current: ', '等待应用壁纸': 'Waiting to apply wallpaper', '壁纸设置保存失败': 'Could not save wallpaper settings', '仅读取此文件夹内的 PNG / JPG / WebP,不复制或修改原文件;自动跳过超过 20MB 或 1600 万像素的图片。': 'Reads PNG / JPG / WebP from this folder without copying or modifying originals. Images over 20MB or 16 megapixels are skipped.','选择要查看的账号': 'Choose an account to view', '选择账号并输入密码后导出备份': 'Choose accounts and enter a password to export backups', '从加密导出文件导入账号备份': 'Import account backups from an encrypted export', '使用密码导出选中会话': 'Export selected sessions with a password', '使用密码导出选中快捷短语': 'Export selected quick phrases with a password', '从加密文件导入会话': 'Import sessions from an encrypted file', '从加密文件导入快捷短语': 'Import quick phrases from an encrypted file', '仅支持 PNG / JPG / WebP': 'PNG / JPG / WebP only', '点击或拖拽上传壁纸': 'Click or drag to upload a wallpaper', '点击选择图片,或拖拽到此处': 'Click to choose an image, or drag it here', '支持 PNG / JPG / WebP,自动压缩;可添加多张': 'PNG / JPG / WebP supported; images are compressed automatically',+ // 视频壁纸(毛玻璃主题的背景层)+ '视频壁纸': 'Video wallpaper', 'MP4 / WebM · 自动静音循环': 'MP4 / WebM · muted loop', '点击或拖拽上传视频': 'Click or drag to upload a video', '点击选择视频,或拖拽到此处': 'Click to choose a video, or drag it here', '最大 128MB;选择图片壁纸会自动移除视频': 'Up to 128MB. Choosing an image wallpaper removes the video.', '移除视频壁纸': 'Remove video wallpaper', '当前视频 · ': 'Current video · ', '仅支持 MP4 / WebM 视频': 'MP4 / WebM videos only', '视频不能超过': 'Video must be under ', '正在上传视频壁纸…': 'Uploading video wallpaper…', '视频壁纸已应用': 'Video wallpaper applied', '上传视频壁纸失败': 'Video wallpaper upload failed', '已移除视频壁纸': 'Video wallpaper removed', '移除视频壁纸失败': 'Could not remove video wallpaper','未命名账号': 'Unnamed account', '未命名模型': 'Unnamed model', '未命名': 'Unnamed', '未知错误': 'Unknown error', '未知': 'Unknown', '有效期未知': 'Expiry unknown', '未找到输入框': 'Composer not found', '输入框内容为空': 'Composer is empty', '当前输入框暂不支持引用插入': 'The current composer does not support quote insertion', '引用插入失败,请重试': 'Could not insert quote. Please try again', '短语不能为空': 'Quick phrase cannot be empty', '请输入快捷短语': 'Enter a quick phrase', '删除快捷短语': 'Delete quick phrase', '编辑快捷短语': 'Edit quick phrase', '新增快捷短语': 'Add quick phrase', '确定删除': 'Confirm deletion', '确认永久删除': 'Confirm permanent deletion','本机回环 CDP 注入 · 不改官方安装包': 'Local CDP injection · official app untouched', '一个基于 ': 'A ', ' 的 WorkBuddy 桌面端增强工具。零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。': ' WorkBuddy desktop enhancement tool using Chrome DevTools Protocol (CDP). No intrusion or re-signing; UI components are injected into the running renderer.', '问题反馈': 'Report an issue',// —— 覆盖度补齐(分区域,模板条目支持 {name} 占位,匹配时最长优先)——@@ -11188,6 +11190,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-bg-upload" id="wbs-bg-upload" title="点击选择图片,或拖拽到此处"><span class="wbs-bg-upload-ico">+</span><span>点击或拖拽上传壁纸</span><span class="wbs-bg-upload-hint">支持 PNG / JPG / WebP,自动压缩;可添加多张</span></div>' +'<div class="wbs-wallpapers wbs-custom-wallpapers" id="wbs-custom-wallpapers"><div class="wbs-wp-loading">壁纸加载中…</div></div>' +'<input type="file" id="wbs-theme-file" accept="image/png,image/jpeg,image/webp" style="display:none">' ++ // 视频壁纸:和图片壁纸共用蒙版/毛玻璃,只是背景层换成循环播放的视频+ '<div class="wbs-video-block" id="wbs-video-block">' ++ '<div class="wbs-video-head"><span class="wbs-video-title">视频壁纸</span><span class="wbs-video-tag">MP4 / WebM · 自动静音循环</span></div>' ++ '<div class="wbs-bg-upload wbs-video-upload" id="wbs-video-upload" title="点击选择视频,或拖拽到此处"><span class="wbs-bg-upload-ico">▶</span><span>点击或拖拽上传视频</span><span class="wbs-bg-upload-hint">最大 128MB;选择图片壁纸会自动移除视频</span></div>' ++ '<div class="wbs-video-current" id="wbs-video-current" hidden>' ++ '<span class="wbs-video-name" id="wbs-video-name"></span>' ++ '<button class="wbs-video-remove" type="button" id="wbs-video-remove">移除视频壁纸</button>' ++ '</div>' ++ '<input type="file" id="wbs-video-file" accept="video/mp4,video/webm" style="display:none">' ++ '</div>' +'</div>' +'</div>' +'<div class="wbs-mask-row">' +@@ -12029,6 +12041,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}var up = t.closest ? t.closest('#wbs-bg-upload, #wbs-theme-upload') : null;if (up) { var f = themePane.querySelector('#wbs-theme-file'); if (f) f.click(); return; }+ var vup = t.closest ? t.closest('#wbs-video-upload') : null;+ if (vup) { var vf = themePane.querySelector('#wbs-video-file'); if (vf) vf.click(); return; }+ var vdel = t.closest ? t.closest('#wbs-video-remove') : null;+ if (vdel) { removeVideoWallpaper(); return; }var removeAvatar = t.closest ? t.closest('[data-avatar-delete]') : null;if (removeAvatar) {e.preventDefault();@@ -12059,6 +12075,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {reader.readAsDataURL(file);t.value = '';}+ if (t && t.id === 'wbs-video-file') {+ var vfile = t.files && t.files[0];+ t.value = '';+ if (vfile) uploadVideoWallpaper(vfile);+ }if (t && t.id === 'wbs-avatar-file') {var f2 = t.files && t.files[0];if (!f2) return;@@ -12162,6 +12183,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {reader.readAsDataURL(f);});}+ // 视频壁纸上传区:点击由上面的委托处理,这里只补拖拽+ var videoUpload = themePane.querySelector('#wbs-video-upload');+ if (videoUpload) {+ videoUpload.addEventListener('dragover', function (e) {+ e.preventDefault();+ this.classList.add('drag');+ });+ videoUpload.addEventListener('dragleave', function () { this.classList.remove('drag'); });+ videoUpload.addEventListener('drop', function (e) {+ e.preventDefault();+ this.classList.remove('drag');+ var f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];+ if (f) uploadVideoWallpaper(f);+ });+ }}function wireEnhancePane() {// 决策弹窗开关@@ -12317,6 +12353,26 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}registerDisposer(releaseWallpaperPreviews);registerDisposer(function () { if (window.__wbsWallpaperRuntime) window.__wbsWallpaperRuntime.dispose(); });+ // 视频壁纸状态只在「自定义壁纸」面板里显示一行「当前视频 · 大小」;+ // 视频本身不进面板,避免再解码一路、也避免面板比客户端更耗电。+ function renderVideoState(video) {+ var box = root.querySelector('#wbs-video-current');+ if (!box) return;+ var nameEl = root.querySelector('#wbs-video-name');+ var uploadEl = root.querySelector('#wbs-video-upload');+ if (!video) {+ box.hidden = true;+ if (nameEl) nameEl.textContent = '';+ if (uploadEl) uploadEl.classList.remove('has-video');+ return;+ }+ var size = Number(video.size) || 0;+ var label = size >= 1048576 ? (size / 1048576).toFixed(1) + ' MB'+ : size >= 1024 ? Math.round(size / 1024) + ' KB' : size + ' B';+ box.hidden = false;+ if (uploadEl) uploadEl.classList.add('has-video');+ if (nameEl) nameEl.textContent = '当前视频 · ' + label;+ }function loadWallpapers(force) {var grid = root.querySelector('#wbs-wallpapers');var cgrid = root.querySelector('#wbs-custom-wallpapers');@@ -12367,6 +12423,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}// 面板高度固定为主题页高度:首进主题页壁纸渲染后锁定,防止切 tab 高度跳动lockPanelHeight();+ // 视频壁纸状态(有视频时图片网格整体不再高亮,因为背景层被视频占用)+ renderVideoState(d.currentVideo || null);// 逐张 fetch → blob → objectURL 预览(no-store 防 HTTP 缓存旧图——图库重建后同名文件内容会变)var allGrids = [grid, cgrid].filter(Boolean);allGrids.forEach(function (g) {@@ -13023,6 +13081,45 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {avatarTimer = setBuildInterval(applyAvatar, 2000);setBuildTimeout(applyAvatar, 800);+ // ===== 视频壁纸(毛玻璃主题的背景层)=====+ // 图片壁纸是 base64 JSON,视频几十 MB 走不了 JSON,所以直接把 File 当请求体:+ // 直连 transport 是普通 fetch(File);CDP transport 由桥接自动切成 256KB 分片上传。+ var VIDEO_MAX_MB = 128;+ function uploadVideoWallpaper(file) {+ if (!file) return;+ if (!/^video\/(mp4|webm)$/i.test(file.type || '') && !/\.(mp4|webm)$/i.test(file.name || '')) {+ toast('仅支持 MP4 / WebM 视频', true, root);+ return;+ }+ if (file.size > VIDEO_MAX_MB * 1024 * 1024) {+ toast('视频不能超过 ' + VIDEO_MAX_MB + 'MB', true, root);+ return;+ }+ var target = themeSelectValue();+ toast('正在上传视频壁纸…', false, root);+ api('/api/theme-video/upload?id=' + encodeURIComponent(target), {+ method: 'POST',+ headers: { 'content-type': 'application/octet-stream' },+ body: file,+ }).then(function (r) {+ if (!r || !r.ok) throw new Error((r && r.error) || '上传视频壁纸失败');+ toast('视频壁纸已应用', false, root);+ loadWallpapers(true);+ if (typeof loadWallpaperRotation === 'function') loadWallpaperRotation();+ }).catch(function (e) {+ toast('上传视频壁纸失败: ' + ((e && e.message) || e), true, root);+ });+ }+ function removeVideoWallpaper() {+ var target = themeSelectValue();+ api('/api/theme-video?id=' + encodeURIComponent(target), { method: 'DELETE' }).then(function (r) {+ if (!r || !r.ok) throw new Error((r && r.error) || '移除视频壁纸失败');+ toast('已移除视频壁纸', false, root);+ loadWallpapers(true);+ }).catch(function (e) {+ toast('移除视频壁纸失败: ' + ((e && e.message) || e), true, root);+ });+ }// ===== 自定义图片生成皮肤(WBSS 方案:压缩 webp + HSL 取色 -> theme.json + 背景图)=====// 上传按钮/文件输入位于主题 pane(构建后由 wireThemePane 事件委托处理)// 替换当前主题背景图(保持主题配色不变,不再生成新主题——避免 reload 后被"切回最早背景图")@@ -18985,6 +19082,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-bg-upload:hover,.wbs-bg-upload.drag{border-color:var(--wb-accent-blue,#4f86ff);color:var(--wb-color-text-primary,#1f1f1f);background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 8%,transparent)}','.wbs-bg-upload-ico{width:30px;height:30px;border-radius:50%;background:var(--wb-bg-hover,#e8e9eb);display:flex;align-items:center;justify-content:center;font-size:18px;line-height:1;font-weight:400}','.wbs-bg-upload-hint{font-size:11px;color:var(--wb-icon-tertiary,#999);font-weight:400}',+ /* 视频壁纸:上传区 + 当前视频一行 */+ '.wbs-video-block{margin-top:14px;padding-top:12px;border-top:1px solid var(--wb-border-subtle,rgba(0,0,0,.08))}',+ '.wbs-video-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:8px}',+ '.wbs-video-title{font-size:12px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f)}',+ '.wbs-video-tag{font-size:11px;font-weight:400;color:var(--wb-icon-tertiary,#999)}',+ '.wbs-video-upload{padding:14px 12px;gap:4px}',+ '.wbs-video-upload.has-video{border-style:solid}',+ '.wbs-video-current{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:8px;padding:6px 10px;border-radius:8px;background:color-mix(in srgb,var(--wb-bg-tertiary,#f0f0f0) 45%,transparent);font-size:12px;color:var(--wb-color-text-primary,#1f1f1f)}',+ '.wbs-video-current[hidden]{display:none}',+ '.wbs-video-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',+ '.wbs-video-remove{flex:0 0 auto;border:1px solid var(--wb-border-subtle,rgba(0,0,0,.12));background:transparent;color:var(--wb-color-text-muted,#666);font-size:11px;font-weight:600;padding:3px 9px;border-radius:7px;cursor:pointer;transition:color .15s,border-color .15s,background .15s}',+ '.wbs-video-remove:hover{color:#e24b4a;border-color:rgba(226,75,74,.45);background:rgba(226,75,74,.08)}','.wbs-bg-preview{display:none;width:100%;max-height:140px;object-fit:cover;border-radius:10px;margin-top:8px;border:1px solid var(--wb-border-subtle,#eee)}','.wbs-avatar-option{position:relative;display:flex;flex-direction:column;align-items:center;gap:4px;cursor:pointer;font-size:10px;color:var(--wb-color-text-secondary)}.wbs-avatar-option input{position:absolute;opacity:0;width:1px;height:1px}.wbs-avatar-option img,.wbs-avatar-default-mark{box-sizing:border-box;width:42px;height:42px;padding:3px;object-fit:contain;border:1px solid var(--wb-border-subtle);border-radius:10px;background:var(--wb-bg-tertiary)}.wbs-avatar-option input:checked+img,.wbs-avatar-option input:checked+.wbs-avatar-default-mark{border-color:var(--wb-button-primary-bg);box-shadow:0 0 0 1px var(--wb-button-primary-bg)}.wbs-avatar-option input:focus-visible+img,.wbs-avatar-option input:focus-visible+.wbs-avatar-default-mark{outline:2px solid var(--wb-accent-blue);outline-offset:3px}.wbs-avatar-default-mark{display:flex;align-items:center;justify-content:center;color:var(--wb-icon-secondary);font-size:18px;font-weight:600;line-height:1}',/* 背景蒙版滑块(黑色半透明遮罩,0~100%) */diff --git a/scripts/renderer-api-bridge.js b/scripts/renderer-api-bridge.jsindex c16f357..97145a5 100644--- a/scripts/renderer-api-bridge.js+++ b/scripts/renderer-api-bridge.js@@ -6,6 +6,10 @@ const http = require('node:http');const crypto = require('node:crypto');const BINDING = '__wbsLocalApiRequest';const MAX_BYTES = 64 * 1024 * 1024;+// 需要以流式(Blob 分片)上传的路由:这些路径的请求体可能有几十 MB,+// 一次性塞进 JSON 载荷会撞上 CDP 报文体积上限,也会把渲染进程内存顶爆。+const CHUNKED_UPLOAD_PATHS = ['/api/sessions/import', '/api/theme-video/upload'];+const isChunkedUploadPath = path => CHUNKED_UPLOAD_PATHS.some(p => path === p || path.startsWith(p + '?'));function createRendererApiBridge({ token, port, send }) {let active = 0;@@ -88,7 +92,7 @@ function createRendererApiBridge({ token, port, send }) {await reply({error:'本地 API 请求无效或过多'}); return;}if (request.kind==='upload-start') {- if(path!=='/api/sessions/import' || method!=='POST' || contentType!=='application/octet-stream' ||+ if(!isChunkedUploadPath(path) || method!=='POST' || contentType!=='application/octet-stream' ||typeof request.uploadId!=='string' || !/^[\w:-]{1,100}$/.test(request.uploadId) || uploads.has(request.uploadId) ||!Number.isSafeInteger(request.totalBytes) || request.totalBytes<=0) {await reply({error:'上传请求无效'});return;}const opened=openRequest(path,method,contentType,request.totalBytes);@@ -135,12 +139,19 @@ function installRendererBridge(binding) {catch (_) {pending.delete(id);clearTimeout(timer);reject(new Error('本地 API 尚未连接'));}});}+ // 注意:installRendererBridge 会被 toString() 后注入渲染进程,函数体不能引用+ // 模块作用域的变量(isChunkedUploadPath 等),白名单必须在函数内自己写。+ function bodyNeedsChunking(path, body) {+ if (!(body instanceof Blob)) return false;+ return path === '/api/sessions/import' ||+ path === '/api/theme-video/upload' || path.indexOf('/api/theme-video/upload?') === 0;+ }window.__wbsApiFetch = async function (path, options, token) {options=options || {};var body=options.body;var contentType=options.headers && (options.headers['content-type'] || options.headers['Content-Type']);var request={path:path,method:options.method || 'GET',contentType:contentType};- if(body instanceof Blob && path==='/api/sessions/import') {+ if(bodyNeedsChunking(path, body)) {var uploadId=prefix+':upload:'+(++serial);await transmit(Object.assign({},request,{kind:'upload-start',uploadId:uploadId,totalBytes:body.size}),token);try {diff --git a/scripts/wallpaper-video.js b/scripts/wallpaper-video.jsnew file mode 100644index 0000000..8c0f6e2--- /dev/null+++ b/scripts/wallpaper-video.js@@ -0,0 +1,252 @@+'use strict';++// 视频壁纸(毛玻璃主题)+// ============================================================+// 图片壁纸是把 #root 的 background 换成 data URL,视频没法这么塞,所以改成+// 「#root 只留蒙版/渐变,真正的画面交给 z-index:-1 的 <video> 层」。+// 两者的蒙版、背景毛玻璃、容器透明化完全复用,只有背景层本身不同。+//+// 视频层必须挂在 document.body 上并位于 #root 之下:+// body 背景(画布)→ #wbs-video-wallpaper → #root 半透明蒙版 → 应用内容+// 这样蒙版才能压在视频上,应用自己的容器透明规则也照旧生效。+//+// 视频不进 CSS、不进 CDP 表达式(大文件会把协议撑爆),由 daemon 通过+// /api/theme-video 提供字节流,渲染进程 fetch 成 blob 再交给 <video>。+const fs = require('fs');+const path = require('path');++const VIDEO_MAX_BYTES = 128 * 1024 * 1024;+const VIDEO_HEAD_BYTES = 64 * 1024;++/** 只按文件头判断容器格式:扩展名与 Content-Type 都由调用方给,不能作为落盘依据。 */+function sniffVideo(buf) {+ if (!buf || buf.length < 16) return null;+ // ISO BMFF(MP4/MOV):第 4~7 字节固定 'ftyp'+ if (buf.length >= 12 && buf.toString('ascii', 4, 8) === 'ftyp') {+ // 品牌白名单:排除 HEIF/AVIF 这类同结构但不是视频的图片容器+ const brand = buf.toString('ascii', 8, 12);+ if (/^(heic|heix|mif1|msf1|avif|avis)$/i.test(brand)) return null;+ return { ext: 'mp4', mime: 'video/mp4', brand };+ }+ // EBML(WebM/Matroska)+ if (buf.readUInt32BE(0) === 0x1a45dfa3) {+ const head = buf.subarray(0, Math.min(buf.length, 512)).toString('latin1');+ // 只认 WebM:Chromium 不解码 Matroska 容器里的 H.264,mkv 上传后会一片黑。+ if (head.includes('webm')) return { ext: 'webm', mime: 'video/webm', brand: 'webm' };+ return null;+ }+ return null;+}++/**+ * 定位主题的视频文件。theme.json 里的 video 字段是相对文件名(background.mp4),+ * 但扁平布局(themes/<id>.json)下也可能写成相对 THEMES_DIR 的路径,两种都试。+ * 不做「按扩展名猜 background.*」的兜底:那会让一个写错的文件名静默命中另一段视频。+ */+function resolveVideoFile(themesDir, themeId, videoName) {+ const safeId = String(themeId || '').replace(/[^A-Za-z0-9_-]/g, '_');+ const raw = String(videoName || '').replace(/^\.\.?[/\\]/, '');+ if (!safeId || !raw) return null;+ const candidates = [+ path.join(themesDir, safeId, raw),+ path.join(themesDir, raw),+ ];+ for (const c of candidates) {+ try { if (fs.existsSync(c) && fs.statSync(c).isFile()) return c; } catch (_) {}+ }+ return null;+}++/** 视频壁纸只替换 #root 的背景层:蒙版/渐变/darken 与图片模式保持完全一致。 */+function videoRootBackground(mask) {+ const m = Math.min(1, Math.max(0, Number.isFinite(mask) ? mask : 0.3));+ return '#root{background:' + [+ 'linear-gradient(rgba(0,0,0,' + m + '),rgba(0,0,0,' + m + '))',+ 'linear-gradient(90deg,color-mix(in srgb,var(--wb-bg-primary) 40%,transparent) 0 18%,transparent 42%)',+ 'linear-gradient(180deg,transparent 0 58%,color-mix(in srgb,var(--wb-bg-primary) 50%,transparent) 100%)',+ ].join(',') + ' !important;}';+}++const VIDEO_LAYER_CSS = [+ '#wbs-video-wallpaper{position:fixed;inset:0;z-index:-1;overflow:hidden;pointer-events:none;background:transparent;opacity:0;transition:opacity .45s ease}',+ '#wbs-video-wallpaper.wbs-video-ready{opacity:1}',+ '#wbs-video-wallpaper video{width:100%;height:100%;object-fit:cover;display:block;pointer-events:none;background:transparent}',+ '#wbs-video-wallpaper video::-webkit-media-controls,#wbs-video-wallpaper video::-webkit-media-controls-enclosure,#wbs-video-wallpaper video::-webkit-media-controls-panel{display:none!important}',+].join('');++const VIDEO_HOST_ID = 'wbs-video-wallpaper';+// 视频层使用自己的 <style>,不跟着 #wbs-theme-style 一起被重写:+// 主题重应用(拖蒙版、改毛玻璃、nebula 的官方深色预置)不会把视频层的定位规则清掉,+// 也就不会出现"视频层突然变成 body 里的普通 div 把界面顶下去"的一帧。+const VIDEO_STYLE_ID = 'wbs-video-style';++/**+ * 在渲染进程里安装/更新视频壁纸层。+ * 这段函数体是被 toString() 序列化后注入页面的,不能引用模块作用域的任何变量。+ *+ * key 用来判断「是不是同一个视频」:蒙版/毛玻璃拖动会反复重应用主题,命中 key+ * 时直接复用已加载的 blob,不会把几十 MB 的视频重新拉一遍。+ */+async function updateVideoInRenderer(options) {+ var opts = options || {};+ var key = String(opts.key || '');+ if (!key) return false;++ function ensureStyle() {+ var style = document.getElementById('wbs-video-style');+ var css = String(opts.css || '');+ if (!style) {+ style = document.createElement('style');+ style.id = 'wbs-video-style';+ (document.head || document.documentElement).appendChild(style);+ }+ if (style.textContent !== css) style.textContent = css;+ return style;+ }++ var runtime = window.__wbsVideoRuntime;+ if (runtime && runtime.key === key && runtime.host && runtime.host.isConnected) {+ ensureStyle();+ runtime.play();+ return true;+ }+ if (runtime && runtime.dispose) runtime.dispose();+ ensureStyle();++ var host = document.getElementById('wbs-video-wallpaper');+ if (!host) {+ host = document.createElement('div');+ host.id = 'wbs-video-wallpaper';+ host.setAttribute('aria-hidden', 'true');+ }+ // 必须是 body 的第一个子节点,且不能参与布局:fixed 已脱离文档流。+ var parent = document.body || document.documentElement;+ if (host.parentNode !== parent) parent.insertBefore(host, parent.firstChild);+ host.classList.remove('wbs-video-ready');+ var video = host.querySelector('video');+ if (!video) {+ video = document.createElement('video');+ video.muted = true;+ video.defaultMuted = true;+ video.loop = true;+ video.autoplay = true;+ video.playsInline = true;+ video.preload = 'auto';+ video.setAttribute('muted', '');+ video.setAttribute('loop', '');+ video.setAttribute('autoplay', '');+ video.setAttribute('playsinline', '');+ video.setAttribute('webkit-playsinline', '');+ video.setAttribute('disablepictureinpicture', '');+ video.setAttribute('disableremoteplayback', '');+ host.appendChild(video);+ }+ video.muted = true;++ var controller = new AbortController();+ var objectUrl = '';+ var onVisibility = null;+ var onGesture = null;+ var disposed = false;+ var rt = {+ key: key,+ host: host,+ video: video,+ play: function () {+ if (document.hidden) return;+ try { var p = video.play(); if (p && p.catch) p.catch(function () {}); } catch (_) {}+ if (video.readyState >= 2) host.classList.add('wbs-video-ready');+ },+ dispose: function () {+ disposed = true;+ try { controller.abort(); } catch (_) {}+ if (onVisibility) { document.removeEventListener('visibilitychange', onVisibility); onVisibility = null; }+ if (onGesture) { document.removeEventListener('pointerdown', onGesture, true); onGesture = null; }+ try { video.pause(); } catch (_) {}+ try { video.removeAttribute('src'); video.load(); } catch (_) {}+ if (objectUrl) { try { URL.revokeObjectURL(objectUrl); } catch (_) {} objectUrl = ''; }+ if (host.parentNode) host.parentNode.removeChild(host);+ var style = document.getElementById('wbs-video-style');+ if (style && style.parentNode) style.parentNode.removeChild(style);+ if (window.__wbsVideoRuntime === rt) { try { delete window.__wbsVideoRuntime; } catch (_) {} }+ },+ };+ window.__wbsVideoRuntime = rt;++ // 窗口切到后台时暂停解码:视频壁纸持续播放会明显吃 GPU/电量。+ onVisibility = function () {+ if (disposed) return;+ if (document.hidden) { try { video.pause(); } catch (_) {} }+ else rt.play();+ };+ document.addEventListener('visibilitychange', onVisibility);++ var loaded = new Promise(function (resolve, reject) {+ var timer = setTimeout(function () { reject(new Error('视频加载超时')); }, 20000);+ video.addEventListener('loadeddata', function () {+ clearTimeout(timer);+ if (!disposed && window.__wbsVideoRuntime === rt) host.classList.add('wbs-video-ready');+ resolve(true);+ }, { once: true });+ video.addEventListener('error', function () {+ clearTimeout(timer);+ reject(new Error('视频无法解码'));+ }, { once: true });+ controller.signal.addEventListener('abort', function () {+ clearTimeout(timer);+ reject(new Error('已取消'));+ }, { once: true });+ });+ loaded.then(function () { rt.play(); }).catch(function () {});++ try {+ var response = await fetch(opts.url, {+ headers: { 'X-WorkDaddy-Token': opts.token, 'Cache-Control': 'no-store' },+ cache: 'no-store',+ signal: controller.signal,+ });+ if (!response.ok) throw new Error('wallpaper video unavailable');+ var blob = await response.blob();+ if (disposed || window.__wbsVideoRuntime !== rt) return false;+ objectUrl = URL.createObjectURL(blob);+ video.src = objectUrl;+ // 自动播放被策略拦下时,等用户第一次点击再补播(静音视频通常不需要)。+ onGesture = function () {+ if (disposed) return;+ rt.play();+ if (video.readyState >= 2) {+ document.removeEventListener('pointerdown', onGesture, true);+ onGesture = null;+ }+ };+ document.addEventListener('pointerdown', onGesture, true);+ try { video.load(); } catch (_) {}+ return await loaded.then(function () { return true; }).catch(function () { return false; });+ } catch (_) {+ return false;+ }+}++/** 摘掉视频层(切回图片壁纸 / 关闭接管 / 换成不支持视频的主题时)。 */+function disposeVideoInRenderer() {+ var runtime = window.__wbsVideoRuntime;+ if (runtime && runtime.dispose) runtime.dispose();+ var stale = document.getElementById('wbs-video-wallpaper');+ if (stale && stale.parentNode) stale.parentNode.removeChild(stale);+ var style = document.getElementById('wbs-video-style');+ if (style && style.parentNode) style.parentNode.removeChild(style);+ return true;+}++module.exports = {+ VIDEO_MAX_BYTES,+ VIDEO_HEAD_BYTES,+ VIDEO_HOST_ID,+ VIDEO_STYLE_ID,+ VIDEO_LAYER_CSS,+ sniffVideo,+ resolveVideoFile,+ videoRootBackground,+ updateVideoInRenderer,+ disposeVideoInRenderer,+};diff --git a/test/system-theme.test.js b/test/system-theme.test.jsindex bcdef6b..c544c1f 100644--- a/test/system-theme.test.js+++ b/test/system-theme.test.js@@ -12,7 +12,7 @@ const applySource = source.slice(applyStart, source.indexOf('\n/**', applyStart)function applyContext(overrides = {}) {const context = {PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },- readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0,+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0,currentAccount: () => null, getTheme: () => ({ dark: true, colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',wallpaperRotation: { status: () => ({ mode: 'manual' }) },@@ -44,7 +44,7 @@ for (const automatic of [false, true]) test('later manual choice cancels a penditest('disabling takeover during a system lookup prevents application', async () => {let resolve, takeover = true;const context = applyContext({- readSessionState: () => ({ themeTakeoverEnabled: takeover }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: takeover }),resolveSystemTheme: () => new Promise(done => { resolve = done; }),cdpSend: async () => { throw new Error('must not apply'); },});@@ -83,7 +83,7 @@ function systemContext(overrides = {}) {const context = {PROFILE: { capabilities: { theme: true } }, process: { platform: 'linux' },cdp: { connected: true }, readSavedThemeId: () => 'system',- readSessionState: () => ({ themeTakeoverEnabled: true }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: true }),setInterval: () => ({ unref() {} }), clearInterval() {},cdpSend: async () => ({ result: { value: 'dark' } }),...overrides,@@ -201,7 +201,7 @@ for (const profile of ['codebuddy-cn', 'codebuddy-intl']) test(profile + ' follolet tick, timerCount = 0, stopped = 0, mode = 'default', calls = 0;const native = { id: profile, capabilities: { theme: true, nativeComposer: true, themeTakeover: false } };const context = systemContext({ ...applyContext(), PROFILE: native,- readSessionState: () => ({ themeTakeoverEnabled: false }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: false }),setInterval: fn => { tick = fn; timerCount++; return { unref() {} }; }, clearInterval: () => { stopped++; },resolveSystemTheme: async () => mode,cdpSend: async (_, params) => {@@ -226,7 +226,7 @@ for (const nativeOnly of [false, true]) test('native manual selection cancels alet finish, calls = 0;const context = applyContext({PROFILE: { capabilities: { theme: true, nativeComposer: true, themeTakeover: false } },- readSessionState: () => ({ themeTakeoverEnabled: false }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: false }),resolveSystemTheme: () => new Promise(resolve => { finish = resolve; }),cdpSend: async (_, params) => {calls++;@@ -248,7 +248,7 @@ test('CodeBuddy restores system mode after reconnect while leaving native manualconst context = {PROFILE: { capabilities: { theme: true, nativeComposer: true, themeTakeover: false } },cdp: { connected: true }, readSavedThemeId: () => saved,- readSessionState: () => ({ themeTakeoverEnabled: false }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: false }),applyThemeByCdp: async (id, options) => { applied.push({ id, ...options }); },};vm.runInNewContext(restore, context);diff --git a/test/theme-restore-stability.test.js b/test/theme-restore-stability.test.jsindex 10683d2..e792ab3 100644--- a/test/theme-restore-stability.test.js+++ b/test/theme-restore-stability.test.js@@ -15,7 +15,7 @@ for (const saved of ['default', 'dark', 'eye-care', 'cyber-purple', 'nebula', 'sconst applied = [];const context = {PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },- readSessionState: () => ({ themeTakeoverEnabled: true }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: true }),DATA_DIR: '/test', path, fs: { readFileSync: () => saved === null ? '{invalid' : JSON.stringify({id:saved}) },getTheme: id => ['default','dark','eye-care','cyber-purple','nebula'].includes(id),applyThemeByCdp: async id => applied.push(id),@@ -32,7 +32,7 @@ test('follow-system apply resolves once and reuses the normal theme pipeline', alet pollingStarted = 0, resolutions = 0;const context = {PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },- readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0, stopSystemThemePolling() {},+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0, stopSystemThemePolling() {},currentAccount: () => null, getTheme: () => ({ dark: true, colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',setTimeout: resolve => resolve(),@@ -60,7 +60,7 @@ async function themeExpression(id, takeover = true, accountUid = null, options =const context = {wallpaperRotation: { status: () => ({ mode: 'manual' }) },PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },- readSessionState: () => ({ themeTakeoverEnabled: takeover }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: takeover }),themeApplyGeneration: 0, stopSystemThemePolling() {},setTimeout: resolve => resolve(),currentAccount: () => accountUid ? { uid: accountUid } : null, getTheme: () => ({ dark: id !== 'default', colors: {} }),@@ -108,7 +108,7 @@ for (const initial of ['default', 'dark']) test('system polling follows repeatedlet appearance = initial, timer = 0, evaluations = 0;const daemon = {PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },- readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0,+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0,readSavedThemeId: () => 'system', currentAccount: () => null,getTheme: id => ({ dark: id !== 'default', colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',@@ -244,7 +244,7 @@ test('theme takeover opt-out follows native appearance on reload without forcingconst context = {PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },DATA_DIR: '/test', path, fs: { existsSync: () => true, readFileSync: () => '{"id":"nebula"}' },- readSessionState: () => ({ themeTakeoverEnabled: false }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: false }),startNativeAppearanceSyncByCdp: async () => applied.push('native'),applyThemeByCdp: async id => applied.push(id),};@@ -306,7 +306,7 @@ test('turning off takeover restores the WorkBuddy appearance saved before takeovcontext.localStorage.setItem('workbuddy.appearance.mode::personal::personal::other', 'dark');const daemon = {cdp: { connected: true }, themeApplyGeneration: 0, stopSystemThemePolling() {},- readSessionState: () => ({ themeTakeoverEnabled: false }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: false }),currentAccount: () => ({ uid }),cdpSend: async (_, params) => { vm.runInNewContext(params.expression, context); return {}; },startNativeAppearanceSyncByCdp: async () => {@@ -438,7 +438,7 @@ test('a pending light reset cannot overwrite takeover re-enabled during a CDP reconst context = {wallpaperRotation: { status: () => ({ mode: 'manual' }) },PROFILE: { capabilities: { theme: true } }, cdp: { connected: true, ws: { readyState: 1 } },- readSessionState: () => ({ themeTakeoverEnabled: takeover }), themeApplyGeneration: 0, stopSystemThemePolling() {},+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: takeover }), themeApplyGeneration: 0, stopSystemThemePolling() {},currentAccount: () => null, getTheme: () => ({ dark: false, colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',cdpSend: async () => { evaluations++; takeover = true; context.themeApplyGeneration++; return { result: { value: { pending: true } } }; },@@ -468,7 +468,7 @@ test('release resets light once then follows official dark and special skins acrconst daemon = {wallpaperRotation: { status: () => ({ mode: 'manual' }) },PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0, stopSystemThemePolling() {},- readSessionState: () => ({ themeTakeoverEnabled: false }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: false }),cdpSend: async (_, params) => { vm.runInNewContext(params.expression, context); return {}; },applyThemeByCdp: async (id, options) => {lightResets++;@@ -557,7 +557,7 @@ test('nebula releases custom CSS and guards, waits for official dark, then reappwallpaperRotation: { status: () => ({ mode: 'manual' }) },PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0, stopSystemThemePolling() {},setTimeout: resolve => resolve(),- readSessionState: () => ({ themeTakeoverEnabled: true }), currentAccount: () => ({ uid: 'current' }),+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: true }), currentAccount: () => ({ uid: 'current' }),getTheme: id => ({ dark: id !== 'default', colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',cdpSend: async (_, params) => {@@ -653,7 +653,7 @@ test('frosted takeover completes even when background renderer timers and animatconst daemon = {wallpaperRotation: { status: () => ({ mode: 'manual' }) },PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0, stopSystemThemePolling() {},- readSessionState: () => ({ themeTakeoverEnabled: true }), currentAccount: () => null,+ lastVideoKey: '', readSessionState: () => ({ themeTakeoverEnabled: true }), currentAccount: () => null,getTheme: () => ({ dark: true, colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',setTimeout: (resolve, ms) => { delays.push(ms); resolve(); },diff --git a/test/theme-video.test.js b/test/theme-video.test.jsnew file mode 100644index 0000000..4999b33--- /dev/null+++ b/test/theme-video.test.js@@ -0,0 +1,281 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const vm = require('node:vm');+const {+ VIDEO_MAX_BYTES, VIDEO_LAYER_CSS,+ sniffVideo, resolveVideoFile, videoRootBackground,+ updateVideoInRenderer, disposeVideoInRenderer,+} = require('../scripts/wallpaper-video');++function mp4(brand = 'isom') {+ const b = Buffer.alloc(32);+ b.writeUInt32BE(32, 0); b.write('ftyp', 4, 'ascii'); b.write(brand, 8, 'ascii');+ return b;+}+function webm(docType = 'webm') {+ const b = Buffer.alloc(64);+ b.writeUInt32BE(0x1a45dfa3, 0); b.write(docType, 24, 'latin1');+ return b;+}++test('sniffVideo accepts only browser-playable containers and trusts magic bytes', () => {+ assert.deepEqual([sniffVideo(mp4()).ext, sniffVideo(mp4()).mime], ['mp4', 'video/mp4']);+ assert.deepEqual([sniffVideo(webm()).ext, sniffVideo(webm()).mime], ['webm', 'video/webm']);+ // 同结构但不是视频的图片容器+ assert.equal(sniffVideo(mp4('heic')), null);+ assert.equal(sniffVideo(mp4('avif')), null);+ // mkv 是 EBML 但不是 webm,Chromium 播不了+ assert.equal(sniffVideo(webm('matroska')), null);+ assert.equal(sniffVideo(Buffer.from('\x00\x00\x00\x18ftypmp4')), null);+ assert.equal(sniffVideo(Buffer.alloc(0)), null);+ assert.equal(sniffVideo(Buffer.from('not a video at all, just text')), null);+});++test('resolveVideoFile stays inside themes/ and falls back to the file name layout', async t => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-video-'));+ t.after(() => fs.promises.rm(dir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(dir, 'nebula'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'nebula', 'background.mp4'), mp4());+ assert.equal(resolveVideoFile(dir, 'nebula', 'background.mp4'), path.join(dir, 'nebula', 'background.mp4'));+ // 主题 id 里的路径分隔符会被压成下划线,不可能逃出 themes/+ assert.equal(resolveVideoFile(dir, '../nebula', 'background.mp4'), null);+ // video 字段写成分散路径时只取文件名,仍落在该主题目录内+ assert.equal(resolveVideoFile(dir, 'nebula', '../background.mp4'), path.join(dir, 'nebula', 'background.mp4'));+ assert.equal(resolveVideoFile(dir, 'nebula', 'missing.mp4'), null);+ assert.equal(resolveVideoFile(dir, '', 'background.mp4'), null);+});++test('video background keeps the shared mask but drops the image layer', () => {+ const css = videoRootBackground(0.45);+ assert.match(css, /rgba\(0,0,0,0\.45\)/);+ assert.doesNotMatch(css, /url\(/);+ // 蒙版可关:0 不能被兜底成默认值+ assert.match(videoRootBackground(0), /rgba\(0,0,0,0\)/);+ assert.match(videoRootBackground(-1), /rgba\(0,0,0,0\)/);+ assert.match(videoRootBackground(9), /rgba\(0,0,0,1\)/);+ assert.match(VIDEO_LAYER_CSS, /z-index:-1/);+ assert.match(VIDEO_LAYER_CSS, /pointer-events:none/);+});++/** 极简 DOM:只实现 updateVideoInRenderer 真正用到的接口。 */+function fakeWallpaperDom() {+ const fetched = [];+ const revoked = [];+ let hostCount = 0;+ function element(tag) {+ const listeners = new Map();+ const el = {+ tagName: tag, id: '', parentNode: null, isConnected: false, readyState: 0, style: {},+ attrs: {}, children: [], classList: {+ set: new Set(),+ add(c) { this.set.add(c); }, remove(c) { this.set.delete(c); }, contains(c) { return this.set.has(c); },+ },+ setAttribute(k, v) { this.attrs[k] = String(v); },+ getAttribute(k) { return Object.prototype.hasOwnProperty.call(this.attrs, k) ? this.attrs[k] : null; },+ removeAttribute(k) { delete this.attrs[k]; },+ appendChild(child) { return el.insertBefore(child, null); },+ insertBefore(child, ref) {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = el;+ const at = ref ? el.children.indexOf(ref) : -1;+ if (at < 0) el.children.push(child); else el.children.splice(at, 0, child);+ child.isConnected = true;+ return child;+ },+ removeChild(child) {+ const at = el.children.indexOf(child);+ if (at >= 0) el.children.splice(at, 1);+ child.parentNode = null; child.isConnected = false;+ return child;+ },+ querySelector(sel) {+ const want = sel.replace(/^[#.]/, '');+ return el.children.find(c => (sel[0] === '#' ? c.id : c.tagName) === want) || null;+ },+ querySelectorAll() { return []; },+ addEventListener(type, fn) { listeners.set(type, fn); },+ removeEventListener(type) { listeners.delete(type); },+ dispatch(type) { const fn = listeners.get(type); if (fn) { listeners.delete(type); fn(); } },+ play() { el.playCount = (el.playCount || 0) + 1; return Promise.resolve(); },+ pause() { el.pauseCount = (el.pauseCount || 0) + 1; },+ load() { el.readyState = 4; setTimeout(() => el.dispatch('loadeddata'), 0); },+ };+ if (tag === 'div') hostCount++;+ return el;+ }+ const body = element('body');+ const head = element('head');+ const docListeners = new Map();+ const document = {+ hidden: false,+ body,+ head,+ documentElement: element('html'),+ createElement: element,+ getElementById(id) {+ const walk = node => {+ for (const child of node.children) {+ if (child.id === id) return child;+ const found = walk(child);+ if (found) return found;+ }+ return null;+ };+ return walk(body) || walk(head);+ },+ addEventListener(type, fn) { docListeners.set(type, fn); },+ removeEventListener(type) { docListeners.delete(type); },+ };+ const env = {+ window: {}, document,+ AbortController, setTimeout, clearTimeout,+ URL: {+ createObjectURL: () => 'blob:video-' + (revoked.length + 1),+ revokeObjectURL: url => revoked.push(url),+ },+ fetch: async (url, options) => {+ fetched.push({ url, options });+ return { ok: true, blob: async () => ({ size: 1024 }) };+ },+ Promise, console,+ };+ vm.createContext(env);+ vm.runInContext('var update = ' + updateVideoInRenderer.toString() + ';var dispose = ' + disposeVideoInRenderer.toString(), env);+ return { env, document, body, element, fetched, revoked, docListeners, hostCount: () => hostCount };+}++const settle = () => new Promise(resolve => setTimeout(resolve, 5));++test('renderer mounts one video layer under body, muted and looping, and reuses it for the same key', async () => {+ const dom = fakeWallpaperDom();+ const first = dom.env.update({+ url: '/api/theme-video?id=nebula', token: 'tok', key: 'nebula:background.mp4:1024:1',+ css: '#wbs-video-wallpaper{z-index:-1}',+ });+ await settle();+ assert.equal(await first, true);++ const host = dom.document.getElementById('wbs-video-wallpaper');+ assert.ok(host, 'video host exists');+ assert.equal(dom.body.children[0], host, 'host is body\'s first child so #root paints the mask above it');+ assert.equal(dom.fetched.length, 1);+ assert.equal(dom.fetched[0].options.headers['X-WorkDaddy-Token'], 'tok');+ // 视频层样式独立挂在 head 上,不随主题样式表重写+ const style = dom.document.getElementById('wbs-video-style');+ assert.ok(style, 'layer keeps its own style element');+ assert.equal(style.textContent, '#wbs-video-wallpaper{z-index:-1}');++ const video = host.querySelector('video');+ assert.equal(video.muted, true, 'autoplay only works muted');+ assert.equal(video.loop, true);+ assert.equal(video.attrs.muted, '');+ assert.equal(video.attrs.playsinline, '');+ assert.equal(video.src, 'blob:video-1');+ assert.equal(host.classList.contains('wbs-video-ready'), true);+ assert.equal(video.playCount >= 1, true);++ // 同样的 key(拖蒙版/改毛玻璃会重复应用主题)不能再拉一遍视频+ assert.equal(await dom.env.update({ url: '/api/theme-video?id=nebula', token: 'tok', key: 'nebula:background.mp4:1024:1', css: '' }), true);+ await settle();+ assert.equal(dom.fetched.length, 1, 'same key must not refetch');+ assert.equal(dom.document.getElementById('wbs-video-wallpaper'), host, 'no duplicate layer');+ assert.equal(dom.document.head.children.length, 1, 'style element is reused, not stacked');+});++test('renderer replaces the layer for a new key and dispose removes it completely', async () => {+ const dom = fakeWallpaperDom();+ const first = dom.env.update({ url: '/a', token: 'tok', key: 'k1', css: 'a{}' });+ await settle();+ assert.equal(await first, true);++ const second = dom.env.update({ url: '/b', token: 'tok', key: 'k2', css: 'b{}' });+ await settle();+ assert.equal(await second, true);+ assert.equal(dom.fetched.length, 2);+ assert.deepEqual(dom.revoked, ['blob:video-1'], 'previous blob released');++ dom.env.dispose();+ assert.equal(dom.document.getElementById('wbs-video-wallpaper'), null);+ assert.equal(dom.body.children.length, 0, 'no leftover node');+ assert.equal(dom.document.getElementById('wbs-video-style'), null, 'style element removed with the layer');+ assert.equal(dom.env.window.__wbsVideoRuntime, undefined);+});++test('video layer pauses while the window is hidden', async () => {+ const dom = fakeWallpaperDom();+ const loading = dom.env.update({ url: '/a', token: 'tok', key: 'k1' });+ await settle();+ await loading;+ const video = dom.document.getElementById('wbs-video-wallpaper').querySelector('video');+ const before = video.playCount;+ dom.document.hidden = true;+ dom.docListeners.get('visibilitychange')();+ assert.equal(video.pauseCount >= 1, true);+ dom.document.hidden = false;+ dom.docListeners.get('visibilitychange')();+ assert.equal(video.playCount > before, true);+});++test('video size limit is explicit and generous enough for a short clip loop', () => {+ assert.equal(VIDEO_MAX_BYTES, 128 * 1024 * 1024);+});++const daemonSource = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');++/** 在沙箱里跑真正的 applyThemeByCdp,拿它生成的注入表达式。 */+async function applyThemeSandbox(t, theme, extra = {}) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-theme-video-'));+ t.after(() => fs.promises.rm(dir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(dir, 'nebula'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'nebula', 'background.mp4'), mp4());+ const start = daemonSource.indexOf('async function applyThemeByCdp(id, options = {})');+ const end = daemonSource.indexOf('\n/**', start);+ const seen = { expression: '', applied: [], disposed: 0 };+ const context = {+ PROFILE: { name: 'WorkBuddy', capabilities: { theme: true } },+ cdp: { connected: true, ws: { readyState: 1 } },+ readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0,+ stopSystemThemePolling() {}, currentAccount: () => null, log: () => {},+ getTheme: () => theme, THEMES_DIR: dir, DATA_DIR: dir, path, fs,+ LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',+ MAX_BACKGROUND_BLUR_PX: 24, readBackgroundBlur: () => 0,+ resolveVideoFile, VIDEO_LAYER_CSS, videoRootBackground,+ lastVideoKey: '', wallpaperRotation: { status: () => ({ mode: 'manual' }) },+ setTimeout: resolve => resolve(),+ applyVideoWallpaperByCdp: async (video, id) => { seen.applied.push([id, video.name]); return true; },+ disposeVideoWallpaperByCdp: async () => { seen.disposed++; return true; },+ cdpSend: async (_method, params) => {+ seen.expression = params.expression;+ // nebula 会先要求官方深色就绪(ready),再注入毛玻璃样式+ return { result: { value: { applied: true, ready: true, dark: true, bg: '', text: '' } } };+ },+ ...extra,+ };+ vm.runInNewContext(daemonSource.slice(start, end), context);+ await context.applyThemeByCdp('nebula');+ return seen;+}++test('theme apply hands the video layer to the renderer instead of a data URL background', async t => {+ const seen = await applyThemeSandbox(t, {+ id: 'nebula', dark: true, colors: { '--wb-bg-primary': '#111' }, video: 'background.mp4',+ });+ assert.match(seen.expression, /#root\{background:linear-gradient\(rgba\(0,0,0,0\.3\)/);+ assert.doesNotMatch(seen.expression, /data:image/, 'video mode must not embed an image background');+ assert.deepEqual(seen.applied, [['nebula', 'background.mp4']]);+ assert.equal(seen.disposed, 0);+});++test('theme apply without a video tears down a previously mounted layer', async t => {+ const seen = await applyThemeSandbox(t, { id: 'nebula', dark: true, colors: {} }, { lastVideoKey: 'nebula:background.mp4:1:1' });+ // 注入表达式本身就带兜底清理(daemon 重启后 lastVideoKey 为空也能摘掉旧层)+ assert.match(seen.expression, /window\.__wbsVideoRuntime\.dispose\(\)/);+ assert.deepEqual(seen.applied, []);+ // nebula 会先做一次官方深色预置(nativeOnly,videoPreflight),那里也会清一次视频层;+ // 真实实现清完会把 lastVideoKey 置空,所以外层那次是空操作。+ assert.ok(seen.disposed >= 1, 'previous layer must be removed');+});