WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
release: merge 1.2.16 changes
[email protected]28796a85ac34
diff --git a/README.md b/README.mdindex edca152..984c2bf 100644--- a/README.md+++ b/README.md@@ -26,7 +26,7 @@ CodeBuddy 支持范围为 **Electron 智能体窗口**,不包含 VS Code 编- **自动化任务**:从 GitHub / Gitee 公开仓库发现并导入任务,或用自然语言让 WorkBuddy 创建任务;支持编辑、手动、事件和定时触发,以及运行日志、停止任务和 JSON / ZIP 导出。- **权限弹窗免打扰**:真正的零决策弹窗弹出,可以放心开启任务后睡觉。- **暂存提示词**:输入框边上一键把草稿「暂存」到待发送队列——图片 / 文件 / 引用原样保留,择机发送。-- **切换精美主题**:WorkBuddy 的「接管主题」提供浅色、深色、护眼绿、赛博紫、毛玻璃五种外观;毛玻璃支持预设和自定义壁纸,关闭接管后恢复客户端原生主题。+- **切换精美主题**:WorkBuddy 的「接管主题」提供跟随系统、浅色、深色、护眼绿、赛博紫、毛玻璃六种外观;「跟随系统」监听操作系统的深浅色模式变化自动切换,毛玻璃支持预设和自定义壁纸,关闭接管后恢复客户端原生主题。- **账号间会话迁移**:自动或手动跨账号复制会话,跨账号继续接龙。- **会话分支**:在「增强」页开启后,任意一条回复都能从此处开始新会话——复制到该条回复为止的聊天内容,原会话保持不变,可在当前工作区继续聊。- **模型切换更便捷**:解决 WorkBuddy 不支持添加多个同名模型的问题。@@ -254,7 +254,7 @@ WorkBuddy / CodeBuddy Electron 窗口右下角的机器人按钮 → 弹出面| Tab | 能做什么 || ------- | ------------------------------------------------------------------------------- || **账号** | 查看账号数、积分、模型频率限制与预计解封时间、当日签到状态、连续活跃天数、成长任务进度及 Buddy 旅行状态;切换、删除或登录新账号,并加密导入导出账号备份 |-| **主题** | WorkBuddy:接管主题并选择五种外观,管理壁纸、头像和背景;CodeBuddy:黑白悬浮机器人设置 |+| **主题** | WorkBuddy:接管主题并选择六种外观(含跟随系统),管理壁纸、头像和背景;CodeBuddy:黑白悬浮机器人设置 || **会话** | 按账号和时间筛选会话,批量复制或删除,并设置会话 / 工作空间在切换账号时自动复制 || **模型** | 管理当前模型和备选模型,支持备份、复制、编辑、启用、连通测试及批量删除 || **增强** | 配置权限免打扰、异常中断自动续接、会话分支、暂存提示词和快捷短语 |diff --git a/README_en.md b/README_en.mdindex 9e466cc..d91907a 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 Light, Dark, Eye-care green, Cyber purple, and Frosted glass. 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 and custom wallpapers; 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.@@ -223,7 +223,7 @@ Click the robot button in the lower-right corner of WorkBuddy or the CodeBuddy E| Tab | Purpose || -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- || **Accounts** | View account counts, credits, model rate limits and estimated reset times, daily check-in status, consecutive active days, growth progress, and Buddy travel status; switch, delete, or add accounts; import/export encrypted backups |-| **Theme** | WorkBuddy: manage five themes, wallpapers, avatars, blur, and overlays. CodeBuddy: black or white floating robot settings |+| **Theme** | WorkBuddy: manage six themes (including follow system), wallpapers, avatars, blur, and overlays. CodeBuddy: black or white floating robot settings || **Sessions** | Filter by account and date, copy or delete in bulk, and configure automatic session or workspace copying when switching accounts || **Models** | Manage current and alternative models, including backups, copying, editing, enabling, connectivity tests, and bulk deletion || **Enhance** | Configure quiet approvals, auto-continue, session branching, prompt stashing, and quick phrases |diff --git a/scripts/automation-account-sync.js b/scripts/automation-account-sync.jsnew file mode 100644index 0000000..97b4948--- /dev/null+++ b/scripts/automation-account-sync.js@@ -0,0 +1,112 @@+'use strict';++const fs = require('fs');+const path = require('path');+const { readAutomations, writeAutomations } = require('./automation.js');++const SETTINGS_FILE = 'automation-sync.json';+const ACCOUNT_SCOPE_KEY = 'x-workdaddy-account-uids';++function cleanUid(value) {+ const uid = String(value || '').trim();+ return /^[A-Za-z0-9_-]{1,128}$/.test(uid) ? uid : '';+}++function taskAccountUids(task) {+ const raw = task && task[ACCOUNT_SCOPE_KEY];+ if (!Array.isArray(raw)) return null;+ return [...new Set(raw.map(cleanUid).filter(Boolean))];+}++function taskVisibleToAccount(task, uid) {+ const scope = taskAccountUids(task);+ // Tasks written before account-aware syncing are intentionally global.+ return !scope || !scope.length || scope.includes(cleanUid(uid));+}++function scopeTaskToAccount(task, uid) {+ const accountUid = cleanUid(uid);+ if (!accountUid) return task;+ const scope = taskAccountUids(task) || [];+ if (scope.includes(accountUid)) return task;+ return { ...task, [ACCOUNT_SCOPE_KEY]: [...scope, accountUid] };+}++function isScheduledTask(task) {+ const schedule = task && task.schedule;+ return !!schedule && typeof schedule === 'object' && !Array.isArray(schedule) &&+ typeof schedule.type === 'string' && schedule.type !== 'manual';+}++function readAutomationSyncSettings(dataDir) {+ try {+ const value = JSON.parse(fs.readFileSync(path.join(dataDir, SETTINGS_FILE), 'utf8'));+ return { enabled: value && value.enabled === true };+ } catch (_) {+ return { enabled: false };+ }+}++function readBuiltinTaskIds(dataDir) {+ try {+ const value = JSON.parse(fs.readFileSync(path.join(dataDir, 'automation-builtins.json'), 'utf8'));+ return new Set(Object.keys(value || {}).filter((id) => value[id] === true || value[id] && value[id].managed === true));+ } catch (_) {+ return new Set();+ }+}++function writeAutomationSyncSettings(dataDir, enabled) {+ fs.mkdirSync(dataDir, { recursive: true });+ const file = path.join(dataDir, SETTINGS_FILE);+ const tmp = `${file}.tmp-${process.pid}`;+ fs.writeFileSync(tmp, JSON.stringify({ enabled: enabled === true }, null, 2) + '\n', { mode: 0o600 });+ fs.renameSync(tmp, file);+ return { enabled: enabled === true };+}++function readAccountAutomations(dataDir, uid) {+ return readAutomations(dataDir).filter((task) => taskVisibleToAccount(task, uid));+}++function syncAutomationsToAccount(dataDir, sourceUid, targetUid) {+ const source = cleanUid(sourceUid);+ const target = cleanUid(targetUid);+ if (!source || !target || source === target) return { copied: 0, skipped: 0, total: 0 };+ const tasks = readAutomations(dataDir);+ const builtinIds = readBuiltinTaskIds(dataDir);+ const sourceTasks = tasks.filter((task) => taskVisibleToAccount(task, source) && isScheduledTask(task));+ let copied = 0;+ let skipped = 0;+ const next = tasks.map((task) => {+ const scope = taskAccountUids(task);+ // Legacy/global tasks already run for the target and need no mutation.+ if (!isScheduledTask(task) || builtinIds.has(String(task.id || ''))) return task;+ // Tasks created before account-aware syncing had no scope. Treat the first+ // explicit sync as the user's request to bind that legacy task to the+ // source and destination accounts; built-ins remain global.+ if (!scope || !scope.length) {+ copied++;+ return scopeTaskToAccount(scopeTaskToAccount(task, source), target);+ }+ if (!scope.includes(source)) return task;+ if (scope.includes(target)) { skipped++; return task; }+ copied++;+ return scopeTaskToAccount(task, target);+ });+ if (copied) writeAutomations(dataDir, next);+ return { copied, skipped, total: sourceTasks.length };+}++module.exports = {+ ACCOUNT_SCOPE_KEY,+ cleanUid,+ taskAccountUids,+ taskVisibleToAccount,+ isScheduledTask,+ scopeTaskToAccount,+ readAutomationSyncSettings,+ writeAutomationSyncSettings,+ readAccountAutomations,+ syncAutomationsToAccount,+};diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 3904cfd..4769aef 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 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-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 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 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 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 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/cdp-targets.js b/scripts/cdp-targets.jsindex df3e99e..3f1c5ad 100644--- a/scripts/cdp-targets.js+++ b/scripts/cdp-targets.js@@ -1,5 +1,7 @@'use strict';+const { win32: winPath } = require('node:path');+// CDP target 归属判定(纯函数,无副作用,便于单测)。// 背景:WorkDaddy 现在支持四个客户端(WorkBuddy CN / WorkBuddy AI / CodeBuddy CN /// CodeBuddy 国际版),每个客户端由独立 daemon(WBSWITCH_PROFILE 绑定)驱动。旧版未绑定@@ -7,8 +9,8 @@// "这是 WorkBuddy",容易把兄弟客户端的页面误认成自己的注入目标:// - 对别人的页面执行注入(把组件送错端);// - 注入失败后反复重试,每次先清理旧组件,把对方 daemon 注入好的组件也一并销毁。-// 本模块提供严格的归属判定:优先依据应用包路径 / 登录域名(强信号),拒绝一切明确属于-// 其他客户端的页面;无强信号时才按 profile 类型走宽松兜底。+// 本模块提供严格的归属判定:自定义 Windows 目标先核对所选安装目录;其余目标+// 优先依据应用包路径 / 登录域名(强信号),无强信号时才按 profile 类型走兜底。/*** 归一化 URL:Electron file:// URL 中空格编码为 %20(如 WorkBuddy%20AI.app),@@ -95,8 +97,24 @@ function isTargetForProfile(target, profile) {const desc = String(target.description || '');const haystack = `${url} ${title} ${desc}`;+ // 自定义 Windows 客户端的安装路径是用户显式绑定的身份,可能与基础 profile+ // 的 CN/AI 分类不同。file 页面必须位于所选程序的安装目录内,不能用通用标题+ // 或裸应用名覆盖目录不匹配,否则会认领另一安装目录下的同名客户端。+ if (profile.customTarget && /^[A-Za-z]:[\\/]/.test(profile.appPath || '') && /^file:/i.test(url)) {+ try {+ const pageUrl = new URL(url);+ if (pageUrl.hostname) return false;+ const pagePath = decodeURIComponent(pageUrl.pathname);+ if (!/^\/[A-Za-z]:\//.test(pagePath)) return false;+ const relative = winPath.relative(winPath.dirname(profile.appPath), pagePath.slice(1));+ return !!relative && relative !== '..' && !relative.startsWith('..\\') && !winPath.isAbsolute(relative);+ } catch (_) {+ return false;+ }+ }+// Windows 官方安装目录的 app.asar 路径是比标题更可靠的归属证据,必须先于- // customTarget/标题兜底判断;企业目标仍保留自己的精确信号策略。+ // 标题兜底判断;自定义目标已先按所选安装目录判断。const cls = classifyTarget(url, title, desc);const normalizedUrl = normalizeTargetUrl(url);const windowsOfficialPath = /^file:\/\/\/[A-Za-z]:\//i.test(normalizedUrl) && (diff --git a/scripts/client-launch-settings.js b/scripts/client-launch-settings.jsnew file mode 100644index 0000000..8ec8e33--- /dev/null+++ b/scripts/client-launch-settings.js@@ -0,0 +1,45 @@+'use strict';++const fs = require('fs');+const path = require('path');+const { replaceFileWithRetry } = require('./atomic-file-write.js');++// Fixed allowlist only: never turn a local API payload into arbitrary Electron flags.+const SOFTWARE_RENDERING_ARGS = [+ '--disable-gpu',+ '--use-gl=angle',+ '--use-angle=swiftshader-webgl',+ '--enable-unsafe-swiftshader',+];++function supportsClientLaunchSettings(profileId, platform) {+ return platform === 'win32' && profileId === 'workbuddy-ai';+}++function readClientLaunchSettings(dataDir, profileId, platform = process.platform) {+ const supported = supportsClientLaunchSettings(profileId, platform);+ let softwareRendering = false;+ if (supported) {+ try {+ const settings = JSON.parse(fs.readFileSync(path.join(dataDir, 'client-launch-settings.json'), 'utf8'));+ softwareRendering = !!settings && settings.softwareRendering === true;+ } catch (_) { /* Missing or invalid settings retain the official default. */ }+ }+ return { supported, softwareRendering };+}++function setClientLaunchSettings(dataDir, profileId, body, platform = process.platform) {+ if (!supportsClientLaunchSettings(profileId, platform)) throw new Error('当前客户端不支持此兼容设置');+ if (!body || typeof body.softwareRendering !== 'boolean') throw new Error('软件渲染开关值必须是布尔值');+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });+ replaceFileWithRetry(path.join(dataDir, 'client-launch-settings.json'),+ JSON.stringify({ softwareRendering: body.softwareRendering }, null, 2) + '\n', 0o600);+ return readClientLaunchSettings(dataDir, profileId, platform);+}++function getClientLaunchArgs(dataDir, profileId, platform = process.platform) {+ return readClientLaunchSettings(dataDir, profileId, platform).softwareRendering+ ? SOFTWARE_RENDERING_ARGS.slice() : [];+}++module.exports = { readClientLaunchSettings, setClientLaunchSettings, getClientLaunchArgs };diff --git a/scripts/daemon.js b/scripts/daemon.jsindex b6f50c5..9e7c43f 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -33,6 +33,9 @@ let sessionSync = require('./session-sync.js');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 { readClientLaunchSettings, setClientLaunchSettings, getClientLaunchArgs } = require('./client-launch-settings.js');+const { getWorkBuddyLaunchEnv } = require('./workbuddy-launch-env.js');const PROBE_CLIENT_RUNNING = process.argv.includes('--probe-client-running');const {assertSameProcessIdentity,@@ -207,6 +210,14 @@ const {installBuiltinTask,removeBuiltinTasks,} = require('./automation.js');+const {+ ACCOUNT_SCOPE_KEY: AUTOMATION_ACCOUNT_SCOPE_KEY,+ readAccountAutomations,+ readAutomationSyncSettings,+ writeAutomationSyncSettings,+ syncAutomationsToAccount,+ scopeTaskToAccount,+} = require('./automation-account-sync.js');const { assertAccountRequestUrl, createTaskState, cancellableWait, createRendererGate, probeSessionReceipt, receiptComplete } = require('./automation-runtime.js');const { normalizeAutomationModelId, selectAutomationModel, verifyAutomationModel, restoreNewTaskModelPreference } = require('./automation-model.js');@@ -218,6 +229,7 @@ const { previewPackage, PACKAGE_FORMAT_VERSION } = require('./automation-packageconst { exportTasks, importTasks, readTransferBody } = require('./automation-transfer.js');const { createAutomationDiscovery } = require('./automation-discovery.js');const { createAutomationLikesClient } = require('./automation-likes.js');+const { createOfficialAutomationSync } = require('./official-automation-sync.js');const { createAutomationNotifier } = require('./toast-options.js');const { runCompletionReport, probeAccountCompletion } = require('./completion-report.js');@@ -499,8 +511,23 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.2.45:同步功能统一使用 WorkBuddy 的「个性化」名称。// 1.2.43:共享身份提示使用全局说明浮层,来源列出未设置账号并简化文案。// 1.2.46:合入失效卷上的会话目录修复保护,避免后台反复尝试创建目录。-const DAEMON_VERSION = '1.2.46';-const DAEMON_BUILD_ID = 'release-1.2.46-session-cwd-volume-guard';+// 1.2.47:CodeBuddy 主题页支持切换官方浅色/深色外观。+// 1.2.48:支持本地文件夹原图随机轮换壁纸,切换时复用主题并释放旧图资源。+// 1.2.49:换号刷新回退清除旧账号快照;Windows AI 支持持久化软件渲染兼容设置。+// 1.2.53:账号明文模式避开 WorkBuddy 已脱敏占位值;官方定时任务副本按最近编辑清理。+// 1.2.54:手机号栏保留 WorkBuddy 官方脱敏手机号,不再误显示 UIN。+// 1.2.55:官方昵称已脱敏时,账号名称跟随手机号来源,避免 UIN/手机号混用。+// 1.2.56:从已验证的 access-token preferred_username 恢复官方脱敏手机号。+// 1.2.57:CodeBuddy CN 成长计划跳转到可操作的 WorkBuddy 成长中心。+// 1.2.58:官方定时任务按历史关联双向同步修改,保持已保存账号一致。+// 1.2.59:Windows 两端启动分别固定官方更新源、配置目录和临时缓存,避免串端更新。+// 1.2.60:自定义安装的 CDP 目标绑定到选定安装目录。+// 1.2.61:合入跟随系统主题,防止异步检测覆盖后续手动选择。+// 1.2.62:手动复制会话到当前账号后刷新官方列表,无需再次切号。+// 1.2.63:跟随系统将浅色恢复视为成功,持续轮询并更新外观基线。+// 1.2.64:CodeBuddy 原生主题支持跟随系统,重连恢复并与手动选择互斥。+const DAEMON_VERSION = '1.2.64';+const DAEMON_BUILD_ID = 'release-1.2.64-codebuddy-system-theme';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -1961,8 +1988,10 @@ const cdp = {ws: null,connected: false,port: null,+ endpointReachable: false,targetUrl: null,targetTitle: null,+ targetDescription: null,error: null,id: 0,pending: new Map(),@@ -2056,6 +2085,7 @@ function runPendingReloadInjection(reason, executionContextId) {}async function findCdpEndpoint() {+ cdp.endpointReachable = false;// profile 已由启动器绑定时不能扫描其他产品的端口;CodeBuddy Agents/Editor// 共用 Browser 标识,跨 profile 扫描会把注入发到另一端。//@@ -2075,7 +2105,9 @@ async function findCdpEndpoint() {]);const version = await versionRes.json();const list = await listRes.json();- const targets = Array.isArray(list) ? list : [];+ if (!version || typeof version.Browser !== 'string' || !Array.isArray(list)) continue;+ cdp.endpointReachable = true;+ const targets = list;const browserInfo = [version.Browser, version['User-Agent']].filter(Boolean).join(' ');const belongsToWorkBuddy = /workbuddy|codebuddy/i.test(browserInfo) || (IS_LINUX && targetsBelongToProfile(targets));if (belongsToWorkBuddy && targets.some(isWorkBuddyCdpTarget)) {@@ -2257,7 +2289,9 @@ async function connectCdp() {cdp.port = await findCdpEndpoint();if (!cdp.port) {cdp.connected = false;- cdp.error = '未发现 CDP 端口(WorkBuddy 需以 --remote-debugging-port 启动)';+ cdp.error = cdp.endpointReachable+ ? '调试端口可达,但未找到与当前配置匹配的客户端页面,请检查所选客户端路径与 profile 配置'+ : '未发现 CDP 端口(WorkBuddy 需以 --remote-debugging-port 启动)';return false;}const target = await getPageTarget(cdp.port).catch(() => null);@@ -2274,6 +2308,7 @@ async function connectCdp() {cdp.error = null;cdp.targetUrl = target.url || '';cdp.targetTitle = target.title || '';+ cdp.targetDescription = target.description || '';// Target ids survive a transient WebSocket reconnect but change with a// restarted renderer, unlike the navigation serial missed while offline.cdpPageSessionId = String(target.id || target.webSocketDebuggerUrl || 'unknown');@@ -2356,7 +2391,7 @@ function dispatchAutomationEvent(type, detail = {}) {automationEventKeys.add(key);while (automationEventKeys.size > 40) automationEventKeys.delete(automationEventKeys.values().next().value);}- const tasks = readAutomations(DATA_DIR).filter((task) => taskMatchesEvent(task, canonicalType, detail));+ const tasks = (typeof readCurrentAutomations === 'function' ? readCurrentAutomations() : readAutomations(DATA_DIR)).filter((task) => taskMatchesEvent(task, canonicalType, detail));if (!tasks.length) return;const account = detail.account || currentAccount();tasks.forEach((task) => {@@ -2667,8 +2702,8 @@ function resetClientDebugState() {}// clientRunning: true=进程在跑 / false=没跑 / null=未知(探测失败时不计数,避免误报)-function updateClientDebugState({ cdpConnected, clientRunning }) {- if (cdpConnected || clientRunning === false) {+function updateClientDebugState({ cdpConnected, cdpReachable, clientRunning }) {+ if (cdpConnected || cdpReachable || clientRunning === false) {return resetClientDebugState();}if (clientRunning !== true) return clientDebugState;@@ -2807,7 +2842,7 @@ async function cdpLoop() {// 不静默杀进程;恢复由用户在状态页一键触发(POST /api/client/relaunch)。try {// clientRunning 已由后台一次性子进程刷新,避免 cdpLoop 周期性阻塞事件循环。- updateClientDebugState({ cdpConnected: cdp.connected, clientRunning: clientRunningState.value });+ updateClientDebugState({ cdpConnected: cdp.connected, cdpReachable: cdp.endpointReachable, clientRunning: clientRunningState.value });} catch (e) {log(`[cdp] 客户端状态探测异常: ${e.message}`);}@@ -2865,7 +2900,27 @@ async function reloadWorkBuddyPage(options = {}) {log('[cdp] 账号快照导航失败,回退页面刷新');}}- if (!navigated) await withTimeout(cdpSend('Page.reload', { ignoreCache: false }), 10000, '刷新 WorkBuddy 页面');+ if (!navigated) {+ if (options.account && PROFILE.kind === 'workbuddy') {+ // profile IPC 可能尚未观察到登录文件变化。直接 reload 会再次 hydrate+ // URL 内旧账号的身份/套餐;清除快照后由官方正常 getAccount 流程恢复。+ let cleared = false;+ try {+ const result = await withTimeout(cdpSend('Runtime.evaluate', {+ expression: `(function () {+ var url = new URL(location.href);+ url.searchParams.delete('accountSnapshot');+ history.replaceState(history.state, '', url.href);+ return !new URL(location.href).searchParams.has('accountSnapshot');+ })()`,+ returnByValue: true,+ }), 10000, '清除旧账号快照');+ cleared = !!(result && !result.exceptionDetails && result.result && result.result.value === true);+ } catch (_) {}+ if (!cleared) throw new Error('无法清除旧账号快照,请重新打开 WorkDaddy 后重试切换');+ }+ await withTimeout(cdpSend('Page.reload', { ignoreCache: false }), 10000, '刷新 WorkBuddy 页面');+ }if (options.waitForInjection === false) return true;const mounted = await pending.ready;if (!mounted) log('[cdp] 页面重载后组件未在 5 秒内确认挂载,继续后台流程');@@ -3334,14 +3389,16 @@ function relaunchWorkBuddy() {}// 日志用 ASCII 标记(非用户可见文案,无需进 i18n 词典)log(`[logout] 以 ${environmentMode ? '环境变量' : '命令行参数'} CDP=${port} 重启 WorkBuddy: ${command}${viaLauncher ? ' [via launcher]' : ''}`);- const childEnv = { ...process.env };+ const childEnv = getWorkBuddyLaunchEnv(PROFILE, DATA_DIR, process.platform, process.env);if (environmentMode) childEnv.WORKBUDDY_REMOTE_DEBUGGING_PORT = String(port);if (viaLauncher) {// 关键:启动器要用它自己环境的 $HOME 反推真实家目录,必须还原真实 HOMEconst launcherHome = resolveLauncherHome(command);if (launcherHome) childEnv.HOME = launcherHome;}- const child = spawn(command, environmentMode ? [] : [`--remote-debugging-port=${port}`, ...(PROFILE.nativeDebugPort ? [`--inspect=127.0.0.1:${PROFILE.nativeDebugPort}`] : [])], {+ const args = environmentMode ? [] : [`--remote-debugging-port=${port}`, ...(PROFILE.nativeDebugPort ? [`--inspect=127.0.0.1:${PROFILE.nativeDebugPort}`] : [])];+ args.push(...getClientLaunchArgs(DATA_DIR, PROFILE.id, process.platform));+ const child = spawn(command, args, {detached: true,stdio: 'ignore',windowsHide: true,@@ -3875,12 +3932,23 @@ function automationSwitchAccount(account, options = {}) {try {if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');const active = currentAccount();+ const sourceUid = String(active && active.uid || '');if (active && active.uid === uid) return { ok: true, uid, switched: false };automationSwitchProgress(options, options.restore ? 'restoring-account' : 'switching-account');releaseRendererReload = beginRendererReloadPriority();await preserveAccountSwitchTheme(uid);if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');const acct = await switchAccountForProfile(uid);+ let automationSync = { enabled: false, copied: 0, skipped: 0, total: 0 };+ let officialAutomationSync = { enabled: false, copied: 0, skipped: 0, total: 0 };+ if (sourceUid && sourceUid !== uid && typeof automationSyncEnabled === 'function' && automationSyncEnabled()) {+ automationSync.enabled = true;+ try { Object.assign(automationSync, syncAccountAutomations(sourceUid, uid)); }+ catch (error) { automationSync.error = '定时任务同步失败'; log(`[automation-switch] 定时任务同步失败: ${error.message}`); }+ officialAutomationSync.enabled = true;+ try { Object.assign(officialAutomationSync, await syncOfficialAccountAutomations(sourceUid, uid)); }+ catch (error) { officialAutomationSync.error = '官方定时任务同步失败'; log(`[automation-switch] 官方定时任务同步失败: ${error.message}`); }+ }pendingAutomationAccountSwitch = { account: { uid: acct.uid, nickname: acct.nickname } };await reloadWorkBuddyPage({ account: acct });if (pendingAutomationAccountSwitch) {@@ -3888,7 +3956,6 @@ function automationSwitchAccount(account, options = {}) {pendingAutomationAccountSwitch = null;dispatchAutomationEvent('pageReady', { navigationSerial: mainFrameNavigationSerial, source: 'automation-account-switch', account: switchEvent.account });}- const sourceUid = String(active && active.uid || '');const rules = sourceUid ? getAutoCopyRules(DATA_DIR, sourceUid) : {};let job = null;if (rules.allSessions || (rules.sessionIds || []).length || (rules.workspaces || []).length) {@@ -3899,7 +3966,7 @@ function automationSwitchAccount(account, options = {}) {releaseRendererReload = null;if (job) await waitAutomationSyncJob(job, options);if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');- return { ok: true, uid: acct.uid, nickname: acct.nickname, switched: true, syncJobId: job ? job.id : null };+ return { ok: true, uid: acct.uid, nickname: acct.nickname, switched: true, syncJobId: job ? job.id : null, automationSync, officialAutomationSync };} catch (error) {pendingAutomationAccountSwitch = null;throw error;@@ -4173,7 +4240,7 @@ function resumeAutomationAfterNavigation(run) {const next = run.pendingEvent;run.pendingEvent = null;if (!next || next.navigationSerial !== mainFrameNavigationSerial || next.pageSessionId !== cdpPageSessionId) return;- const task = readAutomations(DATA_DIR).find((item) => item.id === run.taskId && item.enabled && item.trigger.restartOnNavigation);+ const task = (typeof readCurrentAutomations === 'function' ? readCurrentAutomations() : readAutomations(DATA_DIR)).find((item) => item.id === run.taskId && item.enabled && item.trigger.restartOnNavigation);if (task) startAutomationRun(task, next);}@@ -4496,11 +4563,11 @@ async function injectWidget(reason, executionContextId) {if (!cdp.connected) {return Promise.reject(new Error('CDP 未连接,无法注入组件'));}- // 防御闸:绝不向其他客户端的页面注入。四客户端支持后,未绑定 profile 的旧 daemon- // 可能扫到兄弟客户端页面;其余环节(归属判定/清理跳过)已拦截,这里作为最后一道保险。+ // 防御闸与发现/选页共用归属规则,既隔离兄弟客户端,也尊重自定义安装目录绑定。if (cdp.targetUrl) {- const cls = classifyTarget(cdp.targetUrl, cdp.targetTitle || '');- if (cls && cls !== PROFILE.id) {+ const target = { type: 'page', url: cdp.targetUrl, title: cdp.targetTitle || '', description: cdp.targetDescription || '' };+ if (!isTargetForProfile(target, PROFILE)) {+ const cls = classifyTarget(target.url, target.title, target.description) || 'unknown';log(`[cdp] 目标页面属于 ${cls}(当前 profile=${PROFILE.id}),拒绝注入`);return Promise.reject(new Error(`目标页面 ${cls} 不属于当前 profile ${PROFILE.id}`));}@@ -4592,6 +4659,7 @@ async function injectWidget(reason, executionContextId) {if (reason === 'manual') throw new Error('注入后未检测到 WorkDaddy 组件(请检查 WorkBuddy 页面是否正常加载)');} else {log(`[cdp] 注入结果确认(${reason}): root=true widget=true url=${state.url}`);+ if (wallpaperRotation.status().mode === 'random') wallpaperRotation.restore().catch(() => {});}return { result: r, mounted: Boolean(state && state.root && state.widget), state };})@@ -4737,6 +4805,13 @@ async function writeDiagnosticsSnapshot(reason) {// ===== SESSIONS_API_MARK:会话管理(读 WorkBuddy workbuddy.db)=====const SESSIONS_DB = PROFILE.sessionDb;const SESSION_DB = createSessionDb({ dbPath: SESSIONS_DB });+const officialAutomationSyncEngine = PROFILE.kind === 'workbuddy'+ ? createOfficialAutomationSync({+ dataDir: DATA_DIR,+ db: SESSION_DB,+ getAccountUids: () => listAccounts(DATA_DIR).map(account => account.uid),+ })+ : null;const CODEBUDDY_SESSIONS = PROFILE.kind === 'codebuddy' ? createCodeBuddySessionStore({readItems: async () => {const items=await codeBuddyNative.sessionItems();@@ -7607,6 +7682,24 @@ function currentAccount() {}}+function readCurrentAutomations() {+ const uid = String((currentAccount() || {}).uid || '').trim();+ return readAccountAutomations(DATA_DIR, uid);+}++function automationSyncEnabled() {+ return readAutomationSyncSettings(DATA_DIR).enabled === true;+}++function syncAccountAutomations(sourceUid, targetUid) {+ return syncAutomationsToAccount(DATA_DIR, sourceUid, targetUid);+}++async function syncOfficialAccountAutomations(sourceUid, targetUid) {+ if (!officialAutomationSyncEngine) return { copied: 0, skipped: 0, total: 0 };+ return officialAutomationSyncEngine(sourceUid, targetUid);+}+function accountBackupFile(uid) {const value = String(uid || '').trim();if (!/^[A-Za-z0-9_-]{1,128}$/.test(value)) {@@ -7777,6 +7870,26 @@ async function waitAiIdle(maxMs = 60000, pollMs = 500, isCancelled = () => falseconst THEMES_DIR = path.join(DATA_DIR, 'themes');// 官方背景图库:面板「主题」页的默认壁纸(wallpaper-01.webp ~ wallpaper-NN.webp)const WALLPAPERS_DIR = path.join(THEMES_DIR, 'wallpapers');+const wallpaperRotation = createWallpaperRotation({+ configFile: path.join(DATA_DIR, 'wallpaper-rotation.json'),+ isActive: () => !!(PROFILE.capabilities.theme && PROFILE.capabilities.themeTakeover !== false &&+ cdp.connected && readSessionState().themeTakeoverEnabled !== false && readSavedThemeId() === 'nebula'),+ invalidate: async () => {+ if (!cdp.connected) return;+ try { await cdpSend('Runtime.evaluate', { expression: "if(window.__wbsWallpaperRuntime)window.__wbsWallpaperRuntime.dispose()" }); } catch (_) {}+ },+ apply: async (image) => {+ if (!cdp.connected) return false;+ const r = await cdpSend('Runtime.evaluate', {+ expression: '(' + updateWallpaperInRenderer.toString() + ')(' + JSON.stringify({+ url: `http://${HOST}:${ACTUAL_PORT}/api/wallpaper-rotation/image?key=${image.key}`,+ token: API_TOKEN,+ }) + ')', awaitPromise: true, returnByValue: true, timeout: 10000,+ });+ return !!(r && r.result && r.result.value === true);+ },+});+/** 内置资产源目录(首次启动初始化的来源,WorkDaddy.app 自包含打包):* 1) 脚本同目录 builtin/(app 内置模式:Contents/Resources/scripts/builtin)@@ -8318,18 +8431,104 @@ async function restoreNativeAppearanceByCdp() {} catch (_) {}}+// 系统设置优先于 renderer matchMedia(官方 nativeTheme 可能已锁定后者)。+function execCaptureText(cmd, args, timeoutMs = 4000) {+ return new Promise((resolve, reject) => {+ execFile(cmd, args, { encoding: 'utf8', timeout: timeoutMs, windowsHide: true }, (err, stdout, stderr) => {+ if (err) { err.stderr = stderr; reject(err); } else resolve(String(stdout || ''));+ });+ });+}+async function resolveSystemThemeByRenderer() {+ try {+ const reply = await cdpSend('Runtime.evaluate', {+ expression: `(function(){try{var m=window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)');return m&&m.matches?'dark':'default';}catch(e){return 'default';}})()`,+ returnByValue: true,+ });+ return reply && reply.result && reply.result.value === 'dark' ? 'dark' : 'default';+ } catch (_) {+ return 'default';+ }+}+async function resolveSystemTheme() {+ try {+ if (process.platform === 'win32') {+ try {+ const out = await execCaptureText('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize', '/v', 'AppsUseLightTheme']);+ const match = out.match(/AppsUseLightTheme\s+REG_DWORD\s+0x([01])\b/i);+ if (match) return match[1] === '0' ? 'dark' : 'default';+ } catch (_) {}+ // reg.exe 不可用(例如被安全软件的程序黑名单拦截、EPERM)时回退 PowerShell 读注册表,+ // 与 windows-process-boundary 的 powershell 查询同模式,保证受限环境下功能仍可用+ try {+ const out = await execCaptureText('powershell', ['-NoProfile', '-Command', "(Get-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize').AppsUseLightTheme"], 8000);+ if (/^[01]$/.test(String(out).trim())) return String(out).trim() === '0' ? 'dark' : 'default';+ } catch (_) {}+ return resolveSystemThemeByRenderer();+ }+ if (process.platform === 'darwin') {+ try {+ const out = await execCaptureText('defaults', ['read', '-g', 'AppleInterfaceStyle']);+ if (/^dark$/i.test(out.trim())) return 'dark';+ if (!out.trim()) return 'default';+ } catch (error) {+ // 浅色时键不存在;权限、超时和命令不可用必须继续降级。+ if (error.code === 1 && /AppleInterfaceStyle[\s\S]*does not exist/i.test(error.stderr || '')) return 'default';+ }+ return resolveSystemThemeByRenderer();+ }+ const out = (await execCaptureText('gsettings', ['get', 'org.gnome.desktop.interface', 'color-scheme'])).trim();+ if (/^['"]?prefer-dark['"]?$/.test(out)) return 'dark';+ if (/^['"]?prefer-light['"]?$/.test(out)) return 'default';+ return resolveSystemThemeByRenderer();+ } catch (_) {+ return resolveSystemThemeByRenderer();+ }+}++// 只在 system 模式轮询 OS,不在 renderer 安装会跨 reinjection 残留的监听器。+let systemThemeTimer = null;+let systemThemePollInFlight = false;+let lastResolvedSystemTheme = null;+function stopSystemThemePolling() {+ if (systemThemeTimer) { clearInterval(systemThemeTimer); systemThemeTimer = null; }+}+function startSystemThemePolling() {+ if (systemThemeTimer) return;+ systemThemeTimer = setInterval(async () => {+ if (systemThemePollInFlight) return;+ if (!cdp.connected || readSavedThemeId() !== 'system') { stopSystemThemePolling(); return; }+ const nativeOnly = PROFILE.capabilities.nativeComposer === true;+ if (!nativeOnly && readSessionState().themeTakeoverEnabled === false) return;+ systemThemePollInFlight = true;+ try {+ await applyThemeByCdp('system', { automatic: true, systemPoll: true, ...(nativeOnly ? { nativeOnly: true } : {}) });+ } catch (_) {+ // 不推进基线:下轮重试同一个系统外观。+ } finally {+ systemThemePollInFlight = false;+ }+ }, 5000);+ if (typeof systemThemeTimer.unref === 'function') systemThemeTimer.unref();+}+function readSavedThemeId() {try {const id = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'current-theme.json'), 'utf8')).id;- if (typeof id === 'string' && (id === 'default' || getTheme(id))) return id;+ if (typeof id === 'string' && (id === 'default' || id === 'system' || getTheme(id))) return id;} catch (_) {}return 'default';}/** 恢复已保存的主题(CDP 连接/页面刷新后调用):读取 current-theme.json 重新应用,保证深浅色在重启/刷新后仍生效 */async function restoreSavedTheme() {- if (!PROFILE.capabilities.theme || PROFILE.capabilities.themeTakeover === false) return;- if (!cdp.connected) return;+ if (!PROFILE.capabilities.theme || !cdp.connected) return;+ if (PROFILE.capabilities.nativeComposer) {+ // 原生手动选择由官方保存;system 需 daemon 在重连后继续跟随。+ if (readSavedThemeId() === 'system') await applyThemeByCdp('system', { automatic: true, nativeOnly: true });+ return;+ }+ if (PROFILE.capabilities.themeTakeover === false) return;if (readSessionState().themeTakeoverEnabled === false) {// 重载/重连时保留官方选择,不能再次触发关闭开关的一次性浅色重置。await startNativeAppearanceSyncByCdp();@@ -8448,13 +8647,29 @@ function readBackgroundBlur() {}async function applyThemeByCdp(id, options = {}) {- if (!PROFILE.capabilities.theme || PROFILE.capabilities.themeTakeover === false) throw new Error(`${PROFILE.name} 暂不支持毛玻璃主题`);+ const nativeOnly = options.nativeOnly === true || PROFILE.capabilities.nativeComposer === true;+ if (!PROFILE.capabilities.theme || (PROFILE.capabilities.themeTakeover === false && !nativeOnly)) throw new Error(`${PROFILE.name} 暂不支持毛玻璃主题`);+ // WorkBuddy's internal nebula transition also uses nativeOnly before+ // applying its own CSS, so only an explicit non-native profile is rejected.+ if (nativeOnly && PROFILE.capabilities.nativeComposer === false) throw new Error(`${PROFILE.name} 不支持原生主题切换`);+ if (nativeOnly && id !== 'default' && id !== 'dark' && id !== 'system') throw new Error(`${PROFILE.name} 仅支持跟随系统、浅色和深色主题`);if (options.release && readSessionState().themeTakeoverEnabled !== false) return { applied: false, takeover: true };- if (options.automatic && readSessionState().themeTakeoverEnabled === false) return { applied: false, takeover: false };- if (!options.automatic && !options.nativeOnly && !options.release) themeApplyGeneration++;+ if (options.automatic && !nativeOnly && readSessionState().themeTakeoverEnabled === false) return { applied: false, takeover: false };+ if (!options.automatic && (!options.nativeOnly || PROFILE.capabilities.nativeComposer) && !options.release) {+ themeApplyGeneration++;+ stopSystemThemePolling();+ }const applyGeneration = themeApplyGeneration;if (!cdp.connected) throw new Error('CDP 未连接');- const takeoverEnabled = !options.nativeOnly && readSessionState().themeTakeoverEnabled !== false;+ const systemMode = id === 'system';+ if (systemMode) {+ id = await resolveSystemTheme();+ // 在第一次 await 之前记录 generation,旧的自动恢复和手动请求均不能覆盖后续选择。+ if (applyGeneration !== themeApplyGeneration || (!nativeOnly && readSessionState().themeTakeoverEnabled === false) ||+ (options.systemPoll && readSavedThemeId() !== 'system')) return { applied: false, cancelled: true };+ if (options.systemPoll && id === lastResolvedSystemTheme) return { applied: false, unchanged: true, system: true, resolved: id };+ }+ const takeoverEnabled = !nativeOnly && readSessionState().themeTakeoverEnabled !== false;if (id === 'nebula' && takeoverEnabled) {// 分开两个 CDP 回合:释放自定义 CSS/守护,让官方深色真正渲染,再接管毛玻璃。// 不改持久化接管开关,避免中途失败或并发操作留下错误的用户设置。@@ -8547,7 +8762,7 @@ async function applyThemeByCdp(id, options = {}) {'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%),',- 'url(' + dataUrl + ') right center / cover no-repeat fixed !important;}',+ '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}',@@ -8566,6 +8781,7 @@ async function applyThemeByCdp(id, options = {}) {}}const expr = `(function(){+ if (window.__wbsWallpaperRuntime) window.__wbsWallpaperRuntime.dispose();var h = document.documentElement, b = document.body;if (!h || !b) return { pending: true };try {@@ -8740,8 +8956,8 @@ async function applyThemeByCdp(id, options = {}) {wbsSyncNativeTheme(mode);return true;}- if (${takeoverEnabled || options.release || options.nativeOnly ? 'true' : 'false'}) wbsPrepareNativeAppearance(${JSON.stringify(id === 'nebula' || options.nativeOnly ? 'dark' : 'light')});- if (${options.release || options.nativeOnly ? 'true' : 'false'}) {+ if (${takeoverEnabled || options.release || nativeOnly ? 'true' : 'false'}) wbsPrepareNativeAppearance(${JSON.stringify(id === 'nebula' || nativeOnly ? 'dark' : 'light')});+ if (${options.release || nativeOnly ? 'true' : 'false'}) {wbsClearNativeCustomCss();// 清掉特殊皮肤缓存;外观快照留给 releaseThemeByCdp 立即恢复。try {@@ -8888,8 +9104,9 @@ async function applyThemeByCdp(id, options = {}) {// 重连重试也必须服从后续主题选择或关闭接管,不能把过期阶段重新应用。if (applyGeneration !== themeApplyGeneration) return { applied: false, cancelled: true };if (options.release && (readSessionState().themeTakeoverEnabled !== false || applyGeneration !== themeApplyGeneration)) return { applied: false, takeover: readSessionState().themeTakeoverEnabled !== false };- if (options.automatic && (readSessionState().themeTakeoverEnabled === false || applyGeneration !== themeApplyGeneration)) return { applied: false, takeover: false };+ if (options.automatic && ((!nativeOnly && readSessionState().themeTakeoverEnabled === false) || applyGeneration !== themeApplyGeneration)) return { applied: false, takeover: false };r = await cdpSend('Runtime.evaluate', { expression: expr, returnByValue: true });+ if (applyGeneration !== themeApplyGeneration) return { applied: false, cancelled: true };if (r && r.exceptionDetails) {const detail = r.exceptionDetails.exception && r.exceptionDetails.exception.description;throw new Error(detail || r.exceptionDetails.text || 'Runtime.evaluate 执行失败');@@ -8912,7 +9129,16 @@ async function applyThemeByCdp(id, options = {}) {log('[theme] 应用主题失败: ' + detail);throw new Error('应用主题失败: ' + detail);}- return { ok: true, applied: v.applied, dark: v.dark, bg: v.bg, text: v.text };+ if (id === 'nebula' && takeoverEnabled && wallpaperRotation.status().mode === 'random') {+ wallpaperRotation.restore().catch(() => {});+ }+ // 浅色成功恢复官方样式时 applied=false(无自定义覆盖),仍须启动轮询并更新基线。+ if (systemMode && (v.applied || id === 'default')) {+ lastResolvedSystemTheme = id;+ startSystemThemePolling();+ }+ return { ok: true, applied: v.applied, dark: v.dark, bg: v.bg, text: v.text,+ ...(systemMode ? { system: true, resolved: id } : {}) };}/**@@ -9831,7 +10057,7 @@ function handleApi(req, res) {if (req.method === 'POST' && p === '/api/automations/export') {return readTransferBody(req).then(body => {- return exportTasks(readAutomations(DATA_DIR), body && body.ids);+ return exportTasks(typeof readCurrentAutomations === 'function' ? readCurrentAutomations() : readAutomations(DATA_DIR), body && body.ids);}).then(result => json(res, 200, { ok: true, ...result })).catch(error => json(res, 400, { ok: false, error: error.message }));}@@ -9906,10 +10132,20 @@ function handleApi(req, res) {});}+ if (req.method === 'GET' && p === '/api/automations/auto-sync') {+ return json(res, 200, { ok: true, enabled: automationSyncEnabled() });+ }+ if (req.method === 'POST' && p === '/api/automations/auto-sync') {+ return readBody(req).then((body) => {+ if (!body || typeof body.enabled !== 'boolean') return json(res, 400, { ok: false, error: '缺少定时任务同步开关状态' });+ return json(res, 200, { ok: true, ...writeAutomationSyncSettings(DATA_DIR, body.enabled) });+ }).catch((error) => json(res, 400, { ok: false, error: error.message }));+ }+if (req.method === 'GET' && p === '/api/automations') {const imported = importAgentInbox(DATA_DIR, { profileId: PROFILE.id });imported.forEach((item) => log(`[automation-agent] request=${item.requestId} ${item.ok ? 'imported=' + item.taskId : 'rejected=' + item.error}`));- const tasks = readAutomations(DATA_DIR);+ const tasks = typeof readCurrentAutomations === 'function' ? readCurrentAutomations() : readAutomations(DATA_DIR);let builtinMarkers = {};try { builtinMarkers = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'automation-builtins.json'), 'utf8')) || {}; } catch (_) {}const runs = Array.from(automationRuns.values()).slice(-50).map(automationPublicRun);@@ -9936,13 +10172,19 @@ function handleApi(req, res) {try {if (body && body.kind != null) throw new Error('任务包或索引不能作为本地任务执行');const task = validateTask(body && body.task ? body.task : body);- const tasks = readAutomations(DATA_DIR);- const index = tasks.findIndex((item) => item.id === task.id);- if (index >= 0 && !isSupportedTaskSchema(tasks[index])) throw new Error('任务使用更新的协议,请升级 WorkDaddy 后再编辑');- if (index < 0 && tasks.length >= 200) throw new Error('自动化任务数量已达到上限');- if (index >= 0) tasks[index] = task; else tasks.unshift(task);- writeAutomations(DATA_DIR, tasks);- return json(res, 200, { ok: true, task });+ const allTasks = readAutomations(DATA_DIR);+ const currentUid = String((currentAccount() || {}).uid || '').trim();+ const index = allTasks.findIndex((item) => item.id === task.id && readAccountAutomations(DATA_DIR, currentUid).some((visible) => visible.id === item.id));+ const sameIdIndex = allTasks.findIndex((item) => item.id === task.id);+ if (sameIdIndex >= 0 && index < 0) throw new Error('任务 ID 已被其他账号使用');+ if (index >= 0 && !isSupportedTaskSchema(allTasks[index])) throw new Error('任务使用更新的协议,请升级 WorkDaddy 后再编辑');+ if (index < 0 && allTasks.length >= 200) throw new Error('自动化任务数量已达到上限');+ const stored = index >= 0 && allTasks[index][AUTOMATION_ACCOUNT_SCOPE_KEY]+ ? { ...task, [AUTOMATION_ACCOUNT_SCOPE_KEY]: allTasks[index][AUTOMATION_ACCOUNT_SCOPE_KEY] }+ : index >= 0 ? task : scopeTaskToAccount(task, currentUid);+ if (index >= 0) allTasks[index] = stored; else allTasks.unshift(stored);+ writeAutomations(DATA_DIR, allTasks);+ return json(res, 200, { ok: true, task: stored });} catch (error) { return json(res, 400, { ok: false, error: error.message }); }});}@@ -9951,7 +10193,7 @@ function handleApi(req, res) {return readBody(req).then((body) => {try {const id = String(body && body.id || '').trim();- const task = readAutomations(DATA_DIR).find((item) => item.id === id);+ const task = (typeof readCurrentAutomations === 'function' ? readCurrentAutomations() : readAutomations(DATA_DIR)).find((item) => item.id === id);if (!task) return json(res, 404, { ok: false, error: '自动化任务不存在' });if (!canManuallyRunTask(task)) return json(res, 409, { ok: false, error: '此任务由事件或定时自动触发,无需手动运行' });const running = Array.from(automationRuns.values()).find((run) => run.taskId === id && run.status === 'running');@@ -9966,7 +10208,7 @@ function handleApi(req, res) {return readBody(req).then((body) => {try {const id = String(body && body.id || '').trim();- if (!readAutomations(DATA_DIR).some(task => task.id === id)) return json(res, 404, { ok: false, error: '自动化任务不存在' });+ if (!(typeof readCurrentAutomations === 'function' ? readCurrentAutomations() : readAutomations(DATA_DIR)).some(task => task.id === id)) return json(res, 404, { ok: false, error: '自动化任务不存在' });if (Array.from(automationRuns.values()).some(run => run.safetyReviewTaskId === id && run.status === 'running')) {return json(res, 409, { ok: false, error: '该任务正在安全评估中' });}@@ -10000,10 +10242,11 @@ function handleApi(req, res) {const ids = Array.isArray(body && body.ids) ? body.ids.map((id) => String(id || '').trim()).filter(Boolean).slice(0, 200) : [];const action = String(body && body.action || '').trim();const tasks = readAutomations(DATA_DIR);- const selected = tasks.filter((task) => ids.includes(task.id));+ const visibleIds = new Set(readCurrentAutomations().map((task) => task.id));+ const selected = tasks.filter((task) => visibleIds.has(task.id) && ids.includes(task.id));if (!selected.length) return json(res, 400, { ok: false, error: '未选择自动化任务' });if (action === 'delete') {- writeAutomations(DATA_DIR, tasks.filter((task) => !ids.includes(task.id)));+ writeAutomations(DATA_DIR, tasks.filter((task) => !selected.some((item) => item.id === task.id)));} else if (action === 'enable' || action === 'disable') {if (selected.some(task => !isTaskCompatible(task))) throw new Error('任务使用更新的协议,请升级 WorkDaddy 后再编辑');selected.forEach((task) => { task.enabled = action === 'enable'; task.updatedAt = Date.now(); });@@ -10012,7 +10255,7 @@ function handleApi(req, res) {if (selected.some((task) => !canManuallyRunTask(task))) return json(res, 409, { ok: false, error: '此任务由事件或定时自动触发,无需手动运行' });selected.forEach((task) => { if (!Array.from(automationRuns.values()).some((run) => run.taskId === task.id && run.status === 'running')) startAutomationRun(task); });} else return json(res, 400, { ok: false, error: '不支持的批量操作' });- return json(res, 200, { ok: true, action, count: selected.length, tasks: readAutomations(DATA_DIR) });+ return json(res, 200, { ok: true, action, count: selected.length, tasks: typeof readCurrentAutomations === 'function' ? readCurrentAutomations() : readAutomations(DATA_DIR) });} catch (error) { return json(res, 400, { ok: false, error: error.message }); }});}@@ -10363,7 +10606,7 @@ function handleApi(req, res) {// 客户端进程是否在跑 / 调试端口是否可达 / 是否命中"更新后丢失调试端口"状态// running 由后台定时刷新(refreshClientRunning),请求线程直读缓存,不再同步探测running: clientRunningState.value,- cdpReachable: cdp.connected,+ cdpReachable: cdp.connected || cdp.endpointReachable,needsDebugRelaunch: clientDebugState.needsDebugRelaunch,debugStateUpdatedAt: clientDebugState.updatedAt || null,},@@ -10444,6 +10687,23 @@ function handleApi(req, res) {});}+ if (req.method === 'GET' && p === '/api/client-launch-settings') {+ return json(res, 200, { ok: true, ...readClientLaunchSettings(DATA_DIR, PROFILE.id, process.platform) });+ }++ if (req.method === 'POST' && p === '/api/client-launch-settings') {+ return readBody(req).then((body) => {+ if (process.platform !== 'win32' || PROFILE.id !== 'workbuddy-ai' || !body || typeof body.softwareRendering !== 'boolean') {+ return json(res, 400, { ok: false, error: '仅 Windows WorkBuddy AI 支持布尔值软件渲染设置' });+ }+ try {+ return json(res, 200, { ok: true, ...setClientLaunchSettings(DATA_DIR, PROFILE.id, body, process.platform) });+ } catch (_) {+ return json(res, 500, { ok: false, error: '保存软件渲染设置失败,请重试' });+ }+ });+ }+// 诊断:保存一份不含 token 的本地快照,便于用户在异常机器上直接提供文件排查。if (req.method === 'GET' && p === '/api/diagnostics') {return writeDiagnosticsSnapshot('api-get').then((snapshot) => json(res, 200, { ok: true, file: DIAGNOSTICS_FILE, diagnostics: snapshot }));@@ -10617,7 +10877,7 @@ function handleApi(req, res) {if (req.method === 'GET' && p === '/api/accounts') {const accounts = listAccountsWithRuntimeTokenCache();- const checkinAutomationEnabled = readAutomations(DATA_DIR).some(task => task.enabled && stepsContainCheckin(task.steps));+ const checkinAutomationEnabled = readCurrentAutomations().some(task => task.enabled && stepsContainCheckin(task.steps));const cache = loadCheckinCache();const today = todayStr();return CREDIT_USAGE_STORE.listDailyCheckins(accounts.map((a) => a.uid), today)@@ -11056,6 +11316,37 @@ function handleApi(req, res) {}}+ // Rotation routes share the authenticated local API; external paths never+ // appear in an image URL. Only an issued current/pending ticket can be read.+ if (p.startsWith('/api/wallpaper-rotation')) {+ if (!PROFILE.capabilities.theme || PROFILE.capabilities.themeTakeover === false) return json(res, 400, { ok: false, error: '当前客户端不支持壁纸轮换' });+ if (req.method === 'GET' && p === '/api/wallpaper-rotation') return json(res, 200, { ok: true, ...wallpaperRotation.status() });+ if (req.method === 'POST' && p === '/api/wallpaper-rotation') {+ return readBody(req).then(body => wallpaperRotation.configure(body))+ .then(info => json(res, 200, { ok: true, ...info }))+ .catch(e => json(res, 400, { ok: false, error: e.message }));+ }+ if (req.method === 'POST' && p === '/api/wallpaper-rotation/pick') {+ return pickWallpaperDirectory().then(directory => json(res, 200, { ok: true, directory, cancelled: !directory }))+ .catch(e => json(res, 400, { ok: false, error: e.message }));+ }+ if (req.method === 'POST' && p === '/api/wallpaper-rotation/next') {+ return wallpaperRotation.next().then(info => json(res, 200, { ok: true, ...info }));+ }+ if (req.method === 'GET' && p === '/api/wallpaper-rotation/image') {+ return wallpaperRotation.openImage(url.searchParams.get('key')).then(image => {+ const headers = { 'Content-Type': image.mime, 'Content-Length': image.size, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' };+ if (res.__wbsCorsOrigin) { headers['Access-Control-Allow-Origin'] = res.__wbsCorsOrigin; headers.Vary = 'Origin'; }+ if (res.destroyed) { image.handle.close().catch(() => {}); return; }+ res.writeHead(200, headers);+ const stream = image.handle.createReadStream({ start: 0 });+ res.on('close', () => stream.destroy());+ stream.on('error', () => res.destroy());+ stream.pipe(res);+ }).catch(() => { if (!res.headersSent) json(res, 404, { ok: false, error: '壁纸已失效或不可用' }); });+ }+ }+// 官方背景图库列表(themes/wallpapers/*.webp),供面板「主题」页预览切换。// 附带 currentWallpaper:当前主题 background.webp 内容哈希匹配到的图库文件名(供面板高亮当前壁纸)// 附带 customWallpapers:用户上传的自定义壁纸(custom-*.webp),供面板分开展示@@ -11718,6 +12009,9 @@ function handleApi(req, res) {// reloadIdeWorkbenchWindows 注释)。同步到其他账号无需刷新——切号时// session-change 会清缓存。if (copied > 0 && targetUid === String((currentAccount() || {}).uid || '')) {+ // SQLite copies bypass WorkBuddy's collection notifications. Publish+ // the completed batch before success, as automatic sync already does.+ await refreshWorkBuddySessionList(targetUid, 'sessions-copy');reloadIdeWorkbenchWindows('sessions-copy');}return json(res, 200, { ok: true, copied, skipped, conflicts, targetUid, warning });@@ -11912,8 +12206,12 @@ function handleApi(req, res) {if (req.method === 'POST' && p === '/api/theme-apply') {return readBody(req).then((body) => {const id = (body.id || 'default') + '';- if (id !== 'default' && !getTheme(id)) return json(res, 404, { ok: false, error: '主题不存在: ' + id });- return applyThemeByCdp(id)+ if (id !== 'default' && id !== 'system' && !getTheme(id)) return json(res, 404, { ok: false, error: '主题不存在: ' + id });+ const nativeOnly = body.nativeOnly === true && PROFILE.capabilities.nativeComposer && (id === 'default' || id === 'dark' || id === 'system');+ const applyOptions = nativeOnly ? { nativeOnly: true } : null;+ const applying = applyOptions ? applyThemeByCdp(id, applyOptions) : applyThemeByCdp(id);+ const requestGeneration = themeApplyGeneration;+ return applying.then((info) => {if (info.cancelled) return json(res, 409, { ok: false, error: '主题切换已被后续操作取消' });try {@@ -11924,6 +12222,11 @@ function handleApi(req, res) {return json(res, 200, { ok: true, ...info, id });}).catch((e) => {+ // 手动切换失败时仍保留原有 system 模式,并让下轮重试实际外观。+ if (requestGeneration === themeApplyGeneration && readSavedThemeId() === 'system') {+ lastResolvedSystemTheme = null;+ startSystemThemePolling();+ }log('[theme] API 应用失败: ' + e.message);return json(res, 500, { ok: false, error: e.message });});@@ -11988,7 +12291,7 @@ function handleApi(req, res) {// 注意:CDP 未连接时应用主题会失败,但文件与 current-theme.json 已保存——此时仍返回成功,// 由 restoreSavedTheme 在连接恢复后自动应用,避免"背景图已保存但应用失败"的报错困扰用户。if (req.method === 'POST' && p === '/api/theme-bg') {- return readBody(req).then((body) => {+ return readBody(req).then(async (body) => {try {const id = String(body.id || '').replace(/[^A-Za-z0-9_-]/g, '_');if (!id) return json(res, 400, { ok: false, error: '缺少 id' });@@ -12015,6 +12318,7 @@ function handleApi(req, res) {buf = Buffer.from(m[2], 'base64');}if (buf.length > 10 * 1024 * 1024) return json(res, 400, { ok: false, error: '图片不能超过 10MB' });+ await wallpaperRotation.configure({ mode: 'manual' });const dir = path.join(THEMES_DIR, id);fs.mkdirSync(dir, { recursive: true });fs.writeFileSync(path.join(dir, 'background.webp'), buf);@@ -12381,6 +12685,24 @@ function handleApi(req, res) {if (sourceUid !== uid) await preserveAccountSwitchTheme(uid);const acct = await switchAccountForProfile(uid);const hint = acct.nativeSwitched ? '原生登录态已切换,无需重启客户端' : '登录文件已切换,请刷新窗口使新账号生效';+ let automationSync = { enabled: false, copied: 0, skipped: 0, total: 0 };+ let officialAutomationSync = { enabled: false, copied: 0, skipped: 0, total: 0 };+ if (sourceUid && sourceUid !== uid && typeof automationSyncEnabled === 'function' && automationSyncEnabled()) {+ automationSync.enabled = true;+ try {+ Object.assign(automationSync, syncAccountAutomations(sourceUid, uid));+ } catch (error) {+ automationSync.error = '定时任务同步失败';+ log(`[switch] 定时任务同步失败: ${error.message}`);+ }+ officialAutomationSync.enabled = true;+ try {+ Object.assign(officialAutomationSync, await syncOfficialAccountAutomations(sourceUid, uid));+ } catch (error) {+ officialAutomationSync.error = '官方定时任务同步失败';+ log(`[switch] 官方定时任务同步失败: ${error.message}`);+ }+ }let reloaded = false;if (body.reload) {try {@@ -12426,6 +12748,8 @@ function handleApi(req, res) {nickname: acct.nickname,reloaded,autoCopy: autoCopyJob ? { jobId: autoCopyJob.id, total: autoCopyJob.total, openSessionId: autoCopyJob.openSessionId || '' } : { total: 0 },+ automationSync,+ officialAutomationSync,hint: reloaded ? '已切换并触发窗口刷新' : hint,});} catch (e) {@@ -12611,7 +12935,10 @@ function startServer() {// web/ 调试界面已移除(web 目录不再打包),根路径返回自包含的状态提示页const c = currentAccount();const needRelaunch = clientDebugState.needsDebugRelaunch;- const warnBlock = needRelaunch+ const targetMismatch = !cdp.connected && cdp.endpointReachable;+ const warnBlock = targetMismatch+ ? '<p style="max-width:420px;margin:18px auto 0;color:#f0b35e;font-size:13px;line-height:1.6">调试端口可达,但未找到与当前配置匹配的客户端页面。请检查所选客户端路径与 profile 配置。</p>'+ : needRelaunch? '<div style="max-width:420px;margin:18px auto 0;padding:14px 16px;border:1px solid #7a4a1f;border-radius:10px;background:#2a1c0e;text-align:left">' +'<p style="margin:0 0 8px;color:#f0b35e;font-weight:600">⚠ 检测到客户端需要恢复</p>' +'<p style="margin:0 0 12px;color:#d8c9b0;font-size:13px;line-height:1.6">WorkBuddy 正在运行,但未以调试模式启动(通常是官方自动更新后自行重启导致),WorkDaddy 无法注入面板。点击下方按钮将以调试模式重启客户端,恢复右下角机器人按钮。</p>' +@@ -12815,7 +13142,7 @@ setTimeout(() => { migrateAutoCopyTargetRevisionBaselines().catch(() => {}); },const tickAutomationSchedules = createScheduleTicker(DATA_DIR);function runAutomationSchedules() {if (PROFILE.capabilities.automations === false) return;- tickAutomationSchedules(readAutomations(DATA_DIR), startAutomationRun,+ tickAutomationSchedules(readCurrentAutomations(), startAutomationRun,(id) => Array.from(automationRuns.values()).some((run) => run.taskId === id && run.status === 'running'));}runAutomationSchedules();diff --git a/scripts/inject.js b/scripts/inject.jsindex 4691da3..c029c49 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -395,23 +395,31 @@ function normalizeAutoContinueError(error) {var details = terminal.details && typeof terminal.details === 'object' ? terminal.details : {};function numberValue() {for (var i = 0; i < arguments.length; i++) {+ if (arguments[i] === null || arguments[i] === undefined || arguments[i] === '' || typeof arguments[i] === 'boolean') continue;var n = Number(arguments[i]);if (Number.isSafeInteger(n)) return n;}return null;}- var code = numberValue(error.code, error.bizCode, terminal.bizCode, details.code);+ // The official cap banner gives terminal.bizCode=6004 precedence over the+ // outer transport code (including 0/500), so statistics must do the same.+ var code = Number(terminal.bizCode) === 6004 ? 6004 : numberValue(error.code, error.bizCode, terminal.bizCode, details.code);var statusCode = numberValue(error.statusCode, error.status, error.httpStatus);var requestModelId = String(error.requestModelId || error.modelId || details.requestModelId || '').slice(0, 160);var category = String(error.category || error.type || details.category || '').slice(0, 80).toLowerCase();var message = String(error.message || terminal.message || details.message || '').slice(0, 240);+ // WorkBuddy 5.8's terminal.details is text, and may contain the only reset+ // date. Match its banner's reset source without retaining provider text.+ var resetTextSource = [terminal.details, terminal.message, error.message].filter(function (value) {+ return typeof value === 'string';+ }).map(function (value) { return value.slice(0, 4096); }).join(' ');var rateLimited = code === 6004 || statusCode === 429 || /rate.?limit|频率|限流/i.test(category + ' ' + message);var quotaExhausted = code === 14018 || code === 14012 || code === 14014 || code === 14019 || /quota|credit|额度|积分|余额/i.test(category + ' ' + message);var authFailure = statusCode === 401 || statusCode === 403 || /auth|credential|登录|认证/i.test(category + ' ' + message);var resetAt = null;var resetSource = details.resetAt || details.reset_at || terminal.resetAt || error.resetAt;if (resetSource === undefined || resetSource === null || resetSource === '') {- var resetMatch = /(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(?:\s+UTC[+-]\d{1,2})?)/i.exec(message);+ var resetMatch = /(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\s*\(?UTC[+-]\d{1,2}\)?)?)/i.exec(resetTextSource);if (resetMatch) resetSource = resetMatch[1];}if (resetSource !== undefined && resetSource !== null && resetSource !== '') {@@ -419,7 +427,10 @@ function normalizeAutoContinueError(error) {if (Number.isFinite(resetNumber)) resetAt = resetNumber < 1e12 ? Math.round(resetNumber * 1000) : Math.round(resetNumber);else {var resetText = String(resetSource).trim();- var parsed = Date.parse(resetText.replace(' UTC+8', '+08:00').replace(' UTC+0800', '+08:00').replace(' ', 'T'));+ resetText = resetText.replace(/\s*\(?UTC\+0?8(?:00)?\)?$/i, '+08:00').replace(' ', 'T');+ // Official cap dates are Shanghai wall clock, even on non-China hosts.+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(resetText)) resetText += '+08:00';+ var parsed = Date.parse(resetText);if (Number.isFinite(parsed)) resetAt = parsed;}}@@ -437,6 +448,68 @@ function normalizeAutoContinueError(error) {};}+// Cap statistics have their own read-only subscription. Auto-continue may be+// disabled or detach a finished reply before its terminal error arrives.+function createModelRateLimitObserver(options) {+ var bindings = new Map();+ var alive = true;+ function inspect(controller, binding) {+ if (!alive) return;+ try {+ var state = controller.sessionStore.getState() || {};+ [state.error, state.warning].forEach(function (error) {+ var normalized = normalizeAutoContinueError(error);+ if (!normalized || normalized.code !== 6004) return;+ var modelId = normalized.requestModelId || String(state.model || state.modelId || '');+ if (!modelId) return;+ binding.latest = {+ conversationId: String(controller.conversationId || ''),+ assistantId: String(error.requestId || ''),+ rateLimited: true,+ errorCode: 6004,+ errorRequestModelId: modelId,+ errorModelName: modelId,+ errorResetAt: normalized.resetAt,+ };+ });+ // Keep the sanitized cap after WorkBuddy clears a transient error, so a+ // temporary local API failure can retry on the next discovery heartbeat.+ if (binding.latest) options.record(binding.latest);+ } catch (_) {}+ }+ function refresh() {+ if (!alive) return;+ var controllers;+ try { controllers = options.discover() || []; } catch (_) { return; }+ var seen = new Set(controllers);+ bindings.forEach(function (binding, controller) {+ if (seen.has(controller)) return;+ try { if (binding.unsubscribe) binding.unsubscribe(); } catch (_) {}+ bindings.delete(controller);+ });+ controllers.forEach(function (controller) {+ if (!controller || !controller.sessionStore || typeof controller.sessionStore.getState !== 'function') return;+ var binding = bindings.get(controller);+ if (!binding) {+ binding = {};+ bindings.set(controller, binding);+ try {+ binding.unsubscribe = controller.sessionStore.subscribe(function () { inspect(controller, binding); });+ } catch (_) {}+ }+ inspect(controller, binding);+ });+ }+ refresh();+ var timer = options.setInterval(refresh, 5000);+ return { refresh: refresh, destroy: function () {+ alive = false;+ options.clearInterval(timer);+ bindings.forEach(function (binding) { try { if (binding.unsubscribe) binding.unsubscribe(); } catch (_) {} });+ bindings.clear();+ } };+}+function classifyAutoContinueError(error) {var normalized = normalizeAutoContinueError(error) || {};return {@@ -1014,6 +1087,7 @@ if (typeof module !== 'undefined' && module.exports) {classifySessionHealth: classifySessionHealth,classifyAutoContinueReply: classifyAutoContinueReply,normalizeAutoContinueError: normalizeAutoContinueError,+ createModelRateLimitObserver: createModelRateLimitObserver,classifyAutoContinueError: classifyAutoContinueError,classifyAutoContinueControllerSnapshot: classifyAutoContinueControllerSnapshot,autoContinueMessageText: autoContinueMessageText,@@ -1487,6 +1561,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'总大小': 'Total size','初始化设置': 'Initial setup','切换账号自动同步所有会话': 'Automatically sync all sessions when switching accounts',+ '同步定时任务': 'Sync scheduled tasks',+ '切换账号时保持所有已保存账号的定时任务一致,包括重命名和删除': 'Keep scheduled tasks identical across saved accounts on switch, including renames and deletions',+ '已同步': 'Synced',+ '已同步定时任务': 'Scheduled tasks synced',+ '个定时任务': ' scheduled task(s)',+ '已开启同步定时任务': 'Scheduled task sync enabled',+ '已关闭同步定时任务': 'Scheduled task sync disabled',+ '同步定时任务设置失败: ': 'Could not save scheduled task sync: ','开启后,切换账号时会自动同步当前账号的全部会话,包括之后新增的会话。': 'When enabled, switching accounts automatically syncs all sessions for the current account, including new sessions added later.','选择切换账号时是否自动同步会话。此设置之后也可以在「会话」页面修改。': 'Choose whether to sync sessions automatically when switching accounts. You can change this later on the “Sessions” page.','保存失败,请重试': 'Save failed, please try again',@@ -1642,6 +1724,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'暂存提示词': 'Stash prompt', '暂存': 'Stashed', '引用文本': 'Quote text', '快捷短语': 'Quick phrases', '点击后发送': 'Send on click', '编辑 →': 'Edit →', '新增': 'Add', '批量操作': 'Batch actions', '批量管理': 'Batch manage', '全选': 'Select all', '取消全选': 'Deselect all', '已选 0': 'Selected 0','分支到新会话': 'Start a new conversation here', '从这里开始新会话': 'Start a new conversation here', '复制到这条回复为止的聊天内容,在当前工作区继续聊;原会话不变。': 'Copy the conversation up to this reply into a new conversation in the current workspace. The original stays unchanged.', '正在创建分支会话…': 'Creating branch session…', '分支会话已创建,正在打开…': 'Branch created. Opening…', '分支会话已创建,但无法自动打开,请在会话列表中查找。': 'Branch created but could not open automatically. Check the sessions list.', '新会话未出现在列表中,请在会话列表中查找。': 'The new session is not listed yet. Check the sessions list.', '无法确认所选消息的分支位置,请稍后重试': 'Cannot confirm this reply position. Try again shortly.', '分支失败: ': 'Branch failed: ','账号汇总': 'Account summary', '账号数': 'Accounts', '总积分': 'Total credits', '手机': 'Phone', '有效期至': 'Expires', '当前使用中': 'Currently active', '隐藏敏感信息': 'Mask sensitive info', '显示明文': 'Show plaintext', '登录新账号': 'Log in a new account', '没有可导出的账号备份': 'No account backups to export', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。': 'No account backups yet. Open or log in to WorkBuddy once and check again later.',+ '软件渲染(闪屏兼容)': 'Software rendering (flicker workaround)',+ '关闭硬件加速并使用软件渲染,可能降低性能。保存后请完全退出 WorkBuddy AI,再通过 WorkDaddy AI 启动;关闭此开关可恢复默认。': 'Disables hardware acceleration and uses software rendering, which may reduce performance. After saving, fully quit WorkBuddy AI and launch it through WorkDaddy AI. Turn this off to restore the default.',+ '已保存,下次通过 WorkDaddy AI 启动时生效': 'Saved. Takes effect on the next launch through WorkDaddy AI',+ '设置读取失败,请重新打开面板': 'Could not read settings. Reopen the panel',+ '设置保存失败,请重试': 'Could not save settings. Try again','语言': 'Language', '中文': 'Chinese', '英语': 'English', 'English': 'English', '跟随系统': 'Follow system', '设置语言': 'Language', '首次打开时自动跟随系统语言;未匹配时使用英语。': 'The first launch follows your system language. English is used when no match is found.', '语言设置已更新': 'Language updated','CodeBuddy 暂不支持毛玻璃主题': 'Frosted glass theme is not yet supported in CodeBuddy', '默认': 'Default', 'WorkDaddy 主题': 'WorkDaddy theme', '毛玻璃': 'Frosted glass', '护眼绿': 'Eye-care green', '赛博紫': 'Cyber purple', '主题外观': 'Theme appearance', '壁纸': 'Wallpaper', '头像': 'Avatar', '自定义壁纸': 'Custom wallpaper', '背景蒙版': 'Background overlay', '背景毛玻璃': 'Background blur', '恢复默认': 'Restore default', '恢复官方头像': 'Restore official avatar','加载中…': 'Loading…', '读取中…': 'Reading…', '正在读取设置…': 'Reading settings…', '查询中…': 'Checking…', '暂无快捷短语': 'No quick phrases', '暂无快捷短语,点击「+ 新增」添加': 'No quick phrases. Click “+ Add” to create one.', '当前还未添加模型': 'No models added yet', '还没有模型备份': 'No model backups yet', '当前筛选下没有会话': 'No sessions match the current filter', '暂无进行中的会话': 'No active sessions', '暂无官方壁纸': 'No built-in wallpapers', '还没有自定义壁纸,先上传一张': 'No custom wallpapers yet. Upload one to start.', '壁纸加载中…': 'Loading wallpapers…', '壁纸加载失败(daemon 不可达)': 'Wallpaper loading failed (daemon unavailable)',@@ -1700,6 +1787,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {' · 跳过': ' · Skipped', ' · 分叉': ' · Conflicts', '成功': 'Succeeded', '跳过': 'Skipped', '已跳过': 'Skipped', '部分失败': 'Partial failure', '分叉': 'Conflict', '处理中': 'Processing', '会话已分叉,已保留双方内容': 'Changed on both sides; neither side was overwritten', '部分文件失败': 'Some files failed', '当前任务未记录逐项明细。': 'No per-session details were recorded for this task.', '会话同步明细': 'Session sync details', '会话同步结果筛选': 'Filter session sync results', '当前分类没有会话。': 'No sessions in this category.', '正在把已标记的会话从「': 'Syncing marked sessions from “', '」同步到「': '” to “', '查看明细': 'View details', ' 个候选会话': ' candidate session(s)', ' 秒后自动关闭': ' seconds until automatic close','收录 GitHub 和 Gitee 公开仓库。参考 ': 'Public GitHub and Gitee repositories are indexed. See ', '。': '.', '克隆示例仓库:': 'Clone the example repository: ', '删除 ': 'Delete ', ' 目录中不需要的示例任务。': ' directory tasks you do not need.', '把你的自动化任务 JSON 放进 ': 'Put your automation task JSON in ', ' 目录。': ' directory.', '提交改动并推送到 GitHub 或 Gitee。': 'Commit and push changes to GitHub or Gitee.', '在仓库简介中加入关键词 ': 'Add the keyword ','导出账号': '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','未命名账号': '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',@@ -1852,7 +1940,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'安装程序已打开,请按提示退出 WorkBuddy 并完成安装。': 'The installer is open. Please quit WorkBuddy as prompted and finish installing.','安装程序已打开,请到任务栏选择安装窗口;按提示退出 WorkBuddy 后完成安装。': 'The installer is open. Select its window from the taskbar, then quit WorkBuddy as prompted to finish installing.','停止旧服务…': 'Stopping old service…', '发现新版本,准备更新…': 'New version available; preparing to update…',- '已应用主题「': 'Theme applied: “', '已恢复官方头像': 'Restored the official avatar', '已应用官方头像': 'Applied the official avatar',+ '已应用主题「': 'Theme applied: “', '已跟随系统,当前使用「': 'Following system, currently “', '」外观': '” appearance', '跟随操作系统的深浅色模式自动切换': 'Follow the operating system dark/light mode and switch automatically', '已恢复官方头像': 'Restored the official avatar', '已应用官方头像': 'Applied the official avatar','头像已更新 ✓': 'Avatar updated ✓', '头像处理失败:': 'Avatar processing failed:','已开启:需要你决策时 WorkBuddy 会用弹窗提问(全局生效)': 'Enabled: WorkBuddy asks with a dialog when your decision is needed (applies globally)',// —— 第八批:壁纸/授权/休眠/开启风险文案与时间相对词前导空格变体 ——@@ -2699,6 +2787,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function mountPersistentOverlay(node) {node.setAttribute('data-wbs-panel-overlay', '');if (CAPS.panelAppearance === 'light') node.setAttribute('data-wbs-appearance', 'light');+ if (CAPS.nativeComposer) node.setAttribute('data-wbs-profile', PROFILE_ID);document.body.appendChild(node);if (nativePanelMount) nativePanelMount.keep(node);}@@ -4459,6 +4548,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {} catch (e) {}}+ // WorkBuddy 自带的会话历史索引使用稳定的 aside class,但父级 teams 布局会变化。+ // 开启 WorkDaddy 消息索引时移除官方导航,避免两套索引重叠;body observer 会在官方重建后再次清理。+ function removeOfficialConversationHistoryNavigation(enabled) {+ if (!enabled || typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return 0;+ var removed = 0;+ var nodes;+ try { nodes = document.querySelectorAll('aside.conversation-history-navigation'); } catch (_) { return 0; }+ for (var i = 0; i < nodes.length; i++) {+ try {+ if (nodes[i] && typeof nodes[i].remove === 'function') { nodes[i].remove(); removed++; }+ } catch (_) {}+ }+ return removed;+ }+// 会话消息导航:完整索引来自 controller.messageStore,DOM 仅用于判断当前可见位置。function createMessageNavigation() {var surface = null;@@ -4907,6 +5011,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function setEnabled(enabled) {if (enabled) {+ removeOfficialConversationHistoryNavigation(true);sync();return;}@@ -5061,6 +5166,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {listen(window, 'resize', onWindowChange);listen(window, 'scroll', onWindowChange, true);+ removeOfficialConversationHistoryNavigation(sessState.messageNav);sync();registerDisposer(function () {disposed = true;@@ -5210,6 +5316,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function onDomChange() {if (!alive) return;guardSessionChange();+ removeOfficialConversationHistoryNavigation(sessState.messageNav);if (messageNavigation) messageNavigation.sync();scheduleForkButtons();scheduleFabPos();@@ -5228,6 +5335,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var html = document.documentElement;var glass = html && html.getAttribute('data-wbs-theme-id') === 'nebula';var selector = '.teams-container .cr-input-toolbar__right > span.cr-voice-trigger-tooltip,' ++ '.teams-container .cr-input-toolbar__right > span.cr-voice-trigger-wrap > span.cr-voice-trigger-tooltip,' +'.teams-container .cr-input-toolbar__right > span.cr-context-usage-tooltip-trigger,' +'.teams-container .cr-input-toolbar__right > span.cr-enhance-button-tooltip';document.querySelectorAll(selector).forEach(function (node) {@@ -5867,7 +5975,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!alive || (!arr.length && !ids.length)) return;var items = document.querySelectorAll('.cb-message-queue-item');Array.prototype.forEach.call(items, function (it) {- var actions = it.querySelector('.cb-message-queue-item-actions');+ // WorkBuddy 5.8 renamed the actions class while keeping the queue item+ // class. Accept both names; the parent path is intentionally ignored.+ var actions = it.querySelector('.conversation-message-queue-item-actions, .cb-message-queue-item-actions');if (!actions) return;var hasTag = !!it.querySelector('.wbs-queue-tag');var matched = isStashItem(sessionId, it);@@ -6711,7 +6821,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {section.querySelectorAll('[name="wbs-persona-mode"]').forEach(function (radio) { radio.disabled = false; radio.checked = radio.value === mode; });info.sources.forEach(function (source) {var option = document.createElement('option'); option.value = source.uid;- var name = source.uid === 'legacy' ? wbsTranslateString('升级前共用的设置', WBS_LANGUAGE) : state.mask ? maskAccountName(source.nickname) : source.nickname;+ var name = source.uid === 'legacy' ? wbsTranslateString('升级前共用的设置', WBS_LANGUAGE) : accountDisplayName(source, state.mask);option.textContent = name + (source.available ? '' : ' · ' + wbsTranslateString('未设置', WBS_LANGUAGE));option.disabled = !source.available;option.setAttribute('data-wbs-i18n-skip', '');@@ -7047,7 +7157,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function officialWebsiteOrigin() {if (PROFILE_ID === 'workbuddy-ai') return 'https://www.workbuddy.ai';if (PROFILE_ID === 'codebuddy-intl') return 'https://www.codebuddy.ai';- if (PROFILE_ID === 'codebuddy-cn') return 'https://www.codebuddy.cn';+ // CodeBuddy CN exposes the growth APIs on codebuddy.cn, but its web+ // growth-center route is only implemented by the WorkBuddy site. Keep+ // the device-code login flow while opening that operable host.+ if (PROFILE_ID === 'codebuddy-cn') return 'https://www.workbuddy.cn';return 'https://www.workbuddy.cn';}@@ -7737,22 +7850,39 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function copyPlainText(text) {- if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {- return navigator.clipboard.writeText(String(text));+ text = String(text);+ function copyWithSelection() {+ return new Promise(function (resolve, reject) {+ var previousFocus = document.activeElement;+ var textarea = document.createElement('textarea');+ textarea.value = text;+ textarea.setAttribute('readonly', '');+ textarea.style.position = 'fixed';+ textarea.style.left = '-9999px';+ textarea.style.top = '0';+ textarea.style.opacity = '0';+ var copied = false;+ try {+ document.body.appendChild(textarea);+ textarea.select();+ copied = document.execCommand('copy');+ } catch (_) {+ } finally {+ textarea.remove();+ if (previousFocus && typeof previousFocus.focus === 'function') {+ try { previousFocus.focus({ preventScroll: true }); } catch (_) {}+ }+ }+ if (copied) resolve(); else reject(new Error('复制失败'));+ });}- return new Promise(function (resolve, reject) {- var textarea = document.createElement('textarea');- textarea.value = String(text);- textarea.setAttribute('readonly', '');- textarea.style.position = 'fixed';- textarea.style.opacity = '0';- document.body.appendChild(textarea);- textarea.select();- var copied = false;- try { copied = document.execCommand('copy'); } catch (_) {}- document.body.removeChild(textarea);- if (copied) resolve(); else reject(new Error('复制失败'));- });+ // Electron may expose the Clipboard API while denying write permission.+ try {+ if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {+ return Promise.resolve(navigator.clipboard.writeText(text)).catch(copyWithSelection);+ }+ } catch (_) {}+ return copyWithSelection();}// 导出账号:密码必填,daemon 使用随机 salt 加密后触发浏览器下载。@@ -9132,7 +9262,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}// ===== 会话 pane(构建:账号/时间筛选 + 按空间分组[默认2条/展开全部] + 刷新 + 批量操作[迁移/删除])=====- var sessionsState = { uid: undefined, currentUid: '', range: 'all', minBytes: 0, totalBytes: null, list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null, autoCopyAll: false, autoCopyJob: null, autoCopyPollTimer: null };+ var sessionsState = { uid: undefined, currentUid: '', range: 'all', minBytes: 0, totalBytes: null, list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null, autoCopyAll: false, autoSyncAutomations: false, autoSyncAutomationsBusy: false, autoCopyJob: null, autoCopyPollTimer: null };function isTaskSessionRecordUI(s) {// 任务(未选择项目/一次性)会话:以官方 is_playground=1 为准。// 普通工作区也用 WorkBuddy\\YYYY-MM-DD-HH-MM-SS 命名,仅凭 cwd 无法区分。@@ -9226,6 +9356,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<span class="wbs-sess-auto-all-box" aria-hidden="true"><svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="12" height="12" rx="2"/><path class="wbs-sess-auto-all-check" d="m4.5 8 2.2 2.2L11.5 5.5"/></svg></span>' +'<span class="wbs-sess-auto-all-label">自动同步所有会话</span>' +'</button>' ++ '<button class="wbs-sess-auto-all" type="button" id="wbs-sess-auto-automations" role="checkbox" aria-checked="false" aria-label="同步定时任务" title="切换账号时保持所有已保存账号的定时任务一致,包括重命名和删除">' ++ '<span class="wbs-sess-auto-all-box" aria-hidden="true"><svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="12" height="12" rx="2"/><path class="wbs-sess-auto-all-check" d="m4.5 8 2.2 2.2L11.5 5.5"/></svg></span>' ++ '<span class="wbs-sess-auto-all-label">同步定时任务</span>' ++ '</button>' +'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-batch">批量操作</button>' +'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-import" title="从加密文件导入会话">' + IMPORT_ICON + '<span>导入</span></button>' +'<span class="wbs-sess-count" id="wbs-sess-count"></span>' +@@ -9264,6 +9398,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {wireSessionsPane();loadSessionAccounts();loadSessions();+ loadAutomationSyncSetting();pollActiveSessionCopyJob();pollSessionExport();registerDisposer(function () { if (sessionsState.autoCopyPollTimer) clearTimeout(sessionsState.autoCopyPollTimer); });@@ -9400,6 +9535,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}+ function loadAutomationSyncSetting() {+ api('/api/automations/auto-sync').then(function (result) {+ sessionsState.autoSyncAutomations = !!(result && result.enabled);+ updateAutomationSyncButton();+ }).catch(function () { updateAutomationSyncButton(); });+ }+function filteredSessions() {var minBytes = Number(sessionsState.minBytes) || 0;return sessionsState.list.filter(function (session) {@@ -9413,6 +9555,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var countEl = sessionsPane.querySelector('#wbs-sess-count');if (!listEl) return;updateAutoCopyAllButton();+ if (typeof updateAutomationSyncButton === 'function') updateAutomationSyncButton();if (!filteredSessions().length) {listEl.innerHTML = '<div class="wbs-empty">当前筛选下没有会话</div>';updateSessionSummary(countEl);@@ -9531,6 +9674,38 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {button.classList.toggle('active', enabled);button.setAttribute('aria-checked', enabled ? 'true' : 'false');}+ function updateAutomationSyncButton() {+ if (!sessionsPane) return;+ var button = sessionsPane.querySelector('#wbs-sess-auto-automations');+ if (!button) return;+ var enabled = !!sessionsState.autoSyncAutomations;+ button.disabled = !!sessionsState.batchMode || !!sessionsState.autoSyncAutomationsBusy;+ button.classList.toggle('active', enabled);+ button.setAttribute('aria-checked', enabled ? 'true' : 'false');+ }+ function toggleAutomationSync(enabled) {+ var button = sessionsPane && sessionsPane.querySelector('#wbs-sess-auto-automations');+ if (!button || button.disabled) return;+ var previous = !!sessionsState.autoSyncAutomations;+ sessionsState.autoSyncAutomations = !!enabled;+ sessionsState.autoSyncAutomationsBusy = true;+ updateAutomationSyncButton();+ api('/api/automations/auto-sync', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ enabled: !!enabled }),+ }).then(function (response) {+ sessionsState.autoSyncAutomations = !!(response && response.enabled);+ sessionsState.autoSyncAutomationsBusy = false;+ updateAutomationSyncButton();+ toast(sessionsState.autoSyncAutomations ? '已开启同步定时任务' : '已关闭同步定时任务', false, root);+ }).catch(function (e) {+ sessionsState.autoSyncAutomations = previous;+ sessionsState.autoSyncAutomationsBusy = false;+ updateAutomationSyncButton();+ toast('同步定时任务设置失败: ' + (e.message || e), true, root);+ });+ }function toggleAutoCopyAll(enabled) {var button = sessionsPane && sessionsPane.querySelector('#wbs-sess-auto-all');if (!button || button.disabled) return;@@ -9800,6 +9975,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {toggleAutoCopyAll(autoCopyAllBtn.getAttribute('aria-checked') !== 'true');});}+ var autoAutomationBtn = sessionsPane.querySelector('#wbs-sess-auto-automations');+ if (autoAutomationBtn) {+ autoAutomationBtn.addEventListener('click', function () {+ toggleAutomationSync(autoAutomationBtn.getAttribute('aria-checked') !== 'true');+ });+ }// 时间 Segment 组件var rangeSeg = sessionsPane.querySelector('#wbs-sess-range-seg');if (rangeSeg) {@@ -10663,13 +10844,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<label class="wbs-ask-label" for="wbs-fab-auto-dock">自动贴边<span class="wbs-ask-hint">闲置 5 秒后收起,鼠标靠近即展开</span></label>' +'<label class="wbs-switch"><input type="checkbox" id="wbs-fab-auto-dock"><span class="wbs-switch-slider"></span></label>' +'</div></div>' +- (codeBuddyTheme ? '' : '<div class="wbs-pcard">' ++ (codeBuddyTheme ? '<div class="wbs-pcard" id="wbs-native-theme-card">' ++ '<div class="wbs-pcard-title">主题外观</div>' ++ '<div class="wbs-theme-seg" id="wbs-theme-seg" role="radiogroup" aria-label="主题外观">' ++ '<label class="wbs-theme-opt wbs-theme-option" title="跟随操作系统的深浅色模式自动切换"><input type="radio" name="wbs-theme" value="system"><span>跟随系统</span></label>' ++ '<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="default"><span>浅色</span></label>' ++ '<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="dark"><span>深色</span></label>' ++ '</div></div>' : '<div class="wbs-pcard">' +'<div class="wbs-theme-takeover-row">' +'<div class="wbs-pcard-title">接管主题</div>' +'<label class="wbs-switch"><input type="checkbox" id="wbs-theme-takeover" checked aria-label="接管主题"><span class="wbs-switch-slider"></span></label></div>' +'<div class="wbs-theme-managed" id="wbs-theme-appearance-options">' +'<div class="wbs-pcard-title">主题外观</div>' +'<div class="wbs-theme-seg" id="wbs-theme-seg" role="radiogroup" aria-label="主题外观">' ++ '<label class="wbs-theme-opt wbs-theme-option" title="跟随操作系统的深浅色模式自动切换"><input type="radio" name="wbs-theme" value="system"><span>跟随系统</span></label>' +'<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="default"><span>浅色</span></label>' +'<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="dark"><span>深色</span></label>' +'<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="eye-care"><span>护眼绿</span></label>' +@@ -10687,10 +10875,23 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-wallpapers" id="wbs-wallpapers"><div class="wbs-wp-loading">壁纸加载中…</div></div>' +'</div>' +'<div class="wbs-bg-panel" data-src-panel="custom" style="display:none">' ++ '<div class="wbs-wallpaper-mode" role="radiogroup" aria-label="壁纸模式">' ++ '<label><input type="radio" name="wbs-wallpaper-mode" value="manual" checked>手动应用</label>' ++ '<label><input type="radio" name="wbs-wallpaper-mode" value="random">文件夹随机</label>' ++ '</div>' ++ '<div id="wbs-wallpaper-random" hidden>' ++ '<label class="wbs-wallpaper-label" for="wbs-wallpaper-directory">壁纸文件夹</label>' ++ '<div class="wbs-wallpaper-folder"><input id="wbs-wallpaper-directory" type="text" placeholder="选择或填写文件夹路径" autocomplete="off" spellcheck="false"><button type="button" id="wbs-wallpaper-pick" class="wbs-wallpaper-button">选择文件夹</button></div>' ++ '<div class="wbs-wallpaper-interval"><label for="wbs-wallpaper-interval">切换间隔</label><select id="wbs-wallpaper-interval"><option value="1">1 分钟</option><option value="3">3 分钟</option><option value="5">5 分钟</option><option value="10" selected>10 分钟</option><option value="30">30 分钟</option><option value="60">1 小时</option><option value="custom">自定义</option></select>' ++ '<label id="wbs-wallpaper-custom-wrap" hidden><input type="number" id="wbs-wallpaper-minutes" min="1" max="1440" step="1" value="10" aria-label="自定义切换间隔(分钟)"><span>分钟</span></label></div>' ++ '<div class="wbs-wallpaper-actions"><button type="button" id="wbs-wallpaper-next" class="wbs-wallpaper-button">立即换一张</button><span class="wbs-wallpaper-status" id="wbs-wallpaper-status" role="status" aria-live="polite"></span></div>' ++ '<div class="wbs-wallpaper-hint">仅读取此文件夹内的 PNG / JPG / WebP,不复制或修改原文件;自动跳过超过 20MB 或 1600 万像素的图片。</div>' ++ '</div><div id="wbs-wallpaper-manual">' +'<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>' ++ '</div>' +'<div class="wbs-mask-row">' +'<label class="wbs-blur-label" for="wbs-mask-range">背景蒙版<span class="wbs-blur-hint">黑色半透明遮罩,压暗背景图</span></label>' +'<input type="range" id="wbs-mask-range" min="0" max="100" step="1" value="30">' +@@ -10923,6 +11124,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'</div>' +'</div>' +'</div>' ++ (WBS_PLATFORM === 'win32' && WBS_PROFILE_IS_AI ?+ '<div class="wbs-pcard wbs-settings-card wbs-rendering-card">' ++ '<div class="wbs-settings-row"><label class="wbs-pcard-title" for="wbs-software-rendering">软件渲染(闪屏兼容)</label>' ++ '<label class="wbs-switch wbs-telemetry-switch"><input type="checkbox" id="wbs-software-rendering" aria-label="软件渲染(闪屏兼容)" aria-describedby="wbs-rendering-help" disabled><span class="wbs-switch-slider"></span></label>' ++ '</div>' ++ '<div class="wbs-pcard-sub" id="wbs-rendering-help">关闭硬件加速并使用软件渲染,可能降低性能。保存后请完全退出 WorkBuddy AI,再通过 WorkDaddy AI 启动;关闭此开关可恢复默认。</div>' ++ '<div class="wbs-pcard-sub" id="wbs-rendering-status" role="status" aria-live="polite">正在读取设置…</div>' ++ '</div>' : '') +'<div class="wbs-pcard wbs-telemetry-card" id="wbs-telemetry-card">' +'<div class="wbs-telemetry-head">' +'<div class="wbs-telemetry-label"><span class="wbs-pcard-title">发送错误诊断</span><span class="wbs-telemetry-help" tabindex="0" aria-label="查看错误诊断说明"><svg viewBox="0 0 20 20" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="10" cy="10" r="8"/><path d="M8.4 7.6a1.8 1.8 0 1 1 2.8 1.45c-.75.48-1.2.85-1.2 1.75M10 13.7v.1"/></svg><span class="wbs-telemetry-tooltip" role="tooltip">此开关控制脱敏错误诊断。匿名安装数和日活独立统计(随机安装标识、系统、架构、版本、客户端类型及出口国家),不受此开关影响。不包含账号、会话内容、Token 或 API Key。</span></span></div>' +@@ -10985,11 +11194,45 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}wireTelemetrySettings();+ wireClientLaunchSettings();acRenderMonitorLogModal();// 自动更新:检查 + 红点 + 更新卡片checkForUpdate();}+ function wireClientLaunchSettings() {+ var toggle = aboutPane.querySelector('#wbs-software-rendering');+ var status = aboutPane.querySelector('#wbs-rendering-status');+ if (!toggle || !status) return;+ var saved = false;+ api('/api/client-launch-settings').then(function (data) {+ saved = data.softwareRendering === true;+ toggle.checked = saved;+ toggle.disabled = data.supported !== true;+ status.textContent = '';+ }).catch(function () {+ status.textContent = '设置读取失败,请重新打开面板';+ });+ toggle.addEventListener('change', function () {+ var next = toggle.checked;+ toggle.disabled = true;+ status.textContent = '保存中…';+ api('/api/client-launch-settings', {+ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ softwareRendering: next }),+ }).then(function (data) {+ saved = data.softwareRendering === true;+ toggle.checked = saved;+ toggle.disabled = data.supported !== true;+ status.textContent = '已保存,下次通过 WorkDaddy AI 启动时生效';+ }).catch(function () {+ toggle.checked = saved;+ toggle.disabled = false;+ status.textContent = '设置保存失败,请重试';+ });+ });+ }+function wireTelemetrySettings() {var toggle = aboutPane.querySelector('#wbs-telemetry-switch');var status = aboutPane.querySelector('#wbs-telemetry-status');@@ -11337,7 +11580,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {card.style.display = visible ? '' : 'none';var textCard = themePane.querySelector('#wbs-text-shadow-card');if (textCard) textCard.style.display = visible ? '' : 'none';- if (visible) loadWallpapers();+ if (visible) { loadWallpapers(); loadWallpaperRotation(); }}// 关闭接管后只隐藏主题外观选项;头像和悬浮机器人独立于主题接管。@@ -11394,6 +11637,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {dockSwitch.checked = fabQuietMode.isEnabled();dockSwitch.addEventListener('change', function () { fabQuietMode.setEnabled(this.checked); });}+ wireWallpaperRotation();// 壁纸通过下方来源按钮管理,主题单选项使用 change 事件。themePane.addEventListener('click', function (e) {var t = e.target;@@ -11569,6 +11813,111 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// (开发调试入口已抽离至独立脚本 picker-internal.js,连点 logo 右侧按钮呼出)}+ var wallpaperRotationState = null;+ var wallpaperRotationBusy = false;+ var wallpaperRotationDraft = false;+ var wallpaperRotationReadSerial = 0;+ function renderWallpaperRotation(info) {+ if (!alive || !themePane || !info) return;+ var previous = wallpaperRotationState;+ wallpaperRotationState = info;+ var random = info.mode === 'random';+ if (random && (!previous || previous.mode !== 'random')) {+ themePane.querySelectorAll('.wbs-bg-src').forEach(function (button) { button.classList.toggle('active', button.getAttribute('data-src') === 'custom'); });+ themePane.querySelectorAll('.wbs-bg-panel').forEach(function (panel) { panel.style.display = panel.getAttribute('data-src-panel') === 'custom' ? '' : 'none'; });+ }+ themePane.querySelectorAll('input[name="wbs-wallpaper-mode"]').forEach(function (input) { input.checked = input.value === info.mode; });+ var randomPanel = themePane.querySelector('#wbs-wallpaper-random');+ var manualPanel = themePane.querySelector('#wbs-wallpaper-manual');+ if (!randomPanel) return;+ randomPanel.hidden = !random;+ manualPanel.hidden = random;+ var directory = themePane.querySelector('#wbs-wallpaper-directory');+ if (document.activeElement !== directory) directory.value = info.directory || '';+ directory.title = info.directory || '';+ var interval = themePane.querySelector('#wbs-wallpaper-interval');+ var minutes = themePane.querySelector('#wbs-wallpaper-minutes');+ if (document.activeElement !== interval && document.activeElement !== minutes) {+ interval.value = [1,3,5,10,30,60].indexOf(info.intervalMinutes) >= 0 ? String(info.intervalMinutes) : 'custom';+ minutes.value = info.intervalMinutes;+ }+ themePane.querySelector('#wbs-wallpaper-custom-wrap').hidden = interval.value !== 'custom';+ var status = themePane.querySelector('#wbs-wallpaper-status');+ status.textContent = !info.directory ? '请选择壁纸文件夹' : info.error || (info.paused ? '已暂停,恢复毛玻璃主题后继续' : (info.current ? '当前:' + info.current : '等待应用壁纸'));+ status.title = status.textContent;+ status.dataset.error = info.error ? '1' : '0';+ themePane.querySelector('#wbs-wallpaper-next').disabled = wallpaperRotationBusy || !random || !info.directory || info.paused;+ }+ function loadWallpaperRotation() {+ if (!themePane || !themePane.querySelector('#wbs-wallpaper-random') || wallpaperRotationBusy || wallpaperRotationDraft) return;+ var serial = ++wallpaperRotationReadSerial;+ return api('/api/wallpaper-rotation').then(function (info) {+ if (serial === wallpaperRotationReadSerial && !wallpaperRotationBusy) renderWallpaperRotation(info);+ }).catch(function () {});+ }+ function wireWallpaperRotation() {+ var panel = themePane.querySelector('#wbs-wallpaper-random');+ if (!panel || panel.dataset.wired) return;+ panel.dataset.wired = '1';+ var directory = themePane.querySelector('#wbs-wallpaper-directory');+ var interval = themePane.querySelector('#wbs-wallpaper-interval');+ var minutes = themePane.querySelector('#wbs-wallpaper-minutes');+ var pick = themePane.querySelector('#wbs-wallpaper-pick');+ var next = themePane.querySelector('#wbs-wallpaper-next');+ function busy(value) {+ wallpaperRotationBusy = value;+ wallpaperRotationReadSerial++;+ themePane.querySelectorAll('input[name="wbs-wallpaper-mode"],#wbs-wallpaper-random input,#wbs-wallpaper-random select,#wbs-wallpaper-random button').forEach(function (node) { node.disabled = value; });+ if (!value && wallpaperRotationState) next.disabled = wallpaperRotationState.mode !== 'random' || !wallpaperRotationState.directory || wallpaperRotationState.paused;+ }+ function choose() {+ return api('/api/wallpaper-rotation/pick', { method: 'POST' }).then(function (info) {+ if (!alive || info.cancelled) return false;+ directory.value = info.directory;+ return true;+ });+ }+ function save(mode, shouldPick) {+ if (wallpaperRotationBusy) return;+ busy(true);+ var prepare = shouldPick ? choose() : Promise.resolve(true);+ return prepare.then(function (proceed) {+ if (!proceed || !alive) return;+ return api('/api/wallpaper-rotation', { method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ mode: mode, directory: directory.value.trim(), intervalMinutes: Number(interval.value === 'custom' ? minutes.value : interval.value) })+ }).then(function (info) { wallpaperRotationDraft = false; renderWallpaperRotation(info); });+ }).catch(function (e) { if (alive) toast(e.message || '壁纸设置保存失败', true, root); })+ .finally(function () { if (!alive) return; busy(false); if (wallpaperRotationState) renderWallpaperRotation(wallpaperRotationState); else loadWallpaperRotation(); });+ }+ themePane.querySelectorAll('input[name="wbs-wallpaper-mode"]').forEach(function (radio) {+ radio.addEventListener('change', function () {+ if (!radio.checked) return;+ if (radio.value === 'random' && !directory.value.trim()) {+ wallpaperRotationDraft = true;+ renderWallpaperRotation(Object.assign({}, wallpaperRotationState, { mode: 'random', directory: '', current: '', paused: false }));+ return;+ }+ wallpaperRotationDraft = false;+ save(radio.value);+ });+ });+ pick.addEventListener('click', function () { save('random', true); });+ directory.addEventListener('change', function () { save('random'); });+ interval.addEventListener('change', function () {+ themePane.querySelector('#wbs-wallpaper-custom-wrap').hidden = interval.value !== 'custom';+ if (interval.value === 'custom') { minutes.focus(); minutes.select(); } else save('random');+ });+ minutes.addEventListener('change', function () { save('random'); });+ next.addEventListener('click', function () {+ if (wallpaperRotationBusy) return;+ busy(true);+ api('/api/wallpaper-rotation/next', { method: 'POST' }).then(renderWallpaperRotation)+ .catch(function (e) { if (alive) toast(e.message || '切换壁纸失败', true, root); }).finally(function () { busy(false); });+ });+ loadWallpaperRotation();+ }+ setBuildInterval(function () { if (state.open && themePane && themePane.style.display !== 'none') loadWallpaperRotation(); }, 15000);+// 官方壁纸网格:加载 /api/wallpapers,渲染缩略图,点击切换背景图// file:// 页面无法直接 <img src="http://...">(Electron 拦截),改为 fetch → blob → objectURL 预览// 面板高度固定为主题页高度:防止切 tab 时高度忽高忽低(首次主题页壁纸渲染后锁定一次)@@ -11580,11 +11929,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var bodyEl = panel.querySelector('.wbs-body');if (bodyEl) bodyEl.style.overflowY = 'auto';}+ var wallpaperPreviewUrls = [];+ var wallpaperPreviewSerial = 0;+ function releaseWallpaperPreviews() {+ wallpaperPreviewSerial++;+ wallpaperPreviewUrls.forEach(function (url) { URL.revokeObjectURL(url); });+ wallpaperPreviewUrls = [];+ }+ registerDisposer(releaseWallpaperPreviews);+ registerDisposer(function () { if (window.__wbsWallpaperRuntime) window.__wbsWallpaperRuntime.dispose(); });function loadWallpapers(force) {var grid = root.querySelector('#wbs-wallpapers');var cgrid = root.querySelector('#wbs-custom-wallpapers');if (!grid && !cgrid) return;if (grid && grid.dataset.loaded && !force) return;+ releaseWallpaperPreviews();+ var previewSerial = wallpaperPreviewSerial;if (grid) grid.dataset.loaded = '1';var base = API.replace(/\/api\/?$/, '');var wallpaperRequest = api('/api/wallpapers');@@ -11592,6 +11952,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {setTimeout(function () { reject(new Error('壁纸请求超时')); }, 8000);});Promise.race([wallpaperRequest, wallpaperTimeout]).then(function (d) {+ if (!alive || previewSerial !== wallpaperPreviewSerial) return;var list = d.wallpapers || [];var customList = d.customWallpapers || [];var current = d.currentWallpaper || null;@@ -11633,7 +11994,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {g.querySelectorAll('.wbs-wp-thumb img').forEach(function (im) {fetch(im.getAttribute('data-src'), { cache: 'no-store' }).then(function (r) { return r.ok ? r.blob() : Promise.reject(new Error('HTTP ' + r.status)); })- .then(function (blob) { im.src = URL.createObjectURL(blob); })+ .then(function (blob) {+ if (!alive || previewSerial !== wallpaperPreviewSerial || !im.isConnected) return;+ var url = URL.createObjectURL(blob); wallpaperPreviewUrls.push(url); im.src = url;+ }).catch(function () {im.alt = '加载失败';im.style.opacity = '.25';@@ -11656,6 +12020,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!r || !r.ok) throw new Error((r && r.error) || '切换壁纸失败');toast('已应用壁纸「' + (card.getAttribute('title') || name) + '」', false, root);loadWallpapers(true);+ loadWallpaperRotation();}).catch(function (e) {toast('切换壁纸失败: ' + (e.message || e), true, root);}).finally(function () { card.classList.remove('busy'); });@@ -12026,10 +12391,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}- // ===== 主题系统(WorkDaddy 换肤):segmented 切换 =====+ // ===== 主题系统:WorkDaddy 换肤 / CodeBuddy 官方外观切换 =====// 主题 = CSS 变量覆盖(--wb-* / --dc-*),daemon 通过 CDP 注入 <style>。- // 五种外观共用主题接管;只有毛玻璃使用壁纸、蒙版和背景模糊。- var ALLOWED_THEMES = ['default', 'dark', 'nebula', 'eye-care', 'cyber-purple'];+ // WorkDaddy 提供六种外观并共用主题接管;CodeBuddy 提供跟随系统与官方浅色/深色。+ var ALLOWED_THEMES = (typeof CAPS !== 'undefined' && CAPS.nativeComposer)+ ? ['system', 'default', 'dark']+ : ['system', 'default', 'dark', 'nebula', 'eye-care', 'cyber-purple'];var currentThemeId = 'default';var themeSelectionSerial = 0;function syncThemeSelection(id) {@@ -12041,23 +12408,45 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});syncWallpaperCardVisibility(currentThemeId);}+ function readNativeThemeId() {+ if (!(typeof CAPS !== 'undefined' && CAPS.nativeComposer)) return null;+ try {+ var html = document.documentElement;+ var body = document.body;+ var dark = html && (html.getAttribute('data-theme') === 'dark' || html.classList.contains('cb-dark'));+ dark = dark || body && (body.getAttribute('data-vscode-theme-kind') === 'vscode-dark' || body.getAttribute('data-vscode-theme-name') === 'IDE Night');+ return dark ? 'dark' : 'default';+ } catch (_) { return null; }+ }function loadThemes() {var serial = themeSelectionSerial;+ var nativeCurrent = readNativeThemeId();+ if (nativeCurrent) syncThemeSelection(nativeCurrent);return api('/api/themes').then(function (d) {- if (serial === themeSelectionSerial) syncThemeSelection(d.current);+ if (serial === themeSelectionSerial) syncThemeSelection(d.current === 'system' ? 'system' : nativeCurrent || d.current);}).catch(function () {});}function selectTheme(id) {- if (!sessState.themeTakeover || CAPS.themeTakeover === false || ALLOWED_THEMES.indexOf(id) < 0) return;+ var nativeTheme = typeof CAPS !== 'undefined' && CAPS.nativeComposer;+ if (!nativeTheme) {+ if (!sessState.themeTakeover) return;+ if (CAPS.themeTakeover === false) return;+ }+ if (ALLOWED_THEMES.indexOf(id) < 0) return;var previous = currentThemeId;var serial = ++themeSelectionSerial;syncThemeSelection(id);- return applyTheme(id).then(function () {+ return applyTheme(id).then(function (info) {if (serial !== themeSelectionSerial) return;- var names = { 'default': '浅色', 'dark': '深色', 'eye-care': '护眼绿', 'cyber-purple': '赛博紫', 'nebula': '毛玻璃' };- toast('已应用主题「' + names[id] + '」', false, root);+ var names = { 'system': '跟随系统', 'default': '浅色', 'dark': '深色', 'eye-care': '护眼绿', 'cyber-purple': '赛博紫', 'nebula': '毛玻璃' };+ if (id === 'system') {+ // daemon 返回按系统解析出的具体外观,让用户确认当前落在深色还是浅色+ toast('已跟随系统,当前使用「' + (info && info.resolved === 'dark' ? '深色' : '浅色') + '」外观', false, root);+ } else {+ toast('已应用主题「' + names[id] + '」', false, root);+ }}).catch(function (error) {if (serial !== themeSelectionSerial) return;syncThemeSelection(previous);@@ -12069,12 +12458,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return api('/api/theme-apply', {method: 'POST',headers: { 'content-type': 'application/json' },- body: JSON.stringify({ id: id }),+ body: JSON.stringify({ id: id, nativeOnly: typeof CAPS !== 'undefined' && CAPS.nativeComposer }),});}// 壁纸控件仅在毛玻璃下显示;保留默认主题下上传壁纸的兼容目标。function themeSelectValue() {- return currentThemeId !== 'default' && currentThemeId !== 'dark' ? currentThemeId : 'nebula';+ return currentThemeId !== 'default' && currentThemeId !== 'dark' && currentThemeId !== 'system' ? currentThemeId : 'nebula';}// 页面主题由 daemon 在早期注入/加载时恢复;不要延迟 POST 旧主题,// 否则旧页面的异步请求可能覆盖用户刚选择的主题。@@ -12281,6 +12670,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!d || !d.ok) throw new Error((d && d.error) || '替换背景图失败');toast('已添加并应用自定义壁纸', false, root);loadThemes();+ loadWallpaperRotation();// 刷新自定义壁纸网格(含选中态)与当前壁纸高亮loadWallpapers(true);});@@ -13394,15 +13784,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function acRecordModelRateLimit(snapshot) {- if (!snapshot || !snapshot.rateLimited) return;+ if (!snapshot || !snapshot.rateLimited || Number(snapshot.errorCode) !== 6004) return;var modelId = String(snapshot.errorRequestModelId || 'unknown-model').slice(0, 160);var code = Number(snapshot.errorCode);var signature = [snapshot.conversationId, snapshot.assistantId, modelId, code, snapshot.errorResetAt || ''].join('|');if (acRateLimitRecorded[signature]) return;- acRateLimitRecorded[signature] = true;- if (!acCurrentUidPromise) acCurrentUidPromise = api('/api/current').then(function (current) { return String(current && current.uid || '').trim(); }).catch(function () { return ''; });+ acRateLimitRecorded[signature] = 'pending';+ if (!acCurrentUidPromise) acCurrentUidPromise = api('/api/current').then(function (current) {+ var uid = String(current && current.uid || '').trim();+ if (!uid) throw new Error('Current account is not ready');+ return uid;+ }).catch(function (error) { acCurrentUidPromise = null; throw error; });acCurrentUidPromise.then(function (uid) {- if (!uid) return;return api('/api/model-rate-limit', {method: 'POST',headers: { 'content-type': 'application/json' },@@ -13411,13 +13804,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {modelId: modelId,modelName: snapshot.errorModelName || modelId,resetAt: snapshot.errorResetAt || null,- reasonCode: Number.isSafeInteger(code) ? code : 6004,+ reasonCode: 6004,source: 'renderer-error',}),}).then(function () {+ acRateLimitRecorded[signature] = true;try { window.dispatchEvent(new Event('workdaddy:accounts-updated')); } catch (_) {}- }).catch(function () {});- });+ });+ }).catch(function () { delete acRateLimitRecorded[signature]; });}function acControllerSnapshot(controller) {@@ -15480,8 +15874,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return record && record.modelId;}) : [];if (!records.length) return;- var rawAccountName = String(account.nickname || account.phone || account.uin || account.uid || '未命名账号');- var accountName = state.mask ? maskAccountName(rawAccountName) : rawAccountName;+ var accountName = accountDisplayName(account, state.mask);var rows = records.map(function (record) {var name = String(record.modelName || record.modelId || '未知模型');var reset = record.resetAt ? Number(record.resetAt) : 0;@@ -16394,8 +16787,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var expired = isIdentityExpired(a);var ops = (isCur? ''- : (expired || a.authValid === false ? '' : '<button class="wbs-icon-btn wbs-acc-switch" type="button" title="切换" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(a.nickname || '未命名') + '">' + SWITCH_SVG + '</button>') +- '<button class="wbs-icon-btn wbs-del" type="button" title="删除" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(a.nickname || '未命名') + '">' + TRASH_SVG + '</button>');+ : (expired || a.authValid === false ? '' : '<button class="wbs-icon-btn wbs-acc-switch" type="button" title="切换" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(accountDisplayName(a, state.mask)) + '">' + SWITCH_SVG + '</button>') ++ '<button class="wbs-icon-btn wbs-del" type="button" title="删除" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(accountDisplayName(a, state.mask)) + '">' + TRASH_SVG + '</button>');ops = '<div class="wbs-ops"' + (isCur ? ' hidden' : '') + '>' + ops + '</div>';// 国际版没有手机号:用 UIN(账号唯一数字标识)替代展示;国内版仍显示手机。// UIN 与手机号共用同一标签和值间距,确保与“剩余”额度列对齐。@@ -16403,8 +16796,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var idLbl = a.phone ? '手机' : (a.uin ? 'UIN' : '账号');var rawName = a.nickname || '(未命名)';var rawId = a.phone ? a.phone : (a.uin ? a.uin : '-');- var nameVal = state.mask ? maskAccountName(rawName) : rawName;- var idVal = state.mask ? maskAccountId(rawId) : rawId;+ var nameVal = accountDisplayName(a, state.mask);+ var idVal = accountDisplayId(a, state.mask);card.innerHTML ='<div class="wbs-info">' +'<div class="wbs-row1"><div class="wbs-name-group"><button type="button" class="wbs-account-name" data-uid="' + escAttr(a.uid) + '" aria-label="查看或编辑账号备注" aria-haspopup="dialog" aria-controls="wbs-account-note-popover" aria-expanded="false"><span class="wbs-name">' + esc(nameVal) + '</span><span class="wbs-account-name-edit" aria-hidden="true">' + MODEL_EDIT_SVG + '</span></button>' + badge + dailyRingsHtml(a) + checkinBadge + modelRateLimitBadge + invalidAuthBadge + '</div>' + ops + '</div>' +@@ -16453,13 +16846,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}).then(function (r) {var autoCopy = r && r.autoCopy;+ var automationSync = r && r.automationSync;+ var officialAutomationSync = r && r.officialAutomationSync;+ var automationCopied = (automationSync && automationSync.copied || 0) + (officialAutomationSync && officialAutomationSync.copied || 0);+ var automationChanged = automationCopied + (officialAutomationSync && officialAutomationSync.updated || 0) + (officialAutomationSync && officialAutomationSync.removed || 0);+ var automationError = (automationSync && automationSync.error) || (officialAutomationSync && officialAutomationSync.error);// 兜底文案优先用 daemon 返回的 hint:codebuddy 走原生会话替换,切换即时生效// (无需重启/刷新),"重启后生效"只适用于 WorkBuddy 文件替换且 CDP 刷新失败的场景。toast(- r.reloaded- ? (autoCopy && autoCopy.jobId ? '已切换为「' + (r.nickname || r.uid) + '」,正在同步已标记会话…' : '已切换为「' + (r.nickname || r.uid) + '」,开始领取积分…')+ automationError ? '已切换为「' + (r.nickname || r.uid) + '」,' + automationError : r.reloaded+ ? (automationChanged ? '已切换为「' + (r.nickname || r.uid) + '」,' + t('已同步定时任务') : autoCopy && autoCopy.jobId ? '已切换为「' + (r.nickname || r.uid) + '」,正在同步已标记会话…' : '已切换为「' + (r.nickname || r.uid) + '」,开始领取积分…'): (r.hint || '已切换为「' + (r.nickname || r.uid) + '」,重启后生效'),- false,+ !!automationError,root);if (autoCopy && autoCopy.jobId) pollAutoCopyJob(autoCopy.jobId, r.nickname || r.uid);@@ -16507,6 +16905,28 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}+ function looksOfficiallyMasked(value) {+ return /\d{2,4}\*{2,}\d{2,4}/.test(String(value == null ? '' : value).trim());+ }++ // WorkBuddy may already redact the nickname/phone before it reaches the+ // backup file. In clear mode there is no original value to reveal, so use+ // an account-local stable identifier instead of showing the redaction as+ // if WorkDaddy's own mask were still enabled.+ function accountDisplayName(account, masked) {+ account = account || {};+ var nickname = String(account.nickname || '').trim();+ if (masked) return maskAccountName(nickname || account.uid || '(未命名)');+ if (!looksOfficiallyMasked(nickname)) return nickname || account.uid || '(未命名)';+ return String(account.note || account.phone || account.uid || nickname || '(未命名)');+ }++ function accountDisplayId(account, masked) {+ account = account || {};+ var value = String(account.phone || account.uin || '-').trim();+ return masked ? maskAccountId(value) : value;+ }+function maskAccountName(name) {var s = String(name == null ? '' : name);if (!s.length) return s;@@ -16543,11 +16963,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}if (!account) continue;var nameEl = cards[c].querySelector('.wbs-name');- if (nameEl) nameEl.textContent = state.mask ? maskAccountName(account.nickname || '(未命名)') : (account.nickname || '(未命名)');+ if (nameEl) nameEl.textContent = accountDisplayName(account, state.mask);var valEl = cards[c].querySelector('.wbs-phone-cell .wbs-val');if (valEl) {- var raw = account.phone ? account.phone : (account.uin ? account.uin : '-');- valEl.textContent = state.mask ? maskAccountId(raw) : raw;+ valEl.textContent = accountDisplayId(account, state.mask);}}}@@ -17226,6 +17645,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}});+ var modelRateLimitObserver = createModelRateLimitObserver({+ discover: function () {+ return CAPS.accounts && WBS_COMPAT && typeof WBS_COMPAT.findConversationControllers === 'function'+ ? WBS_COMPAT.findConversationControllers(document) : [];+ },+ record: acRecordModelRateLimit,+ setInterval: setBuildInterval,+ clearInterval: function (timer) { clearInterval(timer); },+ });+ registerDisposer(function () { modelRateLimitObserver.destroy(); });+// 注入完成即按开关状态启动/停止监控(不依赖打开增强面板)try { ensureAutoContinueMonitor(); } catch (e) {}// 注入完成即同步会话模块状态(暂存/快捷短语开关 + 短语列表)并应用到输入框按钮显隐@@ -17441,6 +17871,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-panel.show{display:flex}','.wbs-root.wbs-panel-light,[data-wbs-appearance="light"]{color-scheme:light;--wb-bg-primary:#fff;--wb-bg-secondary:#fff;--wb-bg-tertiary:#f2f2f2;--wb-bg-popover:#fff;--wb-bg-input:#fff;--wb-bg-hover:#f5f5f5;--wb-bg-active:#eee;--wb-border-subtle:#f0f0f0;--wb-border-default:#e5e5e5;--wb-border-hover:#ccc;--wb-border-strong:#ccc;--wb-color-text-primary:#1f1f1f;--wb-color-text-secondary:#666;--wb-color-text-tertiary:#999;--wb-icon-secondary:#666;--wb-icon-tertiary:#999;--wb-button-primary-bg:#1f1f1f;--wb-button-primary-fg:#fff;--wb-button-primary-bg-hover:#333;--wb-button-primary-bg-disabled:#eee;--wb-button-primary-fg-disabled:#999}','.wbs-panel-light .wbs-panel{background:var(--wb-bg-popover);color:var(--wb-color-text-primary)}',+ // CodeBuddy 的面板跟随官方浅色/深色;原生深色下必须在根节点同层覆盖+ // 组件变量,否则宿主的深色文字规则会落在浅色面板上,形成白底浅字。+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) :is(.wbs-root[data-wbs-profile="codebuddy-cn"],.wbs-root[data-wbs-profile="codebuddy-intl"]){color-scheme:dark;--wb-bg-primary:#0a0a0c;--wb-bg-secondary:#131316;--wb-bg-tertiary:#1b1b20;--wb-bg-popover:#131316;--wb-bg-input:#131316;--wb-bg-hover:color-mix(in srgb,#ffffff 7%,transparent);--wb-bg-active:color-mix(in srgb,#ffffff 10%,transparent);--wb-border-subtle:#202025;--wb-border-default:color-mix(in srgb,#ffffff 13%,transparent);--wb-border-hover:color-mix(in srgb,#ffffff 22%,transparent);--wb-border-strong:#2c2c33;--wb-color-text-primary:#e6e6e9;--wb-color-text-secondary:rgba(230,230,233,.72);--wb-color-text-tertiary:rgba(230,230,233,.55);--wb-icon-secondary:rgba(230,230,233,.72);--wb-icon-tertiary:rgba(230,230,233,.55);--wb-button-primary-bg:rgba(255,255,255,.92);--wb-button-primary-fg:#0a0a0c;--wb-button-primary-bg-hover:rgba(255,255,255,.8);--wb-button-primary-bg-disabled:rgba(230,230,233,.18);--wb-button-primary-fg-disabled:rgba(230,230,233,.42)}',// 英文文案更长:英文面板额外加宽,配合 label 自适应避免挤压'html[data-wbs-language="en"] .wbs-panel{width:880px}',// EN 下固定宽度 label 容易溢出:phone/credit/token 列的 label 释放为自适应宽度@@ -17449,6 +17882,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 语言切换 Segmented:复用主题/会话页的分段外观(theme-seg 容器 + sess-seg-btn 按钮)'.wbs-language-card .wbs-settings-row{justify-content:space-between}','.wbs-language-card .wbs-pcard-title{margin-bottom:0}',+ '.wbs-rendering-card .wbs-pcard-title{margin-bottom:0;min-width:0}',+ '.wbs-rendering-card .wbs-pcard-sub{margin-top:6px;line-height:1.6;color:var(--wb-color-text-secondary);white-space:normal;overflow-wrap:anywhere}','.wbs-lang-seg{flex:0 0 auto;width:auto;margin-bottom:0}','.wbs-lang-seg .wbs-sess-seg-btn{padding:6px 14px}','.wbs-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 12px;border-bottom:1px solid var(--wb-border-subtle,#f0f0f0);background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 30%,transparent)}',@@ -17503,6 +17938,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-credit-tip-value{display:flex;align-items:center;gap:8px;padding:8px 9px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent);color:var(--wb-color-text-primary,#1f1f1f)}.wbs-credit-tip-value i.credit{color:var(--wbs-tip-credit)}.wbs-credit-tip-value b{font-size:12px;font-variant-numeric:tabular-nums}.wbs-credit-tip-value+.wbs-daily-manual{margin-top:11px}','.wbs-daily-popover-empty,.wbs-daily-refresh-error{margin-top:8px;padding-top:8px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.12));color:var(--wb-icon-secondary,#667085);font-size:10.5px;line-height:1.55;overflow-wrap:anywhere}.wbs-daily-refresh-error{color:var(--wb-color-text-secondary,#5f6368)}','html.cb-dark .wbs-status-popover,html[data-theme="dark"] .wbs-status-popover,body[data-vscode-theme-name*="dark" i] .wbs-status-popover{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 88%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.14));color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 14px 38px rgba(0,0,0,.42),inset 0 1px 0 rgba(255,255,255,.08)}',+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) .wbs-status-popover[data-wbs-profile^="codebuddy-"]{color-scheme:dark;--wb-bg-primary:#0a0a0c;--wb-bg-secondary:#131316;--wb-bg-tertiary:#1b1b20;--wb-bg-popover:#131316;--wb-bg-input:#131316;--wb-bg-hover:color-mix(in srgb,#ffffff 7%,transparent);--wb-bg-active:color-mix(in srgb,#ffffff 10%,transparent);--wb-border-subtle:#202025;--wb-border-default:color-mix(in srgb,#ffffff 13%,transparent);--wb-border-hover:color-mix(in srgb,#ffffff 22%,transparent);--wb-border-strong:#2c2c33;--wb-color-text-primary:#e6e6e9;--wb-color-text-secondary:rgba(230,230,233,.72);--wb-color-text-tertiary:rgba(230,230,233,.55);--wb-icon-secondary:rgba(230,230,233,.72);--wb-icon-tertiary:rgba(230,230,233,.55);--wb-button-primary-bg:rgba(255,255,255,.92);--wb-button-primary-fg:#0a0a0c;--wb-button-primary-bg-hover:rgba(255,255,255,.8);--wb-button-primary-bg-disabled:rgba(230,230,233,.18);--wb-button-primary-fg-disabled:rgba(230,230,233,.42)}','@media (prefers-reduced-motion:reduce){.wbs-daily-rings,.wbs-daily-liquid,.wbs-growth-task-action{transition:none!important}.wbs-daily-cat-mark{animation:none!important}.wbs-daily-refresh-spinner,.wbs-growth-task-action-spinner{animation-duration:1.8s}}','.wbs-meta{display:flex;flex-direction:column;gap:2px}','.wbs-secondary-row{flex-direction:row;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px}',@@ -17969,6 +18405,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {/* 免打扰确认弹窗:挂载在面板容器内,仅覆盖面板区域(弹窗居中于面板,不盖住 WorkBuddy 窗口) */'.wbs-modal-mask.wbs-modal-mask-panel{position:absolute;inset:0;z-index:2147483645;border-radius:18px}','.wbs-modal{width:300px;max-width:88vw;background:var(--wb-bg-popover,#fff);border-radius:14px;padding:16px;box-shadow:0 10px 40px rgba(0,0,0,.25);color:var(--wb-color-text-primary,#1f1f1f)}',+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) :is(.wbs-modal,.wbs-account-note-popover,.wbs-status-popover,.wbs-credit-summary-popover){background:var(--wb-bg-popover,#131316);border-color:var(--wb-border-default,#2c2c33);color:var(--wb-color-text-primary,#e6e6e9)}',/* 弹窗文字主题适配:body 继承 .wbs-root 硬编码深色字,暗色下必须显式覆盖为浅色 */'html.cb-dark .wbs-modal,html.cb-dark .wbs-modal-title,html.cb-dark .wbs-modal-body,html[data-theme="dark"] .wbs-modal,html[data-theme="dark"] .wbs-modal-title,html[data-theme="dark"] .wbs-modal-body{color:#e6e6e9}','html.cb-dark .wbs-modal-btn:not(:where(.wbs-modal-ok,.primary)),html[data-theme="dark"] .wbs-modal-btn:not(:where(.wbs-modal-ok,.primary)){color:#d5d5d9;border-color:rgba(232,232,234,0.16);background:rgba(255,255,255,0.05)}',@@ -18080,6 +18517,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-update-btn:disabled{opacity:.5;cursor:default}','.wbs-update-progress{display:block;box-sizing:border-box;margin-top:8px;max-height:126px;overflow-y:auto;padding:7px 8px;border:1px solid rgba(226,75,74,.2);border-radius:8px;background:rgba(226,75,74,.045);font-size:10.5px;color:var(--wb-icon-tertiary,#888);line-height:1.5;overflow-wrap:anywhere;scrollbar-width:thin}','.wbs-update-log-line{white-space:normal;word-break:break-word;padding:1px 0}',+ '.wbs-wallpaper-mode{display:flex;flex-wrap:wrap;gap:8px 18px;margin:10px 0;font-size:12px;color:var(--wb-color-text-primary)}',+ '.wbs-wallpaper-mode label{display:flex;align-items:center;gap:5px;cursor:pointer}.wbs-wallpaper-mode input{margin:0;accent-color:var(--wb-color-text-primary)}',+ '#wbs-wallpaper-random[hidden],#wbs-wallpaper-manual[hidden],#wbs-wallpaper-custom-wrap[hidden]{display:none}',+ '.wbs-wallpaper-label{display:block;margin-bottom:6px;font-size:12px;color:var(--wb-color-text-secondary)}',+ '.wbs-wallpaper-folder{display:flex;gap:6px;min-width:0;flex-wrap:wrap}.wbs-wallpaper-folder input{flex:1;min-width:100px;width:0}',+ '.wbs-wallpaper-folder input,.wbs-wallpaper-interval input,.wbs-wallpaper-interval select{box-sizing:border-box;height:28px;padding:4px 7px;border:1px solid var(--wb-border-default);border-radius:7px;background:var(--wb-bg-input);color:var(--wb-color-text-primary);font:inherit;font-size:12px}',+ '.wbs-wallpaper-button{height:28px;flex-shrink:0;padding:4px 9px;border:1px solid var(--wb-border-default);border-radius:7px;background:var(--wb-bg-secondary);color:var(--wb-color-text-primary);font:inherit;font-size:12px;cursor:pointer;transition:background .15s,border-color .15s}',+ '.wbs-wallpaper-button:hover{background:var(--wb-bg-hover);border-color:var(--wb-border-hover)}.wbs-wallpaper-button:disabled,#wbs-wallpaper-random input:disabled,#wbs-wallpaper-random select:disabled{opacity:.5;cursor:default}',+ '.wbs-wallpaper-button:focus-visible,#wbs-wallpaper-random input:focus-visible,#wbs-wallpaper-random select:focus-visible,.wbs-wallpaper-mode input:focus-visible{outline:2px solid var(--wb-accent-blue,var(--wb-color-text-primary));outline-offset:2px}',+ '.wbs-wallpaper-interval{display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-top:10px;font-size:12px;color:var(--wb-color-text-secondary)}.wbs-wallpaper-interval>label:first-child{margin-right:auto}#wbs-wallpaper-custom-wrap{display:flex;align-items:center;gap:5px}#wbs-wallpaper-minutes{width:64px}',+ '.wbs-wallpaper-actions{display:flex;align-items:center;gap:8px;margin-top:10px;min-width:0}.wbs-wallpaper-status{min-width:0;overflow-wrap:anywhere;font-size:11px;line-height:1.5;color:var(--wb-color-text-secondary)}.wbs-wallpaper-status[data-error="1"]{color:var(--wb-color-text-primary)}',+ '.wbs-wallpaper-hint{margin-top:8px;font-size:11px;line-height:1.6;overflow-wrap:anywhere;color:var(--wb-color-text-secondary)}',/* 官方壁纸网格 */'.wbs-wallpapers{display:grid;grid-template-columns:repeat(4,1fr);gap:6px}','.wbs-wp{border-radius:10px;overflow:hidden;cursor:pointer;border:2px solid transparent;transition:all .15s;position:relative}',@@ -18106,6 +18555,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-theme-seg{display:flex;background:var(--wb-bg-tertiary,#f0f0f0);border-radius:10px;padding:3px;gap:3px;margin-bottom:8px}','.wbs-theme-option{position:relative;text-align:center;line-height:normal}.wbs-theme-option input{position:absolute;opacity:0;width:1px;height:1px}.wbs-theme-option:has(input:focus-visible){outline:2px solid var(--wb-icon-secondary);outline-offset:1px}','.wbs-theme-opt{flex:1;min-width:0;padding:6px 4px;border:none;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',+ '#wbs-theme-seg .wbs-theme-option:has(input[value="system"]){flex:1.5}','.wbs-theme-opt:hover{color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-theme-opt.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.2)}',/* 背景图来源切换(WorkDaddy 壁纸 / 自定义背景图) */diff --git a/scripts/lib.js b/scripts/lib.jsindex f55936a..e480a56 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -84,6 +84,23 @@ function wdCompatAuthToken(auth) {return typeof value === 'string' ? value.trim() : '';}+/**+ * WorkBuddy 5.8 may redact account.phoneNumber while the access-token claims+ * still carry the account's verified mobile as preferred_username. Keep only+ * a strict mainland mobile shape; never expose arbitrary token claims.+ */+function wdCompatTokenPhone(token) {+ const parts = String(token || '').split('.');+ if (parts.length < 2) return '';+ try {+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));+ const candidates = [payload.phone_number, payload.phoneNumber, payload.mobile, payload.preferred_username];+ return candidates.map((value) => String(value == null ? '' : value).trim()).find((value) => /^1\d{10}$/.test(value)) || '';+ } catch (_) {+ return '';+ }+}+function wdCompatHasAuthCredential(auth) {if (!auth || typeof auth !== 'object') return false;const value = auth.accessToken ?? auth.access_token ?? auth.token;@@ -1727,6 +1744,8 @@ function listAccounts(dataDir) {item.tokenExpiresAt = j.auth.expiresAt || null;item.refreshExpiresAt = j.auth.refreshExpiresAt || null;item.lastRefreshTime = j.auth.lastRefreshTime || null;+ const tokenPhone = wdCompatTokenPhone(wdCompatAuthToken(j.auth));+ if (tokenPhone) item.phone = tokenPhone;}} catch (_) {/* 文件损坏则显示空字段 */@@ -1890,6 +1909,7 @@ module.exports = {wdCompatContainsEncryptedFields, // [wd-compat]wdCompatText, // [wd-compat]wdCompatAuthToken, // [wd-compat]+ wdCompatTokenPhone, // [wd-compat]wdCompatHasAuthCredential, // [wd-compat]normalizeAccountImportJson, // [wd-compat]wdCompatDecryptAuthJson, // [wd-compat]diff --git a/scripts/official-automation-sync.js b/scripts/official-automation-sync.jsnew file mode 100644index 0000000..f3928e9--- /dev/null+++ b/scripts/official-automation-sync.js@@ -0,0 +1,282 @@+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');++const AUTOMATION_COLUMNS = [+ 'id', 'name', 'prompt', 'status', 'schedule_type', 'next_run_at', 'last_run_at',+ 'cwds', 'rrule', 'scheduled_at', 'valid_from', 'valid_until', 'model_id',+ 'model_is_thinking', 'skills_json', 'push_to_wechat', 'push_to_wecom_bot',+ 'owner_user_id', 'owner_status', 'owner_source', 'expert_id', 'expert_marketplace',+ 'connector_ids_json', 'permission_mode', 'created_at', 'updated_at', 'deleted_at',+ 'wecom_bot_source', 'context_window', 'reasoning_effort', 'workspace_scope',+ 'wecom_bot_chat_id',+];++// Older WorkBuddy builds inserted NULL into columns that are NOT NULL in the+// current schema. Reusing the official defaults keeps those historical tasks+// copyable while preserving NULL for genuinely nullable columns.+const AUTOMATION_DEFAULTS = {+ cwds: '[]',+ rrule: '',+ model_is_thinking: 0,+ skills_json: '[]',+ push_to_wechat: 0,+ push_to_wecom_bot: 0,+ owner_status: 'legacy_unassigned',+ connector_ids_json: '[]',+};++function cleanUid(value) {+ const uid = String(value || '').trim();+ return /^[A-Za-z0-9_-]{1,128}$/.test(uid) ? uid : '';+}++function readMapping(file) {+ try {+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('invalid mapping');+ return value;+ } catch (error) {+ if (error.code === 'ENOENT') return {};+ // Never silently lose task identities and create untracked copies.+ throw new Error('官方定时任务同步记录无法读取');+ }+}++function writeMapping(file, mapping) {+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });+ const tmp = `${file}.tmp-${process.pid}`;+ fs.writeFileSync(tmp, JSON.stringify(mapping, null, 2) + '\n', { mode: 0o600 });+ fs.renameSync(tmp, file);+}++function taskKey(sourceUid, sourceId, targetUid) {+ return `${sourceUid}:${sourceId}:${targetUid}`;+}++function nodeKey(uid, id) {+ return `${uid}:${id}`;+}++// Account ownership and execution history stay local. Only task definitions+// participate in edit detection, so a scheduler tick cannot undo a rename.+const DEFINITION_COLUMNS = AUTOMATION_COLUMNS.filter((column) => ![+ 'id', 'owner_user_id', 'owner_status', 'owner_source', 'created_at', 'updated_at',+ 'next_run_at', 'last_run_at',+].includes(column));+const SCHEDULE_COLUMNS = ['schedule_type', 'rrule', 'scheduled_at', 'valid_from', 'valid_until', 'status'];++function columnValue(row, column) {+ return row[column] == null ? (AUTOMATION_DEFAULTS[column] ?? null) : row[column];+}++function fingerprint(row) {+ return crypto.createHash('sha256')+ .update(JSON.stringify(DEFINITION_COLUMNS.map((column) => columnValue(row, column))))+ .digest('hex');+}++function taskFreshness(row) {+ const value = row.updated_at ?? row.created_at;+ const number = Number(value);+ return Number.isFinite(number) ? number : (Date.parse(value) || 0);+}++function isLive(row) {+ return row.deleted_at == null && row.status !== 'ARCHIVED';+}++function mappingGraph(mapping) {+ const graph = new Map();+ const connect = (left, right) => {+ if (!graph.has(left)) graph.set(left, new Set());+ if (!graph.has(right)) graph.set(right, new Set());+ graph.get(left).add(right);+ graph.get(right).add(left);+ };+ Object.entries(mapping || {}).forEach(([key, value]) => {+ const parts = String(key).split(':');+ if (parts.length < 3 || !value || typeof value !== 'object') return;+ const sourceUid = parts.shift();+ const targetUid = parts.pop();+ const sourceId = parts.join(':');+ const targetId = String(value.targetAutomationId || '').trim();+ if (!cleanUid(sourceUid) || !cleanUid(targetUid) || !sourceId || !targetId) return;+ const sourceNode = nodeKey(sourceUid, sourceId);+ const targetNode = nodeKey(targetUid, targetId);+ connect(sourceNode, targetNode);+ });+ return { graph };+}++function componentNodes(graph, start) {+ const seen = new Set([start]);+ const queue = [start];+ while (queue.length) {+ const node = queue.shift();+ for (const next of graph.get(node) || []) {+ if (seen.has(next)) continue;+ seen.add(next);+ queue.push(next);+ }+ }+ return seen;+}++function insertStatement(source, targetUid, id) {+ const columns = AUTOMATION_COLUMNS;+ const values = columns.map((column) => {+ if (column === 'id') return id;+ if (column === 'owner_user_id') return targetUid;+ const value = source[column];+ if (value === undefined || value === null) {+ return Object.prototype.hasOwnProperty.call(AUTOMATION_DEFAULTS, column)+ ? AUTOMATION_DEFAULTS[column] : null;+ }+ return value;+ });+ const placeholders = columns.map(() => '?').join(', ');+ return {+ sql: `INSERT INTO automations (${columns.join(', ')}) VALUES (${placeholders})`,+ params: values,+ };+}++function createOfficialAutomationSync(options = {}) {+ const db = options.db;+ const mappingFile = options.mappingFile || path.join(String(options.dataDir || ''), 'official-automation-sync.json');+ const idFactory = options.idFactory || (() => crypto.randomUUID());+ if (!db || typeof db.all !== 'function') throw new TypeError('缺少官方定时任务数据库');++ async function reconcile(sourceValue, targetValue) {+ const sourceUid = cleanUid(sourceValue);+ const targetUid = cleanUid(targetValue);+ const result = { copied: 0, updated: 0, removed: 0, skipped: 0, total: 0 };+ if (!sourceUid || !targetUid || sourceUid === targetUid) return result;++ // Reconcile the union for all saved accounts, including a third account's+ // unique tasks, before the destination renderer reads its task list.+ const savedUids = options.getAccountUids ? await options.getAccountUids() : [];+ const owners = [...new Set([sourceUid, targetUid, ...savedUids.map(cleanUid)].filter(Boolean))];+ const rows = await db.all(`SELECT ${AUTOMATION_COLUMNS.join(', ')} FROM automations+ WHERE owner_user_id IN (${owners.map(() => '?').join(', ')})`, owners);+ const mapping = readMapping(mappingFile);+ const state = mapping.__syncState || {};+ const snapshots = state.snapshots || {};+ const retired = { ...(state.retired || {}) };+ const nextSnapshots = { ...snapshots };+ const { graph } = mappingGraph(mapping);+ const byNode = new Map(rows.map(row => [nodeKey(row.owner_user_id, row.id), row]));+ const visited = new Set();+ const groups = [];+ for (const [node] of byNode) {+ if (visited.has(node) || retired[node]) continue;+ const nodes = componentNodes(graph, node);+ nodes.forEach(n => visited.add(n));+ const members = [...nodes].filter(n => byNode.has(n) && !retired[n]).map(n => byNode.get(n));+ if (members.length) groups.push(members);+ }++ // Adopt identical pre-existing copies one-to-one across different owners.+ // Never collapse intentionally separate tasks in the same account, nor+ // once tasks whose scheduled dates differ.+ for (let i = 0; i < groups.length; i++) {+ const ownersInGroup = new Set(groups[i].map(r => r.owner_user_id));+ const hashes = new Set(groups[i].filter(isLive).map(fingerprint));+ for (let j = i + 1; j < groups.length; j++) {+ if (!groups[j].length || groups[j].some(r => ownersInGroup.has(r.owner_user_id))) continue;+ if (!groups[j].some(r => isLive(r) && hashes.has(fingerprint(r)))) continue;+ groups[j].forEach(r => { ownersInGroup.add(r.owner_user_id); if (isLive(r)) hashes.add(fingerprint(r)); });+ groups[i].push(...groups[j]);+ groups[j] = [];+ }+ }++ const statements = [];+ const usedIds = new Set(rows.map(r => r.id));+ const freshnessOrder = (a, b) => taskFreshness(b) - taskFreshness(a) ||+ Number(b.owner_user_id === sourceUid) - Number(a.owner_user_id === sourceUid) ||+ nodeKey(a.owner_user_id, a.id).localeCompare(nodeKey(b.owner_user_id, b.id));+ for (const members of groups) {+ if (!members.length) continue;+ // A genuine definition edit beats an unchanged copy whose updated_at+ // merely advanced during execution. On first migration use latest edit.+ const changed = members.filter(row => {+ const previous = snapshots[nodeKey(row.owner_user_id, row.id)];+ return previous && previous !== fingerprint(row);+ });+ const canonical = [...(changed.length ? changed : members)].sort(freshnessOrder)[0];+ const live = isLive(canonical);+ if (live) result.total++;+ const survivors = [];+ for (const owner of owners) {+ const candidates = members.filter(row => row.owner_user_id === owner).sort(freshnessOrder);+ let row = candidates[0];+ if (!row && !live) continue; // Do not manufacture deleted history.+ if (!row) {+ const id = String(idFactory());+ if (!/^[0-9a-f-]{8,128}$/i.test(id) || usedIds.has(id)) throw new Error('官方定时任务 ID 无效');+ usedIds.add(id);+ statements.push(insertStatement(canonical, owner, id));+ row = { ...canonical, id, owner_user_id: owner };+ result.copied++;+ } else if (fingerprint(row) !== fingerprint(canonical)) {+ const columns = [...DEFINITION_COLUMNS, 'updated_at'];+ // Renames do not overwrite the target's run history. A changed+ // schedule does need its new next occurrence, as in the official edit.+ if (SCHEDULE_COLUMNS.some(c => columnValue(row, c) !== columnValue(canonical, c))) columns.push('next_run_at');+ statements.push({+ sql: `UPDATE automations SET ${columns.map(c => `${c} = ?`).join(', ')} WHERE id = ? AND owner_user_id = ?`,+ params: [...columns.map(c => columnValue(canonical, c)), row.id, owner],+ });+ result.updated++;+ } else if (live) result.skipped++;+ survivors.push(row);+ nextSnapshots[nodeKey(owner, row.id)] = fingerprint(canonical);+ for (const duplicate of candidates.slice(1)) {+ retired[nodeKey(owner, duplicate.id)] = true;+ }+ }+ // Keep historical edges, including missing old IDs, so old A→B→H+ // mappings still identify reverse copies after upgrading or restarting.+ for (const row of survivors) {+ if (row.id === canonical.id) continue;+ mapping[taskKey(canonical.owner_user_id, canonical.id, row.owner_user_id)] = {+ targetAutomationId: row.id,+ sourceUpdatedAt: canonical.updated_at == null ? null : String(canonical.updated_at),+ };+ }+ }++ for (const row of rows) {+ if (!retired[nodeKey(row.owner_user_id, row.id)] || !isLive(row)) continue;+ statements.push({+ sql: 'UPDATE automations SET deleted_at = ? WHERE id = ? AND owner_user_id = ?',+ params: [Date.now(), row.id, row.owner_user_id],+ });+ result.removed++;+ }+ // Persist identities before SQL so a crash or failed mapping write cannot+ // leave an inserted task without a lineage. Only advance edit baselines+ // after the transaction commits. Retired rows are retried after failures.+ mapping.__syncState = { snapshots, retired };+ writeMapping(mappingFile, mapping);+ if (statements.length) await db.transaction(statements);+ mapping.__syncState = { snapshots: nextSnapshots, retired };+ writeMapping(mappingFile, mapping);+ return result;+ }++ // Manual/automation switches can both reach this service; serialize them so+ // they cannot generate two IDs from the same pre-sync snapshot.+ let pending = Promise.resolve();+ return function syncOfficialAutomations(sourceUid, targetUid) {+ const run = pending.then(() => reconcile(sourceUid, targetUid));+ pending = run.catch(() => {});+ return run;+ };+}++module.exports = { AUTOMATION_COLUMNS, cleanUid, createOfficialAutomationSync };diff --git a/scripts/profiles.js b/scripts/profiles.jsindex 717401a..6346a85 100644--- a/scripts/profiles.js+++ b/scripts/profiles.js@@ -97,7 +97,7 @@ const PROFILES = {// User/globalStorage/state.vscdb 只保存 VS Code 状态,不是模型配置。modelsFile: path.join(home, '.codebuddy', 'models.json'),apiHost: 'https://www.codebuddy.cn',- capabilities: { accounts: true, sessions: true, models: true, stashPrompt: false, nativeComposer: true, theme: true, themeTakeover: false, enhance: false, panelAppearance: 'light', robotStyle: 'black', apiTransport: 'cdp', checkin: true, growthDaily: true },+ capabilities: { accounts: true, sessions: true, models: true, stashPrompt: false, nativeComposer: true, theme: true, themeTakeover: false, enhance: false, panelAppearance: 'native', robotStyle: 'black', apiTransport: 'cdp', checkin: true, growthDaily: true },targetHints: ['codebuddy cn'],},'codebuddy-intl': {@@ -111,7 +111,7 @@ const PROFILES = {sessionDb: path.join(appSupport, 'CodeBuddy', 'codebuddy-sessions.vscdb'),modelsFile: path.join(home, '.codebuddy', 'models.json'),apiHost: 'https://www.codebuddy.ai',- capabilities: { accounts: true, sessions: true, models: true, stashPrompt: false, nativeComposer: true, theme: true, themeTakeover: false, enhance: false, panelAppearance: 'light', robotStyle: 'black', apiTransport: 'cdp', checkin: false, builtinAutomations: false },+ capabilities: { accounts: true, sessions: true, models: true, stashPrompt: false, nativeComposer: true, theme: true, themeTakeover: false, enhance: false, panelAppearance: 'native', robotStyle: 'black', apiTransport: 'cdp', checkin: false, builtinAutomations: false },targetHints: ['codebuddy'],},};diff --git a/scripts/relaunch-with-cdp.sh b/scripts/relaunch-with-cdp.shindex 64c02d5..b2dd72d 100644--- a/scripts/relaunch-with-cdp.sh+++ b/scripts/relaunch-with-cdp.sh@@ -162,6 +162,23 @@ if [ -f "$DIR/scripts/workbuddy-target.js" ]; thenfifi+# 单个企业客户端自动发现时也要持久化目标;否则启动路径虽然指向企业+# .app,daemon 仍会按官方 profile 读取 workbuddy-desktop.info。+if [ -z "${TARGET_BIN:-}" ] && [ -n "$APP_BIN" ]; then+ official_name="WorkBuddy"+ [ "$PROFILE" = workbuddy-ai ] && official_name="WorkBuddy AI"+ if [ "$APP_NAME" != "$official_name" ]; then+ if ! "$NODE_BIN" "$DIR/scripts/workbuddy-target.js" --configure --platform darwin \+ --profile="$PROFILE" --binary="$APP_BIN" --data-dir="$DATA_DIR" >/dev/null 2>"$TARGET_ERR"; then+ echo "错误:无法保存自动发现的 WorkBuddy 客户端: $(tr '\n' ' ' <"$TARGET_ERR")"+ rm -f "$TARGET_ERR"+ exit 1+ fi+ rm -f "$TARGET_ERR"+ TARGET_BIN="$APP_BIN"+ fi+fi+# 候选不唯一或自动扫描不到时交给 macOS 原生应用选择器,由用户明确选择并自动记住结果。if [ -z "${TARGET_BIN:-}" ] && [ -z "$APP_BIN" ]; thenSELECTED_APP="$(osascript <<'APPLESCRIPT' 2>/dev/nulldiff --git a/scripts/theme-patches.js b/scripts/theme-patches.jsindex 23e06c6..a189e6e 100644--- a/scripts/theme-patches.js+++ b/scripts/theme-patches.js@@ -519,7 +519,7 @@ module.exports = [id: 'patch-107',themeId: 'nebula',desc: '毛玻璃主题下新版 teams 输入工具条的语音、上下文用量和增强按钮触发器去掉背景色,避免右侧出现多余色块。',- css: ':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container .cr-input-toolbar__right>span:is(.cr-voice-trigger-tooltip,.cr-context-usage-tooltip-trigger,.cr-enhance-button-tooltip),body[data-vscode-theme-name="IDE Night"] .teams-container .cr-input-toolbar__right>span:is(.cr-voice-trigger-tooltip,.cr-context-usage-tooltip-trigger,.cr-enhance-button-tooltip){background:transparent !important;background-color:transparent !important;box-shadow:none !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',+ css: ':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container .cr-input-toolbar__right>span:is(.cr-voice-trigger-tooltip,.cr-context-usage-tooltip-trigger,.cr-enhance-button-tooltip),:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container .cr-input-toolbar__right>span.cr-voice-trigger-wrap>span.cr-voice-trigger-tooltip,body[data-vscode-theme-name="IDE Night"] .teams-container .cr-input-toolbar__right>span:is(.cr-voice-trigger-tooltip,.cr-context-usage-tooltip-trigger,.cr-enhance-button-tooltip),body[data-vscode-theme-name="IDE Night"] .teams-container .cr-input-toolbar__right>span.cr-voice-trigger-wrap>span.cr-voice-trigger-tooltip{background:transparent !important;background-color:transparent !important;box-shadow:none !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',},/* 原 patch-82(AI 端快捷短语弹层 z-index 抬升)已移入 inject.js 常驻样式:theme-patches 仅在非默认主题时注入,默认浅色主题下会失效;层级修复不依赖主题,随注入脚本常驻更可靠。 */diff --git a/scripts/wallpaper-rotation.js b/scripts/wallpaper-rotation.jsnew file mode 100644index 0000000..332731a--- /dev/null+++ b/scripts/wallpaper-rotation.js@@ -0,0 +1,273 @@+'use strict';++const fs = require('fs');+const path = require('path');+const crypto = require('crypto');+const { execFile } = require('child_process');+const { replaceFileWithRetry } = require('./atomic-file-write');+const MAX_BYTES = 20 * 1024 * 1024;+const MAX_PIXELS = 16 * 1024 * 1024;+const MAX_FILES = 5000;++// Inspect a bounded header before Chromium decodes an external image. Extension+// alone is insufficient: a tiny compressed image can allocate gigabytes.+function imageDimensions(b) {+ let width, height, mime;+ if (b.length >= 24 && b.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) && b.toString('ascii', 12, 16) === 'IHDR') {+ width = b.readUInt32BE(16); height = b.readUInt32BE(20); mime = 'image/png';+ } else if (b.length >= 30 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') {+ const format = b.toString('ascii', 12, 16);+ if (format === 'VP8X') {+ if (b[20] & 2) throw new Error('不支持动态壁纸');+ width = b.readUIntLE(24, 3) + 1; height = b.readUIntLE(27, 3) + 1;+ } else if (format === 'VP8 ' && b[23] === 0x9d && b[24] === 1 && b[25] === 0x2a) {+ width = b.readUInt16LE(26) & 0x3fff; height = b.readUInt16LE(28) & 0x3fff;+ } else if (format === 'VP8L' && b[20] === 0x2f) {+ const bits = b.readUInt32LE(21); width = (bits & 0x3fff) + 1; height = ((bits >>> 14) & 0x3fff) + 1;+ }+ mime = 'image/webp';+ } else if (b.length > 4 && b[0] === 0xff && b[1] === 0xd8) {+ let offset = 2;+ while (offset + 4 < b.length) {+ if (b[offset++] !== 0xff) break;+ while (b[offset] === 0xff) offset++;+ const marker = b[offset++];+ if (marker === 0xd9 || marker === 0xda) break;+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;+ if (offset + 2 > b.length) break;+ const length = b.readUInt16BE(offset);+ if (length < 2 || offset + length > b.length) break;+ if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker) && length >= 7) {+ height = b.readUInt16BE(offset + 3); width = b.readUInt16BE(offset + 5); mime = 'image/jpeg'; break;+ }+ offset += length;+ }+ }+ if (!width || !height || width > 8192 || height > 8192 || width * height > MAX_PIXELS) throw new Error('图片无效或超过 1600 万像素');+ return { width, height, mime };+}++async function scanDirectory(directory) {+ if (typeof directory !== 'string' || !path.isAbsolute(directory) || directory.includes('\0')) throw new Error('请选择有效的壁纸文件夹');+ let real, entries;+ try { real = await fs.promises.realpath(directory); entries = await fs.promises.opendir(real); }+ catch (_) { throw new Error('壁纸目录不可用,请重新选择文件夹'); }+ const files = []; let visited = 0; let limited = false;+ for await (const entry of entries) {+ if (entry.isFile() && /\.(png|jpe?g|webp)$/i.test(entry.name)) files.push(entry.name);+ if (++visited >= 20000 || files.length >= MAX_FILES) { limited = true; break; }+ }+ if (!files.length) throw new Error('文件夹中没有 PNG / JPG / WebP 图片');+ return { directory: real, files, limited };+}++function createWallpaperRotation(options) {+ const now = options.now || Date.now;+ const random = options.random || Math.random;+ const schedule = options.setTimeout || setTimeout;+ const cancel = options.clearTimeout || clearTimeout;+ let config = { mode: 'manual', directory: '', intervalMinutes: 10, current: '' };+ try {+ const saved = JSON.parse(fs.readFileSync(options.configFile, 'utf8'));+ if (['manual', 'random'].includes(saved.mode) && typeof saved.directory === 'string' &&+ Number.isInteger(saved.intervalMinutes) && saved.intervalMinutes >= 1 && saved.intervalMinutes <= 1440) {+ config = { mode: saved.mode, directory: saved.directory, intervalMinutes: saved.intervalMinutes,+ current: typeof saved.current === 'string' && path.basename(saved.current) === saved.current ? saved.current : '' };+ }+ } catch (_) {}+ let files = [], bag = [], limited = false, generation = 0, configRequest = 0, nextAt = 0;+ let error = '', timer, flight, flightGeneration, destroyed = false, wasActive = false;+ const tickets = new Map();+ function persist() { replaceFileWithRetry(options.configFile, JSON.stringify(config, null, 2), 0o600); }+ function status() {+ return { ...config, count: files.length, limited, error,+ paused: config.mode === 'random' && !options.isActive(), nextAt };+ }+ function arm() {+ cancel(timer);+ if (destroyed || config.mode !== 'random') return;+ const delay = options.isActive() && nextAt > now() ? Math.min(15000, nextAt - now()) : 15000;+ timer = schedule(() => tick().catch(() => {}), Math.max(1000, delay));+ if (timer && timer.unref) timer.unref();+ }+ async function openFile(name) {+ if (!name || path.basename(name) !== name || !files.includes(name)) throw new Error('壁纸不可用');+ const file = path.join(config.directory, name);+ const real = await fs.promises.realpath(file);+ if (path.dirname(real) !== config.directory || real !== file) throw new Error('壁纸路径已变化');+ const handle = await fs.promises.open(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));+ try {+ const stat = await handle.stat();+ if (!stat.isFile() || stat.size > MAX_BYTES || stat.size < 24) throw new Error('图片无效或超过 20MB');+ const header = Buffer.alloc(Math.min(stat.size, 256 * 1024));+ await handle.read(header, 0, header.length, 0);+ const dimensions = imageDimensions(header);+ return { handle, size: stat.size, ...dimensions };+ } catch (e) { await handle.close(); throw e; }+ }+ function choose() {+ if (!bag.length) {+ bag = files.slice();+ for (let i = bag.length - 1; i > 0; i--) { const j = Math.floor(random() * (i + 1)); [bag[i], bag[j]] = [bag[j], bag[i]]; }+ if (bag.length > 1 && bag[bag.length - 1] === config.current) [bag[0], bag[bag.length - 1]] = [bag[bag.length - 1], bag[0]];+ }+ return bag.pop();+ }+ async function run(restore) {+ if (destroyed || config.mode !== 'random') return status();+ if (!options.isActive()) {+ if (wasActive && options.invalidate) await options.invalidate();+ wasActive = false; nextAt = 0; arm(); return status();+ }+ const version = generation;+ wasActive = true;+ try {+ const scanned = await scanDirectory(config.directory);+ if (version !== generation || destroyed) return status();+ if (scanned.directory !== config.directory) throw new Error('壁纸目录不可用,请重新选择文件夹');+ if (files.join('\0') !== scanned.files.join('\0')) bag = [];+ files = scanned.files; limited = scanned.limited;+ const attempts = Math.min(files.length, 32); // Bound work when a folder contains corrupt files.+ for (let attempt = 0; attempt < attempts; attempt++) {+ const name = restore && attempt === 0 && files.includes(config.current) ? config.current : choose();+ if (restore && attempt === 0 && name === config.current) bag = bag.filter(file => file !== name);+ let image;+ try { image = await openFile(name); await image.handle.close(); }+ catch (_) { continue; }+ if (version !== generation || destroyed || !options.isActive()) return status();+ const key = crypto.randomBytes(24).toString('hex');+ tickets.set(key, { name, generation: version });+ let applied = false;+ try { applied = await options.apply({ key, name }); }+ catch (_) { tickets.delete(key); throw new Error('等待客户端连接后恢复壁纸'); }+ if (version !== generation || destroyed) { tickets.delete(key); return status(); }+ if (!applied) { tickets.delete(key); continue; }+ // Keep only the currently displayed file and its short-lived successor.+ for (const ticket of tickets.keys()) if (ticket !== key) tickets.delete(ticket);+ config.current = name; error = ''; nextAt = now() + config.intervalMinutes * 60000;+ persist(); return status();+ }+ throw new Error('未找到可用壁纸,请检查图片格式、大小或更换文件夹');+ } catch (e) {+ if (version === generation) { error = e.message; nextAt = now() + config.intervalMinutes * 60000; }+ return status();+ } finally { arm(); }+ }+ function enqueue(restore) {+ if (flight) {+ if (flightGeneration === generation) return flight;+ const version = generation;+ return flight.then(() => version === generation ? enqueue(restore) : status());+ }+ flightGeneration = generation;+ flight = run(restore).finally(() => { flight = null; });+ return flight;+ }+ async function tick() {+ if (config.mode !== 'random' || destroyed) return;+ if (!options.isActive()) return enqueue(true);+ if (!wasActive) return enqueue(true);+ if (now() >= nextAt) return enqueue(false);+ arm();+ }+ async function configure(body) {+ const request = ++configRequest;+ if (!body || !['manual', 'random'].includes(body.mode)) throw new Error('请选择壁纸模式');+ let scanned;+ let intervalMinutes = config.intervalMinutes;+ if (body.mode === 'random') {+ intervalMinutes = Number(body.intervalMinutes);+ if (!Number.isInteger(intervalMinutes) || intervalMinutes < 1 || intervalMinutes > 1440) throw new Error('切换间隔须为 1–1440 分钟的整数');+ scanned = await scanDirectory(body.directory);+ if (request !== configRequest) return status();+ }+ generation++; cancel(timer); tickets.clear();+ const previous = config;+ config = { ...config, mode: body.mode, intervalMinutes,+ directory: scanned ? scanned.directory : config.directory,+ current: scanned && scanned.directory !== config.directory ? '' : config.current };+ try { persist(); } catch (_) { config = previous; arm(); throw new Error('壁纸设置保存失败'); }+ if (scanned) { files = scanned.files; limited = scanned.limited; }+ bag = []; error = ''; nextAt = 0; wasActive = false;+ if (options.invalidate) await options.invalidate();+ if (request === configRequest && config.mode === 'random') return enqueue(true);+ return status();+ }+ arm();+ return { status, configure, next: () => enqueue(false), restore: () => enqueue(true),+ async openImage(key) {+ const ticket = tickets.get(key);+ if (!ticket || ticket.generation !== generation || config.mode !== 'random') throw new Error('壁纸已失效');+ return openFile(ticket.name);+ },+ destroy() { destroyed = true; generation++; cancel(timer); tickets.clear(); },+ };+}++// Serialized through CDP. No theme reapplication, React access, persistent+// observer or renderer interval. A pending load cannot overwrite a later choice.+async function updateWallpaperInRenderer(options) {+ let runtime = window.__wbsWallpaperRuntime;+ if (!runtime) {+ runtime = { current: '', pending: null, dispose() {+ if (runtime.pending) { runtime.pending.controller.abort(); if (runtime.pending.url) { URL.revokeObjectURL(runtime.pending.url); runtime.pending.url = ''; } }+ if (runtime.current) URL.revokeObjectURL(runtime.current);+ runtime.current = ''; runtime.pending = null;+ document.documentElement.style.removeProperty('--wbs-wallpaper-image');+ if (window.__wbsWallpaperRuntime === runtime) delete window.__wbsWallpaperRuntime;+ } };+ window.__wbsWallpaperRuntime = runtime;+ }+ if (runtime.pending) runtime.pending.controller.abort();+ const pending = { controller: new AbortController(), url: '' };+ runtime.pending = pending;+ let timeout;+ try {+ const load = async () => {+ const response = await fetch(options.url, { headers: { 'X-WorkDaddy-Token': options.token }, cache: 'no-store', signal: pending.controller.signal });+ if (!response.ok) throw new Error('wallpaper unavailable');+ const blob = await response.blob();+ if (pending.controller.signal.aborted || window.__wbsWallpaperRuntime !== runtime) return false;+ pending.url = URL.createObjectURL(blob);+ const image = new Image(); image.src = pending.url;+ await image.decode(); image.src = '';+ if (pending.controller.signal.aborted || runtime.pending !== pending || window.__wbsWallpaperRuntime !== runtime ||+ document.documentElement.getAttribute('data-wbs-theme-id') !== 'nebula') return false;+ const old = runtime.current;+ runtime.current = pending.url; pending.url = '';+ document.documentElement.style.setProperty('--wbs-wallpaper-image', 'url("' + runtime.current + '")');+ if (old) URL.revokeObjectURL(old);+ return true;+ };+ return await Promise.race([load(), new Promise(resolve => { timeout = setTimeout(() => { pending.controller.abort(); resolve(false); }, 8000); })]);+ } catch (_) { return false; }+ finally {+ clearTimeout(timeout);+ if (pending.url) { URL.revokeObjectURL(pending.url); pending.url = ''; }+ if (runtime.pending === pending) runtime.pending = null;+ }+}++let pickerPending = false;+function pickWallpaperDirectory(platform = process.platform) {+ if (pickerPending) return Promise.reject(new Error('文件夹选择窗口已打开'));+ pickerPending = true;+ let executable, args;+ if (platform === 'darwin') {+ executable = '/usr/bin/osascript'; args = ['-e', 'POSIX path of (choose folder with prompt "选择壁纸文件夹")'];+ } else if (platform === 'win32') {+ executable = 'powershell.exe';+ const script = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Windows.Forms; $picker = New-Object System.Windows.Forms.FolderBrowserDialog; $picker.Description = "选择壁纸文件夹"; $picker.ShowNewFolderButton = $false; if ($picker.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Write($picker.SelectedPath) }; $picker.Dispose()';+ args = ['-NoProfile', '-STA', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')];+ } else {+ executable = 'zenity'; args = ['--file-selection', '--directory', '--title=选择壁纸文件夹'];+ }+ return new Promise((resolve, reject) => execFile(executable, args, { encoding: 'utf8', timeout: 120000, maxBuffer: 16384, windowsHide: true }, (error, stdout) => {+ pickerPending = false;+ if (error && (platform === 'darwin' && /-128/.test(error.message) || platform === 'linux' && error.code === 1)) return resolve('');+ if (error) return reject(new Error('无法打开文件夹选择窗口,请填写目录路径'));+ resolve(String(stdout || '').replace(/^\uFEFF/, '').trim());+ }));+}++module.exports = { createWallpaperRotation, imageDimensions, updateWallpaperInRenderer, pickWallpaperDirectory };diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex 6db3dc7..34d312d 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -52,6 +52,8 @@ const { getProfile, profileDataDir, isCodeBuddyBinary } = require('./profiles.jsconst { isTargetForProfile } = require('./cdp-targets.js');const { replaceFileWithRetry } = require('./atomic-file-write.js');const { parseUiPortState, profileUiPortCandidates } = require('./ui-port.js');+const { getClientLaunchArgs } = require('./client-launch-settings.js');+const { getWorkBuddyLaunchEnv } = require('./workbuddy-launch-env.js');const SCRIPTS_DIR = __dirname;const WORKDADDY_APP_DIR = path.resolve(SCRIPTS_DIR, '..');@@ -1162,9 +1164,9 @@ function launchWorkBuddy(wb) {const environmentMode = !!(PROFILE.cdp && PROFILE.cdp.mode === 'environment');const args = environmentMode ? [] : ['--remote-debugging-port=' + CDP_PORT];if (PROFILE.nativeDebugPort) args.push('--inspect=127.0.0.1:' + PROFILE.nativeDebugPort);- const env = environmentMode- ? { ...process.env, WORKBUDDY_REMOTE_DEBUGGING_PORT: String(CDP_PORT) }- : process.env;+ args.push(...getClientLaunchArgs(DATA_DIR, PROFILE.id, process.platform));+ const env = getWorkBuddyLaunchEnv(PROFILE, DATA_DIR, process.platform, process.env);+ if (environmentMode) env.WORKBUDDY_REMOTE_DEBUGGING_PORT = String(CDP_PORT);const child = spawn(wb, args, {// WorkBuddy 是 GUI 程序:windowsHide:true 会把 STARTUPINFO 的 wShowWindow 置为 SW_HIDE,// 新版 Electron 主窗口显示走 ShowWindow(SW_SHOWDEFAULT) 会继承该值,导致主窗口隐藏启动、diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.goindex 05a0384..3da5fce 100644--- a/scripts/windows-native/main.go+++ b/scripts/windows-native/main.go@@ -634,6 +634,9 @@ func workBuddyImage(profile string) string {if profile == profileAI {return "WorkBuddyAI.exe"}+ if profile == profileCN {+ return "WorkBuddy.exe"+ }return "WorkBuddy.exe"}diff --git a/scripts/workbuddy-launch-env.js b/scripts/workbuddy-launch-env.jsnew file mode 100644index 0000000..12112ff--- /dev/null+++ b/scripts/workbuddy-launch-env.js@@ -0,0 +1,45 @@+'use strict';++const fs = require('fs');+const path = require('path');++// Update origins differ from the billing/API host (CN uses codebuddy.cn there).+const UPDATE_ORIGINS = Object.freeze({+ 'workbuddy-cn': 'https://www.workbuddy.cn',+ 'workbuddy-ai': 'https://www.workbuddy.ai',+});++function getWorkBuddyLaunchEnv(profile, dataDir, platform = process.platform, env = process.env) {+ const childEnv = { ...env };+ if (platform !== 'win32' || profile.customTarget || !Object.hasOwn(UPDATE_ORIGINS, profile.id)) return childEnv;+ if (!profile.dataRoot || !path.isAbsolute(profile.dataRoot) || !dataDir || !path.isAbsolute(dataDir)) {+ throw new Error('无法隔离 WorkBuddy 更新:客户端或 WorkDaddy 数据目录不是绝对路径');+ }++ // #424: the official Windows updater restores cached Setup.exe files before+ // checking its feed. Pinning the URL alone cannot exclude a sibling installer.+ // A stable profile-specific TEMP isolates the cache without deleting any files.+ // Use DATA_DIR rather than inherited TEMP so child restarts cannot nest paths.+ const tempDir = path.join(dataDir, 'client-tmp', profile.id);+ try {+ fs.mkdirSync(tempDir, { recursive: true, mode: 0o700 });+ } catch (error) {+ throw new Error('无法创建 WorkBuddy 独立临时目录,请检查 WorkDaddy 数据目录的写入权限', { cause: error });+ }+ const overrides = {+ WORKBUDDY_UPDATE_URL: UPDATE_ORIGINS[profile.id],+ WORKBUDDY_CONFIG_DIR: profile.dataRoot,+ CODEBUDDY_CONFIG_DIR: profile.dataRoot,+ WORKBUDDY_DATA_FOLDER_NAME: path.basename(profile.dataRoot),+ TEMP: tempDir,+ TMP: tempDir,+ };+ // Windows keys are case-insensitive. Remove aliases before adding canonical+ // names; Node otherwise passes only the first case variant to the child.+ for (const key of Object.keys(childEnv)) {+ if (Object.hasOwn(overrides, key.toUpperCase())) delete childEnv[key];+ }+ return Object.assign(childEnv, overrides);+}++module.exports = { getWorkBuddyLaunchEnv };diff --git a/scripts/workbuddy-target.js b/scripts/workbuddy-target.jsindex f1ee69b..95943ab 100644--- a/scripts/workbuddy-target.js+++ b/scripts/workbuddy-target.js@@ -173,6 +173,39 @@ function findAuthFile(authDir, stem) {return matches.length === 1 ? path.join(authDir, matches[0]) : '';}+// macOS 企业客户端的 Electron 进程名固定为 Electron,不能像 Windows/Linux+// 一样从可执行文件名推导凭据文件。优先用 .app 名称生成精确文件名,+// 再在 auth 目录中选择唯一的带后缀凭据,避免被历史遗留的官方文件遮蔽。+function findMacAuthFile(authDir, appName, profileId) {+ const canonical = path.join(authDir, profileId === 'workbuddy-ai'+ ? 'workbuddy-desktop-ai.info'+ : 'workbuddy-desktop.info');+ let names;+ try {+ names = fs.readdirSync(authDir).filter((name) => /^workbuddy-desktop(?:-[^/]+)?\.info$/i.test(name));+ } catch (_) {+ return canonical;+ }+ const officialName = profileId === 'workbuddy-ai' ? 'WorkBuddy AI' : 'WorkBuddy';+ if (clean(appName).toLowerCase() === officialName.toLowerCase()) return canonical;+ const suffix = clean(appName).replace(/^workbuddy(?:\s*ai)?[\s_-]*/i, '').trim();+ if (suffix) {+ const exact = path.join(authDir, `workbuddy-desktop-${suffix}.info`);+ if (names.some((name) => name === path.basename(exact))) return exact;+ }+ const custom = names.filter((name) => !/^workbuddy-desktop(?:-ai)?\.info$/i.test(name));+ if (custom.length === 1) return path.join(authDir, custom[0]);+ if (suffix && custom.length > 1) {+ const tokens = suffix.toLowerCase().split(/[^a-z0-9\u0080-\uffff]+/).filter((token) => token.length > 1);+ const matched = custom.filter((name) => {+ const lower = name.toLowerCase();+ return tokens.length > 0 && tokens.every((token) => lower.includes(token));+ });+ if (matched.length === 1) return path.join(authDir, matched[0]);+ }+ return canonical;+}+function buildTargetFromBinary(options = {}) {const platform = options.platform || process.platform;const pathApi = platformPath(platform);@@ -252,6 +285,13 @@ function buildTargetFromBinary(options = {}) {const extensionAuth = posixPath.join(appSupport, 'CodeBuddyExtension', 'Data', 'Public', 'auth');const ai = profileId === 'workbuddy-ai';const workbuddyRoot = posixPath.join(home, ai ? '.workbuddy-ai' : '.workbuddy');+ const authFile = findMacAuthFile(extensionAuth, appName, profileId);+ let apiHost = ai ? 'https://www.workbuddy.ai' : 'https://www.codebuddy.cn';+ try {+ if (fs.existsSync(authFile)) {+ apiHost = apiHostFromAuth(JSON.parse(fs.readFileSync(authFile, 'utf8'))) || apiHost;+ }+ } catch (_) {}return validateTarget({schemaVersion: 1,clientType: 'enterprise',@@ -259,10 +299,10 @@ function buildTargetFromBinary(options = {}) {binary,version: clean(options.version),processNames: [processName],- authFile: posixPath.join(extensionAuth, ai ? 'workbuddy-desktop-ai.info' : 'workbuddy-desktop.info'),+ authFile,sessionDb: posixPath.join(workbuddyRoot, 'workbuddy.db'),modelsFile: posixPath.join(workbuddyRoot, 'models.json'),- apiHost: ai ? 'https://www.workbuddy.ai' : 'https://www.codebuddy.cn',+ apiHost,targetHints: [appName].filter(Boolean),cdp: { mode: 'argument', port },capabilities: { accounts: true, sessions: true, models: true, stashPrompt: true, theme: true, checkin: true },diff --git a/test/account-import-clipboard.test.js b/test/account-import-clipboard.test.jsnew file mode 100644index 0000000..342b34d--- /dev/null+++ b/test/account-import-clipboard.test.js@@ -0,0 +1,85 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');+const vm = require('node:vm');++const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+const start = source.indexOf(' function copyPlainText(');+const end = source.indexOf('\n // 导出账号', start);+assert.ok(start >= 0 && end > start);++function loadClipboard(clipboard, { copied = true, copyThrows = false } = {}) {+ const children = new Set();+ const calls = [];+ const previousFocus = { focus() { calls.push('restore-focus'); document.activeElement = this; } };+ const document = {+ activeElement: previousFocus,+ createElement(tag) {+ assert.equal(tag, 'textarea');+ return {+ style: {},+ setAttribute() {},+ select() { document.activeElement = this; calls.push(['select', this.value]); },+ remove() { children.delete(this); },+ };+ },+ body: {+ appendChild(node) { children.add(node); },+ removeChild(node) { assert.ok(children.delete(node)); },+ },+ execCommand(command) {+ assert.equal(command, 'copy');+ calls.push('copy');+ if (copyThrows) throw new Error('legacy clipboard unavailable');+ return copied;+ },+ };+ const context = { navigator: { clipboard }, document };+ vm.runInNewContext(source.slice(start, end) + '\nthis.copy = copyPlainText;', context);+ return { copy: context.copy, calls, children, document, previousFocus };+}++const prompt = '请整理成 WorkDaddy 可导入的 JSON。\n只输出 JSON。';++test('account import copy uses the native clipboard when writing succeeds', async () => {+ const writes = [];+ const fixture = loadClipboard({ writeText(text) { writes.push(text); return Promise.resolve(); } });+ await fixture.copy(prompt);+ assert.deepEqual(writes, [prompt]);+ assert.deepEqual(fixture.calls, []);+ assert.equal(fixture.children.size, 0);+});++for (const [name, clipboard] of [+ ['clipboard permission denied', { writeText() { return Promise.reject(Object.assign(new Error('Write permission denied'), { name: 'NotAllowedError' })); } }],+ ['clipboard throws synchronously', { writeText() { throw new Error('clipboard unavailable'); } }],+ ['clipboard API absent', undefined],+]) {+ test(`account import copy falls back when ${name} and restores modal focus`, async () => {+ const fixture = loadClipboard(clipboard);+ await fixture.copy(prompt);+ assert.deepEqual(fixture.calls, [['select', prompt], 'copy', 'restore-focus']);+ assert.equal(fixture.children.size, 0);+ assert.equal(fixture.document.activeElement, fixture.previousFocus);+ });+}++for (const copyThrows of [false, true]) {+ test(`account import copy reports failure and cleans up when fallback ${copyThrows ? 'throws' : 'returns false'}`, async () => {+ const fixture = loadClipboard({ writeText() { return Promise.reject(new Error('denied')); } }, { copied: false, copyThrows });+ await assert.rejects(fixture.copy(prompt), /复制失败/);+ assert.deepEqual(fixture.calls, [['select', prompt], 'copy', 'restore-focus']);+ assert.equal(fixture.children.size, 0);+ assert.equal(fixture.document.activeElement, fixture.previousFocus);+ });+}++test('account import copy button uses the tested clipboard helper', () => {+ const start = source.indexOf(' function openAccountImportChoice(');+ const end = source.indexOf(' function formatTokenCount(', start);+ assert.ok(start >= 0 && end > start);+ assert.match(source.slice(start, end), /copyBtn\.addEventListener\('click',[\s\S]*?copyPlainText\(prompt\)\.then\(/);+});diff --git a/test/account-snapshot-reload.test.js b/test/account-snapshot-reload.test.jsindex cace5ba..0cad55d 100644--- a/test/account-snapshot-reload.test.js+++ b/test/account-snapshot-reload.test.js@@ -14,7 +14,9 @@ function harness(options = {}) {let armed = false, settled = false, profileReads = 0, initialAccount;let live = { uid: 'target', nickname: '新账号 % &', type: 'personal', editionType: 'experience', isPro: false, accessToken: 'synthetic-secret' };if (Object.hasOwn(options, 'profile')) live = options.profile;- const renderer = { URL, location, wb: options.missingApi ? undefined : { account: { profile: async () => {+ const renderer = { URL, location, history: { state: null, replaceState: (_state, _title, url) => {+ location.href = url;+ } }, wb: options.missingApi ? undefined : { account: { profile: async () => {profileReads++;if (options.profileThrows) throw new Error('synthetic-secret');return live;@@ -33,8 +35,9 @@ function harness(options = {}) {calls.push({ method, params });if (method === 'Page.getFrameTree') return { frameTree: { frame: { id: 'main' } } };if (method === 'Runtime.evaluate') {- if (options.evaluateThrows) throw new Error('synthetic-secret');- if (options.exceptionDetails) return { exceptionDetails: { text: 'synthetic-secret' } };+ if (options.evaluateThrows && params.expression.includes('account.profile')) throw new Error('synthetic-secret');+ if (options.exceptionDetails && params.expression.includes('account.profile')) return { exceptionDetails: { text: 'synthetic-secret' } };+ if (options.clearThrows && params.expression.includes('replaceState')) throw new Error('synthetic-secret');return { result: { value: await vm.runInNewContext(params.expression, renderer) } };}assert.equal(armed, true, 'arm injection before navigation or reload');@@ -84,9 +87,21 @@ for (const options of [const h = harness(options);assert.equal(await h.run(), true);assert.equal(h.calls.at(-1).method, 'Page.reload');+ assert.equal(h.initial(), null, 'fallback must not hydrate the previous account or its entitlement');+ const next = new URL(h.location.href);+ assert.equal(next.searchParams.get('extra'), 'a&b');+ assert.equal(next.hash, '#chat');assert.doesNotMatch(h.logs.join('\n'), /synthetic-secret|accountSnapshot=/);});+test('failed snapshot cleanup refuses to reload the old account', async () => {+ const h = harness({ missingApi: true, clearThrows: true });+ await assert.rejects(h.run(), /清除.*账号快照/);+ assert.equal(h.calls.some(c => c.method === 'Page.reload'), false);+ assert.equal(h.settled(), true);+ assert.doesNotMatch(h.logs.join('\n'), /synthetic-secret/);+});+for (const options of [{ kind: 'codebuddy' }]) test('clients without the WorkBuddy snapshot contract keep normal reload: ' + JSON.stringify(options), async () => {const h = harness(options);await h.run();diff --git a/test/auth-discovery.test.js b/test/auth-discovery.test.jsindex 9ee6d76..f24ed38 100644--- a/test/auth-discovery.test.js+++ b/test/auth-discovery.test.js@@ -100,6 +100,24 @@ test('account listing marks backups that cannot be used for a dynamic switch', (}});+test('account listing recovers the verified mobile from the token when WorkBuddy redacts phoneNumber', () => {+ const f = fixture();+ try {+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });+ const payload = Buffer.from(JSON.stringify({ preferred_username: '13592246735' }), 'utf8').toString('base64url');+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'masked.info'), JSON.stringify({+ account: { uid: 'masked', nickname: '135****6735', phoneNumber: '135****6735', uin: '330112549868' },+ auth: { accessToken: `header.${payload}.signature`, domain: 'https://www.workbuddy.cn' },+ }));+ const account = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.listAccounts(process.env.WBSWITCH_DATA_DIR)[0]))');+ assert.equal(account.nickname, '135****6735');+ assert.equal(account.phone, '13592246735');+ assert.equal(account.uin, '330112549868');+ } finally {+ fs.rmSync(f.root, { recursive: true, force: true });+ }+});+test('multiple valid files without one lastLogin marker are ambiguous and backup all', () => {const f = fixture();try {diff --git a/test/automation-account-sync.test.js b/test/automation-account-sync.test.jsnew file mode 100644index 0000000..77c4b81--- /dev/null+++ b/test/automation-account-sync.test.js@@ -0,0 +1,70 @@+'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 { writeAutomations, readAutomations } = require('../scripts/automation');+const sync = require('../scripts/automation-account-sync');+const daemonSource = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+const injectSource = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');++const task = (id, extra = {}) => ({+ schemaVersion: 1,+ id,+ name: id,+ enabled: true,+ trigger: { type: 'manual' },+ steps: [],+ ...extra,+});++test('account task sync scopes source tasks and preserves target edits', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-automation-sync-'));+ try {+ writeAutomations(dir, [+ task('source-task', { schedule: { type: 'interval', minutes: 60 }, [sync.ACCOUNT_SCOPE_KEY]: ['source'] }),+ task('legacy-scheduled', { schedule: { type: 'daily', time: '08:00' } }),+ task('legacy-global'),+ task('already-target', { schedule: { type: 'daily', time: '09:00' }, [sync.ACCOUNT_SCOPE_KEY]: ['source', 'target'] }),+ task('target-edit', { enabled: false, [sync.ACCOUNT_SCOPE_KEY]: ['target'] }),+ task('manual-source', { [sync.ACCOUNT_SCOPE_KEY]: ['source'] }),+ ]);+ const result = sync.syncAutomationsToAccount(dir, 'source', 'target');+ assert.equal(result.copied, 2);+ assert.equal(result.skipped, 1);+ const tasks = readAutomations(dir);+ assert.deepEqual(tasks.find((item) => item.id === 'source-task')[sync.ACCOUNT_SCOPE_KEY], ['source', 'target']);+ assert.deepEqual(tasks.find((item) => item.id === 'legacy-scheduled')[sync.ACCOUNT_SCOPE_KEY], ['source', 'target']);+ assert.equal(tasks.find((item) => item.id === 'legacy-global')[sync.ACCOUNT_SCOPE_KEY], undefined);+ assert.equal(tasks.find((item) => item.id === 'target-edit').enabled, false);+ assert.deepEqual(sync.readAccountAutomations(dir, 'target').map((item) => item.id).sort(), ['already-target', 'legacy-global', 'legacy-scheduled', 'source-task', 'target-edit']);+ assert.deepEqual(sync.readAccountAutomations(dir, 'other').map((item) => item.id), ['legacy-global']);+ assert.deepEqual(readAutomations(dir).find((item) => item.id === 'manual-source')[sync.ACCOUNT_SCOPE_KEY], ['source']);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('sync setting is explicit and disabled by default', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-automation-sync-setting-'));+ try {+ assert.deepEqual(sync.readAutomationSyncSettings(dir), { enabled: false });+ assert.deepEqual(sync.writeAutomationSyncSettings(dir, true), { enabled: true });+ assert.deepEqual(sync.readAutomationSyncSettings(dir), { enabled: true });+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('daemon and sessions pane expose account task sync without coupling it to session copy', () => {+ assert.match(daemonSource, /GET' && p === '\/api\/automations\/auto-sync'/);+ assert.match(daemonSource, /POST' && p === '\/api\/automations\/auto-sync'/);+ assert.match(daemonSource, /syncAccountAutomations\(sourceUid, uid\)/);+ assert.match(daemonSource, /automationSync/);+ assert.match(injectSource, /id="wbs-sess-auto-automations"/);+ assert.match(injectSource, /loadAutomationSyncSetting/);+ assert.match(injectSource, /\/api\/automations\/auto-sync/);+ assert.match(injectSource, /同步定时任务/);+});diff --git a/test/cdp-custom-target.test.js b/test/cdp-custom-target.test.jsnew file mode 100644index 0000000..426c92f--- /dev/null+++ b/test/cdp-custom-target.test.js@@ -0,0 +1,97 @@+'use strict';++// 在任意平台执行 daemon 的真实发现/注入函数;CDP 响应为脱敏 fixture。+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');+const { PROFILES } = require('../scripts/profiles');+const { classifyTarget, isTargetForProfile, selectPageTarget } = require('../scripts/cdp-targets');+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+const own = { type: 'page', title: 'WorkBuddy',+ url: 'file:///C:/Programs/WorkBuddy/resources/app.asar/renderer/index.html' };+const other = { ...own, url: 'file:///D:/Programs/WorkBuddy/resources/app.asar/renderer/index.html' };+const profile = { ...PROFILES['workbuddy-ai'], customTarget: true,+ appPath: 'C:\\Programs\\WorkBuddy\\WorkBuddy.exe',+ apiHost: 'https://www.workbuddy.cn', targetHints: ['workbuddy'] };++function harness({ targets = [own], unavailable = false, activeProfile = profile } = {}) {+ const evaluations = [];+ const requests = [];+ const cdp = { connected: false, port: null };+ const context = vm.createContext({+ PROFILE: activeProfile, cdp, classifyTarget, isTargetForProfile, selectPageTarget,+ process: { env: { WBSWITCH_PROFILE: 'workbuddy-ai' } },+ IS_LINUX: false, CDP_PORT_HINT: 9233, AbortSignal,+ validCdpPort: (p) => p === 9233, readCdpPortFile: () => 9233,+ writeCdpPortFile: () => {}, cleanupForeignInjectedTargets: async () => {},+ fetch: async (url) => {+ requests.push(url);+ if (unavailable) throw new Error('ECONNREFUSED');+ return { json: async () => url.endsWith('/json/version') ? { Browser: 'WorkBuddy/5.8.3' } : targets };+ },+ WebSocketCtor: class {+ constructor() { throw new Error('No matching target should open a WebSocket'); }+ },+ log: () => {}, Date, lastInjectTs: 0, injectRetryTimer: null,+ buildInjectScript: () => '/* fixture widget */', updateDebug: () => {}, DAEMON_VERSION: 'test',+ setTimeout: (fn) => { fn(); return 1; }, clearTimeout: () => {},+ cdpSend: async (method, params) => {+ evaluations.push({ method, ...params });+ return { result: { value: { root: true, widget: true, url: cdp.targetUrl } } };+ },+ automationPanelSetInputActive: async () => {}, automationInputActive: false,+ wallpaperRotation: { status: () => ({ mode: 'fixed' }) },+ });+ for (const [start, end] of [+ ['async function findCdpEndpoint()', '\n/**'],+ ['function isWorkBuddyCdpTarget(', '\nasync function cleanupForeignInjectedTargets('],+ ['async function connectCdp()', '\nfunction '],+ ['async function injectWidget(', '\nfunction buildInjectScript()'],+ ]) {+ const begin = source.indexOf(start);+ const finish = source.indexOf(end, begin);+ assert.ok(begin >= 0 && finish > begin, start);+ vm.runInContext(source.slice(begin, finish), context);+ }+ return { context, cdp, evaluations, requests };+}++test('custom target 的发现、页面选择和完整注入使用相同归属规则', async () => {+ const h = harness({ targets: [other, own] });+ assert.equal(await h.context.findCdpEndpoint(), 9233);+ const selected = await h.context.getPageTarget(9233);+ assert.equal(selected.url, own.url);+ Object.assign(h.cdp, { connected: true, targetUrl: selected.url, targetTitle: selected.title });+ const result = await h.context.injectWidget('manual');+ assert.equal(result.mounted, true);+ assert.ok(h.evaluations.some((call) => call.expression === '/* fixture widget */'));+ assert.ok(h.requests.every((url) => url.startsWith('http://127.0.0.1:9233/')));+});++test('同名客户端来自其他目录时,发现和注入均拒绝,且诊断说明目标不匹配', async () => {+ const h = harness({ targets: [other] });+ assert.equal(await h.context.connectCdp(), false);+ assert.equal(h.cdp.endpointReachable, true);+ assert.match(h.cdp.error, /调试端口可达.*匹配/);+ Object.assign(h.cdp, { connected: true, targetUrl: other.url, targetTitle: other.title });+ await assert.rejects(h.context.injectWidget('manual'), /不属于当前 profile/);+ assert.equal(h.evaluations.length, 0, '不得清理或注入兄弟客户端页面');+});++test('普通 AI profile 仍拒绝国内版页面,即使 daemon 已绑定独立端口', async () => {+ const h = harness({ activeProfile: PROFILES['workbuddy-ai'] });+ assert.equal(await h.context.findCdpEndpoint(), null);+ Object.assign(h.cdp, { connected: true, targetUrl: own.url, targetTitle: own.title });+ await assert.rejects(h.context.injectWidget('manual'), /不属于当前 profile/);+ assert.equal(h.evaluations.length, 0);+});++test('真正不可达的端口保留调试模式提示,下一轮扫描清除旧的可达状态', async () => {+ const h = harness({ unavailable: true });+ h.cdp.endpointReachable = true;+ assert.equal(await h.context.connectCdp(), false);+ assert.equal(h.cdp.endpointReachable, false);+ assert.match(h.cdp.error, /未发现 CDP 端口/);+});diff --git a/test/cdp-targets.test.js b/test/cdp-targets.test.jsindex 21cfd19..a8227ca 100644--- a/test/cdp-targets.test.js+++ b/test/cdp-targets.test.js@@ -39,6 +39,41 @@ test('classifyTarget 识别 Windows 安装目录中的 app.asar 页面', () => {assert.equal(classifyTarget('file:///E:/WorkBuddy%20AI/resources/app.asar/renderer/index.html', 'WorkBuddy'), 'workbuddy-ai');});+test('Windows custom target 按所选安装目录认领页面,允许 AI profile 显式绑定国内版', () => {+ const profile = {+ ...PROFILES['workbuddy-ai'], customTarget: true,+ appPath: 'E:\\WorkBuddy\\WorkBuddy.exe',+ apiHost: 'https://www.workbuddy.cn', targetHints: ['workbuddy'],+ };+ const own = { type: 'page', url: WIN_CN_URL, title: 'WorkBuddy' };+ assert.equal(isTargetForProfile(own, profile), true);+ assert.equal(selectPageTarget([own], profile), own);+ for (const url of [WIN_AI_URL, 'file:///D:/WorkBuddy/resources/app.asar/renderer/index.html',+ 'file:///E:/WorkBuddy-old/resources/app.asar/renderer/index.html',+ 'file:///E:/WorkBuddy/../Other/resources/index.html',+ 'file://other-host/E:/WorkBuddy/resources/index.html']) {+ assert.equal(isTargetForProfile({ ...own, url }, profile), false, url);+ }+ // 未配置 custom target 时,绑定端口也不能覆盖官方路径归属。+ assert.equal(isTargetForProfile(own, PROFILES['workbuddy-ai']), false);+});++test('Windows custom target 正确处理编码、大小写、路径边界及非官方目录', () => {+ const profile = {+ ...PROFILES['workbuddy-ai'], customTarget: true,+ appPath: 'C:\\Company Apps\\企业版\\WorkBuddy.exe', targetHints: ['workbuddy'],+ };+ const own = { type: 'page', title: 'WorkBuddy',+ url: 'file:///c:/company%20apps/%E4%BC%81%E4%B8%9A%E7%89%88/resources/app.asar/renderer/index.html?locale=zh-CN' };+ assert.equal(isTargetForProfile(own, profile), true);+ for (const url of ['file:///C:/Other/resources/app.asar/renderer/index.html',+ 'file:///C:/Company%20Apps/企业版-backup/resources/index.html',+ 'file:///C:/Company%20Apps/%ZZ/resources/index.html',+ 'file:///C:/Company%20Apps/企业版/%2e%2e/Other/index.html']) {+ assert.equal(isTargetForProfile({ ...own, url }, profile), false, url);+ }+});+test('classifyTarget 依据登录域名识别国际版/国内版', () => {assert.equal(classifyTarget('https://www.workbuddy.ai/profile/plans-usage', ''), 'workbuddy-ai');assert.equal(classifyTarget('https://www.workbuddy.cn/profile/plans-usage', ''), 'workbuddy-cn');diff --git a/test/client-debug-relaunch.test.js b/test/client-debug-relaunch.test.jsindex 8b7cace..a7cda74 100644--- a/test/client-debug-relaunch.test.js+++ b/test/client-debug-relaunch.test.js@@ -90,6 +90,17 @@ test('恢复后(CDP 连上)标记被清除', () => {assert.equal(h.state().consecutiveMiss, 0);});+test('CDP 端口可达但页面不匹配时,不提示重启且清除历史标记', () => {+ const h = harness();+ for (let i = 0; i < 3; i++) h.update({ cdpConnected: false, clientRunning: true });+ assert.equal(h.state().needsDebugRelaunch, true);+ for (let i = 0; i < 5; i++) {+ h.update({ cdpConnected: false, cdpReachable: true, clientRunning: true });+ }+ assert.equal(h.state().consecutiveMiss, 0);+ assert.equal(h.state().needsDebugRelaunch, false);+});+test('一键恢复先走安全退出,再启动带 CDP 的客户端', () => {const start = source.indexOf("p === '/api/client/relaunch'");assert.ok(start >= 0);diff --git a/test/client-launch-settings.test.js b/test/client-launch-settings.test.jsnew file mode 100644index 0000000..3293c21--- /dev/null+++ b/test/client-launch-settings.test.js@@ -0,0 +1,130 @@+'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 { EventEmitter } = require('node:events');+const { readClientLaunchSettings, setClientLaunchSettings, getClientLaunchArgs } = require('../scripts/client-launch-settings.js');+const { getWorkBuddyLaunchEnv } = require('../scripts/workbuddy-launch-env.js');+const read = name => fs.readFileSync(path.join(__dirname, '../scripts', name), 'utf8');+const expectedFlags = ['--disable-gpu', '--use-gl=angle', '--use-angle=swiftshader-webgl', '--enable-unsafe-swiftshader'];+function fixture(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-gpu-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ return dir;+}++test('software rendering is opt-in, persistent and reversible without accepting arbitrary flags', t => {+ const dir = fixture(t);+ assert.deepEqual(readClientLaunchSettings(dir, 'workbuddy-ai', 'win32'), { supported: true, softwareRendering: false });+ assert.deepEqual(getClientLaunchArgs(dir, 'workbuddy-ai', 'win32'), []);+ setClientLaunchSettings(dir, 'workbuddy-ai', { softwareRendering: true, args: ['--no-sandbox'] }, 'win32');+ assert.deepEqual(getClientLaunchArgs(dir, 'workbuddy-ai', 'win32'), expectedFlags);+ assert.doesNotMatch(fs.readFileSync(path.join(dir, 'client-launch-settings.json'), 'utf8'), /no-sandbox/);+ setClientLaunchSettings(dir, 'workbuddy-ai', { softwareRendering: false }, 'win32');+ assert.deepEqual(getClientLaunchArgs(dir, 'workbuddy-ai', 'win32'), []);+ for (const value of ['true', 1, null, undefined]) {+ assert.throws(() => setClientLaunchSettings(dir, 'workbuddy-ai', { softwareRendering: value }, 'win32'), /布尔/);+ }+ fs.writeFileSync(path.join(dir, 'client-launch-settings.json'), '{broken');+ assert.deepEqual(getClientLaunchArgs(dir, 'workbuddy-ai', 'win32'), []);+ fs.writeFileSync(path.join(dir, 'client-launch-settings.json'), '{"softwareRendering":"false"}');+ assert.deepEqual(getClientLaunchArgs(dir, 'workbuddy-ai', 'win32'), []);+});++test('Windows AI settings never affect another profile or platform', t => {+ const dir = fixture(t);+ setClientLaunchSettings(dir, 'workbuddy-ai', { softwareRendering: true }, 'win32');+ for (const [id, platform] of [['workbuddy-cn', 'win32'], ['codebuddy-cn', 'win32'], ['workbuddy-ai', 'darwin'], ['workbuddy-ai', 'linux']]) {+ assert.deepEqual(readClientLaunchSettings(dir, id, platform), { supported: false, softwareRendering: false });+ assert.deepEqual(getClientLaunchArgs(dir, id, platform), []);+ assert.throws(() => setClientLaunchSettings(dir, id, { softwareRendering: true }, platform), /不支持/);+ }+});++test('normal Windows startup and daemon relaunch both apply the persisted flags with CDP intact', async t => {+ const dir = fixture(t);+ setClientLaunchSettings(dir, 'workbuddy-ai', { softwareRendering: true }, 'win32');+ const launches = [];+ const ctx = {+ PROFILE: { id: 'workbuddy-ai', dataRoot: path.join(dir, '.workbuddy-ai'), cdp: { mode: 'environment' } }, DATA_DIR: dir, CDP_PORT: 9223,+ process: { platform: 'win32', env: {} }, IS_WIN: true, IS_LINUX: false, path,+ getClientLaunchArgs, getWorkBuddyLaunchEnv, log() {}, selectCdpPort: async () => 9223,+ resolveWorkBuddyBinary: () => 'C:\\WorkBuddyAI.exe', sleep: async () => {}, restoreWorkBuddyWindow: async () => {},+ spawn: (command, args, options) => {+ launches.push({ command, args: Array.from(args), options });+ const child = new EventEmitter(); child.pid = 123; child.unref = () => {};+ queueMicrotask(() => child.emit('spawn'));+ return child;+ },+ };+ const launcher = read('win-launcher.js'), daemon = read('daemon.js');+ vm.runInNewContext(launcher.slice(launcher.indexOf('function launchWorkBuddy(wb)'), launcher.indexOf('\nasync function waitForWorkBuddyCdp')), ctx);+ const start = daemon.indexOf('function relaunchWorkBuddy()');+ vm.runInNewContext(daemon.slice(start, daemon.indexOf('\n/**', start)), ctx);+ for (const environmentMode of [true, false]) {+ ctx.PROFILE.cdp.mode = environmentMode ? 'environment' : 'argument';+ ctx.launchWorkBuddy('C:\\WorkBuddyAI.exe');+ await ctx.relaunchWorkBuddy();+ for (const launch of launches.splice(0)) {+ assert.deepEqual(launch.args, [...(environmentMode ? [] : ['--remote-debugging-port=9223']), ...expectedFlags]);+ if (environmentMode) assert.equal(launch.options.env.WORKBUDDY_REMOTE_DEBUGGING_PORT, '9223');+ }+ }+});++test('local settings API validates writes and reports unsupported clients', async t => {+ const dir = fixture(t);+ const source = read('daemon.js');+ const start = source.indexOf(" if (req.method === 'GET' && p === '/api/client-launch-settings')");+ const end = source.indexOf(" // 诊断:保存一份", start);+ assert.ok(start >= 0 && end > start);+ const handler = new Function('req', 'p', 'res', 'PROFILE', 'DATA_DIR', 'process', 'readBody', 'json',+ 'readClientLaunchSettings', 'setClientLaunchSettings', source.slice(start, end));+ const call = (method, body, profile = 'workbuddy-ai', platform = 'win32') => handler(+ { method }, '/api/client-launch-settings', {}, { id: profile }, dir, { platform }, async () => body,+ (_res, status, data) => ({ status, data }), readClientLaunchSettings, setClientLaunchSettings);+ assert.equal((await call('GET')).data.softwareRendering, false);+ assert.equal((await call('POST', { softwareRendering: true })).data.softwareRendering, true);+ assert.equal((await call('GET')).data.softwareRendering, true);+ assert.equal((await call('POST', { softwareRendering: 'true' })).status, 400);+ assert.equal((await call('POST', { softwareRendering: true }, 'workbuddy-cn')).status, 400);+ assert.equal((await call('GET', null, 'workbuddy-ai', 'darwin')).data.supported, false);+});++test('rendering switch waits for settings, persists changes and rolls back a failed save', async () => {+ const source = read('inject.js');+ const start = source.indexOf(' function wireClientLaunchSettings()');+ const end = source.indexOf(' function wireTelemetrySettings()', start);+ const events = {}, status = { textContent: '' };+ const toggle = { disabled: true, checked: false, addEventListener: (event, fn) => { events[event] = fn; } };+ let fail = false, reads = 0, saved;+ const ctx = {+ aboutPane: { querySelector: selector => selector === '#wbs-software-rendering' ? toggle : status },+ api: async (_path, options) => {+ if (!options) { reads++; return { supported: true, softwareRendering: true }; }+ if (fail) throw new Error('write failed');+ saved = JSON.parse(options.body).softwareRendering;+ return { supported: true, softwareRendering: saved };+ },+ };+ vm.runInNewContext(source.slice(start, end), ctx);+ ctx.wireClientLaunchSettings();+ assert.equal(toggle.disabled, true);+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(reads, 1);+ assert.equal(toggle.checked, true);+ assert.equal(toggle.disabled, false);+ toggle.checked = false; events.change();+ assert.equal(toggle.disabled, true);+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(saved, false);+ assert.match(status.textContent, /下次/);+ fail = true; toggle.checked = true; events.change();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(toggle.checked, false);+ assert.equal(toggle.disabled, false);+ assert.match(status.textContent, /保存失败/);+});diff --git a/test/codebuddy-compat.test.js b/test/codebuddy-compat.test.jsindex fe01e79..f059323 100644--- a/test/codebuddy-compat.test.js+++ b/test/codebuddy-compat.test.js@@ -14,13 +14,28 @@ test('CodeBuddy keeps accounts, sessions and models but disables composer enhancfor(const key of ['accounts','sessions','models','theme']) assert.equal(c[key],true);assert.equal(c.themeTakeover,false);assert.equal(c.enhance,false);assert.equal(c.nativeComposer,true);assert.equal(c.stashPrompt,false);assert.equal(c.sessionsReadOnly,undefined);assert.equal(c.modelsReadOnly,undefined);- assert.equal(c.apiTransport,'cdp');assert.equal(c.panelAppearance,'light');assert.equal(c.robotStyle,'black');+ assert.equal(c.apiTransport,'cdp');assert.equal(c.panelAppearance,'native');assert.equal(c.robotStyle,'black');}assert.doesNotMatch(inject,/WBS_CODEBUDDY_BOOTSTRAP|CAPS\.sessionsReadOnly|CAPS\.modelsReadOnly/);assert.match(inject,/CAPS\.enhance === false/);assert.match(inject,/themeSwitch\.disabled = true/);assert.match(inject,/window\.__wbsApiFetch\(path, request, WBS_API_TOKEN\)/);});+test('CodeBuddy panel follows the official dark theme palette instead of forcing light colors', () => {+ assert.match(inject, /if \(CAPS\.panelAppearance === 'light'\) root\.classList\.add\('wbs-panel-light'\)/);+ assert.match(inject, /html\.cb-dark,html\[data-theme="dark"\],body\[data-vscode-theme-name\*="dark" i\],body\[data-vscode-theme-name\*="night" i\]/);+ assert.match(inject, /\.wbs-root\[data-wbs-profile="codebuddy-cn"\]/);+ assert.match(inject, /--wb-bg-primary:#0a0a0c/);+ assert.match(inject, /--wb-color-text-primary:#e6e6e9/);+ assert.match(inject, /body\[data-vscode-theme-name\*="night" i\].*\.wbs-modal/);+});+test('CodeBuddy growth popover gives nested cards the dark palette too', () => {+ assert.match(inject, /if \(CAPS\.nativeComposer\) node\.setAttribute\('data-wbs-profile', PROFILE_ID\)/);+ assert.match(inject, /\.wbs-status-popover\[data-wbs-profile\^="codebuddy-"\][^']*--wb-bg-secondary:#131316/);+ assert.match(inject, /\.wbs-status-popover\[data-wbs-profile\^="codebuddy-"\][^']*--wb-color-text-primary:#e6e6e9/);+ assert.match(inject, /wbs-growth-task-section/);+ assert.match(inject, /wbs-daily-detail/);+});test('CodeBuddy injection compiles with all shared pages and the CSP-compatible bridge',()=>{const start=daemon.indexOf('function buildInjectScript()');const end=daemon.indexOf('function injectWidgetManual()',start);diff --git a/test/codebuddy-ide-recovery.test.js b/test/codebuddy-ide-recovery.test.jsindex 25a3109..724a7e7 100644--- a/test/codebuddy-ide-recovery.test.js+++ b/test/codebuddy-ide-recovery.test.js@@ -92,7 +92,7 @@ test('manual copy/migrate handlers reload the IDE workbench for the current acco// 当前账号都刷新;自动复制路径不得触发 reload(切号 session-change 已清缓存)。const copyBlock = source.slice(source.indexOf("p === '/api/sessions/copy'"), source.indexOf("p === '/api/sessions/migrate'"));const migrateBlock = source.slice(source.indexOf("p === '/api/sessions/migrate'"), source.indexOf("删除会话(真实删除)"));- assert.match(copyBlock, /copied > 0 && targetUid === String\(\(currentAccount\(\) \|\| \{\}\)\.uid \|\| ''\)\) \{\s*\n\s*reloadIdeWorkbenchWindows\('sessions-copy'\)/);+ assert.match(copyBlock, /copied > 0 && targetUid === String\(\(currentAccount\(\) \|\| \{\}\)\.uid \|\| ''\)\) \{[^}]*reloadIdeWorkbenchWindows\('sessions-copy'\)/);assert.match(migrateBlock, /reloadIdeWorkbenchWindows\('sessions-migrate'\)/);// 自动复制(startAutoCopyJob 路径)不得调用 reloadconst autoCopyStart = source.indexOf('function startAutoCopyJob');diff --git a/test/enterprise-target.test.js b/test/enterprise-target.test.jsindex 50d2697..6572982 100644--- a/test/enterprise-target.test.js+++ b/test/enterprise-target.test.js@@ -167,6 +167,76 @@ test('macOS target configuration accepts non-exe process names', () => {assert.deepEqual(target.cdp, { mode: 'argument', port: 9222 });});+test('macOS enterprise targets discover the client-specific auth file and API host', () => {+ const root = tempDir();+ try {+ const home = path.join(root, 'Users', 'tester');+ const authDir = path.join(home, 'Library', 'Application Support', 'CodeBuddyExtension', 'Data', 'Public', 'auth');+ fs.mkdirSync(authDir, { recursive: true });+ fs.writeFileSync(path.join(authDir, 'workbuddy-desktop.info'), JSON.stringify({+ account: { uid: 'old' }, auth: { domain: 'https://www.codebuddy.cn' },+ }));+ const enterpriseAuth = path.join(authDir, 'workbuddy-desktop-acme.info');+ fs.writeFileSync(enterpriseAuth, JSON.stringify({+ account: { uid: 'current' }, auth: { domain: 'https://acme.copilot.qq.com' },+ }));++ const target = buildTargetFromBinary({+ binary: '/Applications/WorkBuddy Acme.app/Contents/MacOS/Electron',+ profileId: 'workbuddy-cn',+ platform: 'darwin',+ home,+ });+ assert.equal(target.authFile, enterpriseAuth);+ assert.equal(target.apiHost, 'https://acme.copilot.qq.com');+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++test('macOS enterprise auth discovery matches the app suffix when multiple files exist', () => {+ const root = tempDir();+ try {+ const home = path.join(root, 'Users', 'tester');+ const authDir = path.join(home, 'Library', 'Application Support', 'CodeBuddyExtension', 'Data', 'Public', 'auth');+ fs.mkdirSync(authDir, { recursive: true });+ fs.writeFileSync(path.join(authDir, 'workbuddy-desktop-acme.info'), JSON.stringify({+ account: { uid: 'acme' }, auth: { domain: 'https://acme.example.com' },+ }));+ fs.writeFileSync(path.join(authDir, 'workbuddy-desktop-other.info'), JSON.stringify({+ account: { uid: 'other' }, auth: { domain: 'https://other.example.com' },+ }));+ const target = buildTargetFromBinary({+ binary: '/Applications/WorkBuddy Acme.app/Contents/MacOS/Electron',+ profileId: 'workbuddy-cn', platform: 'darwin', home,+ });+ assert.equal(target.authFile, path.join(authDir, 'workbuddy-desktop-acme.info'));+ assert.equal(target.apiHost, 'https://acme.example.com');+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++test('macOS official app keeps the canonical auth filename', () => {+ const root = tempDir();+ try {+ const home = path.join(root, 'Users', 'tester');+ const authDir = path.join(home, 'Library', 'Application Support', 'CodeBuddyExtension', 'Data', 'Public', 'auth');+ fs.mkdirSync(authDir, { recursive: true });+ const canonical = path.join(authDir, 'workbuddy-desktop.info');+ fs.writeFileSync(canonical, '{}');+ fs.writeFileSync(path.join(authDir, 'workbuddy-desktop-acme.info'), '{}');+ const target = buildTargetFromBinary({+ binary: '/Applications/WorkBuddy.app/Contents/MacOS/Electron',+ profileId: 'workbuddy-cn', platform: 'darwin', home,+ });+ assert.equal(target.authFile, canonical);+ assert.equal(target.apiHost, 'https://www.codebuddy.cn');+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});+test('target resolver accepts launcher-style equals arguments', () => {const dataDir = tempDir();const script = path.join(__dirname, '..', 'scripts', 'workbuddy-target.js');diff --git a/test/growth-rings-ui.test.js b/test/growth-rings-ui.test.jsindex 89ebd51..7ebf3de 100644--- a/test/growth-rings-ui.test.js+++ b/test/growth-rings-ui.test.js@@ -228,6 +228,29 @@ test('growth actions open the official center and never write through local grow}});+test('CodeBuddy CN growth actions use the operable WorkBuddy growth site', async () => {+ const helperStart = inject.indexOf(' var OFFICIAL_GROWTH_TARGET');+ const helperEnd = inject.indexOf(' function confirmCurrentGrowthAccount', helperStart);+ assert.ok(helperStart > 0 && helperEnd > helperStart);+ const source = inject.slice(helperStart, helperEnd);+ const calls = [], listeners = {};+ const adapter = {+ on(event, handler) { listeners[event] = handler; return () => { delete listeners[event]; }; },+ emit(event) { assert.equal(event, 'request-device-auth-code'); setImmediate(() => listeners['request-device-auth-code-result']({ success: true, deviceCode: 'device-code-cn' })); },+ openExternal(url) { calls.push(url); return Promise.resolve(); },+ };+ const open = Function('api', 'toast', 'root', 'findWbsAdapter', 'window', 'PROFILE_ID', source + '\nreturn openOfficialGrowthCenter;')(+ () => Promise.resolve(), () => {}, {}, () => adapter, { __wbsAdapter: adapter }, 'codebuddy-cn'+ );+ await open();+ assert.equal(calls.length, 1);+ const opened = new URL(calls[0]);+ assert.equal(opened.origin, 'https://www.workbuddy.cn');+ assert.equal(opened.pathname, '/console/client-login');+ assert.equal(opened.searchParams.get('code'), 'device-code-cn');+ assert.match(opened.searchParams.get('target'), /^\/profile\/growth-center\?fromSource=gwzcw\.15291246/);+});+test('modern adapter shim forwards the official login event and external-open methods', () => {const start = inject.indexOf(' function findWbsAdapter()');const end = inject.indexOf(' function bootstrapModernQueueBridge()', start);diff --git a/test/message-navigation-removal.test.js b/test/message-navigation-removal.test.jsnew file mode 100644index 0000000..90fbf6d--- /dev/null+++ b/test/message-navigation-removal.test.js@@ -0,0 +1,38 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');++const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');++function harness(nodes) {+ const document = {+ querySelectorAll(selector) {+ assert.equal(selector, 'aside.conversation-history-navigation');+ return nodes;+ },+ };+ const start = source.indexOf('function removeOfficialConversationHistoryNavigation(');+ const end = source.indexOf('\n // 会话消息导航:', start);+ assert.ok(start >= 0 && end > start, 'official navigation cleanup helper missing');+ const context = { document };+ vm.runInNewContext(source.slice(start, end), context);+ return context.removeOfficialConversationHistoryNavigation;+}++test('message index cleanup removes every official history navigation regardless of parent path', () => {+ const removed = [];+ const nodes = [{ remove: () => removed.push(1) }, { remove: () => removed.push(1) }];+ const clean = harness(nodes);+ assert.equal(clean(false), 0);+ assert.equal(removed.length, 0);+ assert.equal(clean(true), 2);+ assert.equal(removed.length, 2);+});++test('message index cleanup is wired to enable and DOM rescan paths', () => {+ assert.match(source, /function setEnabled\(enabled\)[\s\S]*?removeOfficialConversationHistoryNavigation\(true\)/);+ assert.match(source, /function onDomChange\(\)[\s\S]*?removeOfficialConversationHistoryNavigation\(sessState\.messageNav\)/);+});diff --git a/test/model-rate-limit.test.js b/test/model-rate-limit.test.jsnew file mode 100644index 0000000..bd0acc6--- /dev/null+++ b/test/model-rate-limit.test.js@@ -0,0 +1,140 @@+'use strict';++const assert = require('node:assert/strict');+const test = require('node:test');+const fs = require('node:fs');+const vm = require('node:vm');+const inject = require('../scripts/inject.js');+const source = fs.readFileSync(require.resolve('../scripts/inject.js'), 'utf8');++function capError(overrides = {}) {+ return {+ code: '6004', requestModelId: 'deepseek-v4.1-flash',+ terminal: { bizCode: 6004, details: 'Reset at 2026-10-16 17:21:48 (UTC+8)' },+ ...overrides,+ };+}++test('official terminal cap details supply the reset time even with an empty outer code', () => {+ for (const code of [undefined, null, '', ' ', 0, 500, '6004']) {+ const result = inject.normalizeAutoContinueError(capError({ code, message: 'Request failed' }));+ assert.equal(result.code, 6004);+ assert.equal(result.rateLimited, true);+ assert.equal(result.resetAt, Date.parse('2026-10-16T17:21:48+08:00'));+ assert.equal('message' in result, false, 'never retain provider error text');+ }+});++test('cap reset wall clock uses UTC+8 on every client timezone', () => {+ const result = inject.normalizeAutoContinueError(capError({+ message: 'Reset at 2026-10-16T17:21:48', terminal: { bizCode: 6004 },+ }));+ assert.equal(result.resetAt, Date.parse('2026-10-16T17:21:48+08:00'));+});++test('cap statistics subscribe without auto-continue, catch terminal warnings and clean up', () => {+ const listeners = new Set();+ let state = { model: 'deepseek-v4.1-flash' };+ let controllers = [{ conversationId: 'synthetic-conversation', sessionStore: {+ getState: () => state,+ subscribe: fn => { listeners.add(fn); return () => listeners.delete(fn); },+ } }];+ const records = [];+ let tick;+ let cleared = false;+ const observer = inject.createModelRateLimitObserver({+ discover: () => controllers,+ record: value => records.push(value),+ setInterval: fn => { tick = fn; return 123; },+ clearInterval: id => { assert.equal(id, 123); cleared = true; },+ });+ assert.equal(listeners.size, 1);+ // The normal reply has already finished. A short-lived terminal warning+ // follows a separate generic error and must be seen before the next scan.+ state = { ...state, error: { code: 'OTHER' }, warning: capError() };+ for (const fn of listeners) fn();+ state = { model: 'deepseek-v4.1-flash' };+ assert.equal(records.length, 1);+ assert.equal(records[0].errorCode, 6004);+ assert.equal(records[0].errorRequestModelId, 'deepseek-v4.1-flash');+ assert.equal(records[0].errorResetAt, Date.parse('2026-10-16T17:21:48+08:00'));+ assert.equal('message' in records[0], false);+ tick();+ assert.equal(records.length, 2, 'retry the sanitized cap after a transient error clears');+ controllers = [];+ tick();+ assert.equal(listeners.size, 0, 'unmounted controllers are unsubscribed');+ observer.destroy();+ assert.equal(cleared, true);+ tick();+ assert.equal(records.length, 2, 'disposed timers cannot report');+});++function reporterContext(api) {+ const start = source.indexOf(' function acRecordModelRateLimit(');+ const end = source.indexOf('\n function acControllerSnapshot(', start);+ const context = { api, acRateLimitRecorded: Object.create(null), acCurrentUidPromise: null,+ window: { dispatchEvent() {} }, Event: function () {} };+ vm.createContext(context);+ vm.runInContext(source.slice(start, end), context);+ return context;+}+const flush = () => new Promise(resolve => setImmediate(resolve));++test('failed cap writes and current-account lookups are retried; successful writes deduplicate', async () => {+ for (const failedRoute of ['/api/current', '/api/model-rate-limit']) {+ let fail = true;+ let attempts = 0;+ let posts = 0;+ const context = reporterContext(async route => {+ if (route === failedRoute) { attempts++; if (fail) throw Error('temporary local failure'); }+ if (route === '/api/current') return { uid: 'synthetic-user' };+ posts++;+ return { ok: true };+ });+ const snapshot = { conversationId: 'synthetic-conversation', assistantId: 'synthetic-assistant',+ rateLimited: true, errorCode: 6004, errorRequestModelId: 'deepseek-v4.1-flash', errorResetAt: 1792142508000 };+ context.acRecordModelRateLimit(snapshot);+ context.acRecordModelRateLimit(snapshot);+ await flush();+ assert.equal(attempts, 1, 'concurrent callbacks share the pending write');+ fail = false;+ context.acRecordModelRateLimit(snapshot);+ await flush();+ assert.equal(attempts, 2, failedRoute + ' retries after a failed attempt');+ assert.equal(posts, 1);+ context.acRecordModelRateLimit(snapshot);+ await flush();+ assert.equal(posts, 1, 'only a successful write becomes permanently deduplicated');+ }+});++test('statistics never submit a generic HTTP 429 as a business cap 6004', async () => {+ let calls = 0;+ const context = reporterContext(async () => { calls++; return {}; });+ for (const errorCode of [null, 429, 14018]) {+ context.acRecordModelRateLimit({ rateLimited: true, errorCode });+ }+ await flush();+ assert.equal(calls, 0);+});++test('cap observer starts independently and is disposed on reinjection', () => {+ assert.ok(/createModelRateLimitObserver\(\{[\s\S]{0,600}record: acRecordModelRateLimit/.test(source));+ assert.ok(/registerDisposer\(function \(\) \{ modelRateLimitObserver\.destroy\(\); \}\)/.test(source));+});++test('renderer cap cleanup calls the native timer API with a valid receiver', () => {+ const start = source.indexOf(' var modelRateLimitObserver = createModelRateLimitObserver({');+ const end = source.indexOf('\n registerDisposer(', start);+ let options;+ let timerReceiver;+ const context = { CAPS: { accounts: false }, WBS_COMPAT: null,+ acRecordModelRateLimit() {}, setBuildInterval() {},+ createModelRateLimitObserver(value) { options = value; return {}; },+ clearInterval(id) { assert.equal(id, 123); timerReceiver = this; },+ };+ vm.runInNewContext(source.slice(start, end), context);+ options.clearInterval(123);+ assert.notEqual(timerReceiver, options, 'native clearInterval rejects the observer options as its receiver');+});diff --git a/test/official-automation-sync.test.js b/test/official-automation-sync.test.jsnew file mode 100644index 0000000..87b2f7c--- /dev/null+++ b/test/official-automation-sync.test.js@@ -0,0 +1,191 @@+'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 { createSessionDb } = require('../scripts/session-db');+const { createOfficialAutomationSync } = require('../scripts/official-automation-sync');++async function fixture(t, accounts = ['a', 'b', 'h']) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-official-sync-'));+ t.after(() => fs.rmSync(dataDir, { recursive: true, force: true }));+ const db = createSessionDb({ dbPath: path.join(dataDir, 'tasks.db') });+ // Real WorkBuddy constraints: the former mock accepted invalid NULL rrules+ // and did not execute UPDATEs, hiding both copy and rename regressions.+ await db.run(`CREATE TABLE automations (+ id TEXT PRIMARY KEY, name TEXT NOT NULL, prompt TEXT NOT NULL, status TEXT NOT NULL,+ schedule_type TEXT NOT NULL DEFAULT 'recurring', next_run_at INTEGER, last_run_at INTEGER,+ cwds TEXT NOT NULL DEFAULT '[]', rrule TEXT NOT NULL DEFAULT '', scheduled_at TEXT,+ valid_from TEXT, valid_until TEXT, model_id TEXT, model_is_thinking INTEGER NOT NULL DEFAULT 0,+ skills_json TEXT NOT NULL DEFAULT '[]', push_to_wechat INTEGER NOT NULL DEFAULT 0,+ push_to_wecom_bot INTEGER NOT NULL DEFAULT 0, owner_user_id TEXT,+ owner_status TEXT NOT NULL DEFAULT 'legacy_unassigned', owner_source TEXT, expert_id TEXT,+ expert_marketplace TEXT, connector_ids_json TEXT NOT NULL DEFAULT '[]', permission_mode TEXT,+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, deleted_at INTEGER,+ wecom_bot_source TEXT, context_window INTEGER, reasoning_effort TEXT, workspace_scope TEXT,+ wecom_bot_chat_id TEXT)`);+ const insert = async (id, owner, extra = {}) => {+ const row = { id, owner_user_id: owner, name: 'AI 信息汇总', prompt: 'fixture prompt',+ status: 'ACTIVE', rrule: 'FREQ=DAILY;BYHOUR=10', created_at: 1, updated_at: 1, ...extra };+ const columns = Object.keys(row);+ await db.run(`INSERT INTO automations (${columns.join(',')}) VALUES (${columns.map(() => '?').join(',')})`, Object.values(row));+ };+ const mappingFile = path.join(dataDir, 'official-automation-sync.json');+ const buildSync = (options = {}) => createOfficialAutomationSync({ dataDir, db, getAccountUids: () => accounts, ...options });+ const live = owner => db.all("SELECT * FROM automations WHERE owner_user_id = ? AND deleted_at IS NULL AND status <> 'ARCHIVED' ORDER BY name", [owner]);+ const names = async owner => (await live(owner)).map(r => r.name);+ return { db, insert, mappingFile, buildSync, live, names };+}++test('account round trip: A rename, B rename, back to A, all saved accounts converge without new IDs', async t => {+ const f = await fixture(t);+ await f.insert('a-original', 'a');+ await f.insert('h-once', 'h', { name: '111', schedule_type: 'once', rrule: '', scheduled_at: '2030-01-01T10:00:00Z' });+ let sync = f.buildSync();+ await sync('a', 'b');+ const ids = await f.db.all('SELECT id FROM automations ORDER BY id');+ await f.db.run('UPDATE automations SET name = ?, updated_at = ? WHERE id = ?', ['改名 A', 2, 'a-original']);+ await sync('a', 'b');+ for (const owner of ['a', 'b', 'h']) assert.deepEqual(await f.names(owner), ['111', '改名 A']);+ const bId = (await f.live('b')).find(r => r.name === '改名 A').id;+ await f.db.run('UPDATE automations SET name = ?, updated_at = ? WHERE id = ?', ['改名 B', 3, bId]);+ sync = f.buildSync(); // Daemon restart must keep the lineage and edit baseline.+ for (const [from, to] of [['b', 'a'], ['a', 'h'], ['h', 'b'], ['b', 'a']]) {+ await sync(from, to);+ for (const owner of ['a', 'b', 'h']) assert.deepEqual(await f.names(owner), ['111', '改名 B']);+ }+ assert.deepEqual(await f.db.all('SELECT id FROM automations ORDER BY id'), ids);+});++test('legacy mapping graph includes reverse/transitive edges and retires only proven duplicates', async t => {+ const f = await fixture(t);+ await f.insert('a-old', 'a', { updated_at: 1 });+ await f.insert('a-copy', 'a', { name: '最新名称', updated_at: 5 });+ await f.insert('b-copy', 'b', { name: '中间名称', updated_at: 3 });+ await f.insert('h-copy', 'h', { updated_at: 2 });+ await f.insert('h-unique', 'h', { name: '独有任务' });+ fs.writeFileSync(f.mappingFile, JSON.stringify({+ 'a:a-old:b': { targetAutomationId: 'b-copy' },+ 'h:h-copy:b': { targetAutomationId: 'b-copy' },+ 'h:h-copy:a': { targetAutomationId: 'a-copy' },+ }));+ const sync = f.buildSync();+ for (const pair of [['b', 'h'], ['h', 'a'], ['a', 'b']]) {+ await sync(...pair);+ for (const owner of ['a', 'b', 'h']) assert.deepEqual(await f.names(owner), ['最新名称', '独有任务']);+ }+ const retired = (await f.db.all('SELECT deleted_at FROM automations WHERE id = ?', ['a-old']))[0];+ assert.ok(retired.deleted_at, 'duplicate is recoverable, not physically deleted');+});++test('execution bookkeeping cannot overwrite a rename with a stale definition', async t => {+ const f = await fixture(t);+ await f.insert('a', 'a', { next_run_at: 100, last_run_at: 50 });+ const sync = f.buildSync();+ await sync('a', 'b');+ await f.db.run('UPDATE automations SET name = ?, updated_at = ? WHERE id = ?', ['新名称', 10, 'a']);+ await f.db.run('UPDATE automations SET updated_at = ?, last_run_at = ?, next_run_at = ? WHERE owner_user_id = ?', [20, 200, 300, 'b']);+ await sync('a', 'b');+ assert.deepEqual(await f.names('b'), ['新名称']);+ const b = (await f.live('b'))[0];+ assert.equal(b.last_run_at, 200);+ assert.equal(b.next_run_at, 300);+});++test('same-timestamp edits propagate; paused state and schedule changes propagate too', async t => {+ const f = await fixture(t);+ await f.insert('a', 'a');+ const sync = f.buildSync();+ await sync('a', 'b');+ await f.db.run('UPDATE automations SET name = ?, status = ?, rrule = ?, next_run_at = ? WHERE owner_user_id = ?', ['同毫秒改名', 'PAUSED', 'FREQ=WEEKLY', 888, 'b']);+ await sync('b', 'a');+ for (const owner of ['a', 'b', 'h']) {+ const row = (await f.live(owner))[0];+ assert.equal(row.name, '同毫秒改名');+ assert.equal(row.status, 'PAUSED');+ assert.equal(row.rrule, 'FREQ=WEEKLY');+ assert.equal(row.next_run_at, 888);+ }+});++test('adoption is one-to-one; intentional identical tasks and different once schedules survive', async t => {+ const f = await fixture(t);+ await f.insert('a1', 'a');+ await f.insert('a2', 'a');+ await f.insert('b1', 'b');+ await f.insert('once-a', 'a', { name: 'once', schedule_type: 'once', rrule: '', scheduled_at: '2030-01-01' });+ await f.insert('once-b', 'b', { name: 'once', schedule_type: 'once', rrule: '', scheduled_at: '2030-01-02' });+ const sync = f.buildSync();+ await sync('a', 'b');+ await sync('b', 'h');+ for (const owner of ['a', 'b', 'h']) assert.equal((await f.live(owner)).length, 4);+});++test('deletion of a mapped task propagates and never resurrects on reverse switching', async t => {+ const f = await fixture(t);+ await f.insert('a', 'a');+ await f.insert('already-deleted', 'a', { deleted_at: 2, updated_at: 2 });+ const sync = f.buildSync();+ await sync('a', 'b');+ assert.equal((await f.live('b')).length, 1);+ await f.db.run('UPDATE automations SET deleted_at = ?, updated_at = ? WHERE owner_user_id = ?', [10, 10, 'b']);+ for (const pair of [['b', 'h'], ['h', 'a'], ['a', 'b']]) await sync(...pair);+ for (const owner of ['a', 'b', 'h']) assert.deepEqual(await f.names(owner), []);+});++test('mapping persistence failure does not leave untracked new copies in SQLite', async t => {+ const f = await fixture(t);+ await f.insert('a', 'a');+ fs.mkdirSync(f.mappingFile);+ await assert.rejects(f.buildSync()('a', 'b'));+ assert.deepEqual(await f.names('b'), []);+});++test('invalid or identical accounts do not write the database', async t => {+ const f = await fixture(t);+ await f.insert('a', 'a');+ const sync = f.buildSync();+ await sync('../bad', 'b');+ await sync('a', 'a');+ assert.deepEqual(await f.names('b'), []);+});++test('failed SQL transaction is retried with the reserved lineage; concurrent calls do not duplicate', async t => {+ const f = await fixture(t);+ await f.insert('a', 'a');+ let failOnce = true;+ const sync = f.buildSync({ db: { ...f.db, async transaction(statements) {+ if (failOnce) { failOnce = false; throw new Error('fixture busy'); }+ return f.db.transaction(statements);+ } } });+ await assert.rejects(sync('a', 'b'), /fixture busy/);+ await Promise.all([sync('a', 'b'), sync('a', 'h'), sync('h', 'b')]);+ for (const owner of ['a', 'b', 'h']) assert.equal((await f.live(owner)).length, 1);+});++test('historical NULL optional settings use official defaults when copied', async t => {+ const f = await fixture(t);+ await f.insert('a', 'a', { schedule_type: 'once', rrule: '', scheduled_at: '2030-01-01' });+ const sync = f.buildSync({ db: { ...f.db, async all(sql, params) {+ return (await f.db.all(sql, params)).map(row => ({ ...row, rrule: null, skills_json: null }));+ } } });+ await sync('a', 'b');+ const copy = (await f.live('b'))[0];+ assert.equal(copy.rrule, '');+ assert.equal(copy.skills_json, '[]');+});++test('corrupt lineage records fail closed and accounts outside the saved set stay untouched', async t => {+ const f = await fixture(t);+ await f.insert('a', 'a');+ await f.insert('outside', 'outside', { name: '不参与同步' });+ fs.writeFileSync(f.mappingFile, '{broken');+ await assert.rejects(f.buildSync()('a', 'b'), /同步记录无法读取/);+ assert.deepEqual(await f.names('b'), []);+ fs.unlinkSync(f.mappingFile);+ await f.buildSync()('a', 'b');+ assert.deepEqual(await f.names('outside'), ['不参与同步']);+ for (const owner of ['a', 'b', 'h']) assert.deepEqual(await f.names(owner), ['AI 信息汇总']);+});diff --git a/test/panel-theme-controls.test.js b/test/panel-theme-controls.test.jsindex 393dafb..99f493d 100644--- a/test/panel-theme-controls.test.js+++ b/test/panel-theme-controls.test.js@@ -44,9 +44,9 @@ test('theme choices do not activate official data-theme scopes and robot radiosassert.match(pane, /value="default"/);});-test('theme pane restores five radio choices and enabling takeover restores the saved theme', () => {+test('theme pane restores six radio choices and enabling takeover restores the saved theme', () => {const pane = section('function buildThemePane()', 'function buildEnhancePane()');- for (const id of ['default', 'dark', 'eye-care', 'cyber-purple', 'nebula']) {+ for (const id of ['system', 'default', 'dark', 'eye-care', 'cyber-purple', 'nebula']) {assert.ok(pane.includes('name="wbs-theme" value="' + id + '"'));}assert.match(pane, /<div class="wbs-pcard-title">接管主题<\/div>/);@@ -153,6 +153,9 @@ test('glass composer triggers receive an inline transparent background after teaassert.match(source, /node\.style\.setProperty\('background', 'transparent', 'important'\)/);assert.match(source, /node\.style\.setProperty\('background-color', 'transparent', 'important'\)/);assert.match(source, /\.cr-context-usage-tooltip-trigger/);+ const triggerSync = section('function syncGlassComposerTriggerBackgrounds()', 'function onInputSync()');+ assert.ok(triggerSync.includes('.cr-input-toolbar__right > span.cr-voice-trigger-wrap > span.cr-voice-trigger-tooltip'),+ 'nested voice trigger receives the inline override after remounts');assert.match(source, /glassThemeObserver\.observe\(document\.documentElement/);assert.match(source, /\.wbs-account-note-footer \.primary:disabled\{background:rgba\(255,255,255,\.78\) !important[^}]*color:#34343c !important/);});@@ -260,6 +263,7 @@ for (const trigger of ['switch', 'settings refresh']) test('frosted wallpaper stconst requests = [];let resolveWallpapers;const context = {+ alive: true, registerDisposer() {}, loadWallpaperRotation() {},CAPS: {}, currentThemeId: 'nebula', sessState: {}, enhancePane: null, conversationUsageEnabled: false,themePane: { querySelector: selector => nodes[selector] || null, querySelectorAll: () => [card] },root: { querySelector: selector => nodes[selector] || null },@@ -275,7 +279,7 @@ for (const trigger of ['switch', 'settings refresh']) test('frosted wallpaper st};vm.runInNewContext(section('function applySessionModule(', ' /** 增强页快捷短语列表') +section('function syncWallpaperCardVisibility(', ' // 主题 pane 事件绑定') +- section('function loadWallpapers(force)', ' function setOpen('), context);+ section(' var wallpaperPreviewUrls =', ' function setOpen('), context);context.applySessionModule({ ok: true, themeTakeoverEnabled: false });context.syncWallpaperCardVisibility('nebula'); // First visit with takeover off.assert.equal(requests.length, 0);@@ -315,12 +319,16 @@ test('primary actions use native button tokens in every interaction state', () =assert.match(glass, /\.wbs-status-popover/);});-for (const nativeComposer of [false, true]) test('theme controls are rendered only for WorkBuddy: nativeComposer=' + nativeComposer, () => {+for (const nativeComposer of [false, true]) test('theme controls match the client theme capability: nativeComposer=' + nativeComposer, () => {const context = { CAPS: {nativeComposer}, WBS_BRAND: 'WorkDaddy', themePane: {dataset:{}}, wireThemePane() {}, applyAvatar() {} };vm.runInNewContext(section('function buildThemePane()', ' // 增强 pane'), context);context.buildThemePane();- assert.equal((context.themePane.innerHTML.match(/name="wbs-theme"/g) || []).length, nativeComposer ? 0 : 5);+ assert.equal((context.themePane.innerHTML.match(/name="wbs-theme"/g) || []).length, nativeComposer ? 3 : 6);assert.equal(context.themePane.innerHTML.includes('接管主题'), !nativeComposer);+ if (nativeComposer) {+ assert.match(context.themePane.innerHTML, /id="wbs-native-theme-card"/);+ assert.doesNotMatch(context.themePane.innerHTML, /value="(?:eye-care|cyber-purple|nebula)"/);+ }});test('rapid theme selections ignore stale failures and disabled takeover prevents writes', async () => {@@ -343,15 +351,106 @@ test('rapid theme selections ignore stale failures and disabled takeover preventassert.equal(requests.length, 2);});+test('CodeBuddy theme choices use native system/light/dark mode without takeover', async () => {+ const requests = [];+ const context = {+ CAPS: { nativeComposer: true, themeTakeover: false },+ sessState: { themeTakeover: false }, themePane: null, root: {},+ syncWallpaperCardVisibility() {}, toast() {},+ api: (route, options) => new Promise((resolve, reject) => requests.push({ route, options, resolve, reject })),+ };+ vm.runInNewContext(section(' var ALLOWED_THEMES =', ' // 页面主题由 daemon'), context);+ const pending = context.selectTheme('dark');+ assert.equal(requests.length, 1);+ assert.equal(JSON.parse(requests[0].options.body).nativeOnly, true);+ requests[0].resolve({ ok: true });+ await pending;+ await context.selectTheme('nebula');+ const system = context.selectTheme('system');+ assert.equal(requests.length, 2);+ assert.deepEqual(JSON.parse(requests[1].options.body), { id: 'system', nativeOnly: true });+ requests[1].resolve({ ok: true, resolved: 'default' }); await system;+ assert.equal(context.currentThemeId, 'system');+});++test('daemon accepts nativeOnly only for CodeBuddy official modes', () => {+ assert.match(daemon, /const nativeOnly = body\.nativeOnly === true && PROFILE\.capabilities\.nativeComposer/);+ assert.match(daemon, /const applyOptions = nativeOnly \? \{ nativeOnly: true \} : null/);+ assert.match(daemon, /applyOptions \? applyThemeByCdp\(id, applyOptions\) : applyThemeByCdp\(id\)/);+ assert.match(daemon, /if \(nativeOnly && id !== 'default' && id !== 'dark' && id !== 'system'\)/);+});++test('theme apply route responds and persists native theme selections and handles failures', async () => {+ const start = daemon.indexOf(" if (req.method === 'POST' && p === '/api/theme-apply') {");+ const end = daemon.indexOf('\n // 保存自定义主题', start);+ const route = vm.runInNewContext('(async function (req, res, p) {' + daemon.slice(start, end) + '})', {+ readBody: async req => req.body,+ themeApplyGeneration: 0, readSavedThemeId: () => 'default',+ PROFILE: { capabilities: { nativeComposer: true } },+ getTheme: () => ({}),+ applyThemeByCdp: async (id, options) => {+ if (id === 'default') throw new Error('CDP unavailable');+ assert.equal(options.nativeOnly, true);+ return { ok: true };+ },+ fs: { writeFileSync: (file, data) => saved.push(JSON.parse(data)) },+ path, DATA_DIR: '/synthetic',+ json: (res, status, body) => { res.status = status; res.body = body; },+ log() {},+ });+ const saved = [];+ const success = {};+ await route({ method: 'POST', body: { id: 'dark', nativeOnly: true } }, success, '/api/theme-apply');+ assert.equal(success.status, 200);+ assert.equal(success.body.id, 'dark');+ assert.equal(saved.length, 1);+ assert.equal(saved[0].id, 'dark');+ const system = {};+ await route({ method: 'POST', body: { id: 'system', nativeOnly: true } }, system, '/api/theme-apply');+ assert.equal(system.status, 200);+ assert.equal(saved[1].id, 'system');+ const failure = {};+ await route({ method: 'POST', body: { id: 'default', nativeOnly: true } }, failure, '/api/theme-apply');+ assert.equal(failure.status, 500);+ assert.equal(saved.length, 2);+});++test('follow system persists the system mode and reports the resolved appearance', async () => {+ const requests = [], notices = [];+ const context = {+ CAPS: {}, sessState: {themeTakeover:true}, themePane:null, root:{},+ syncWallpaperCardVisibility() {}, toast: message => notices.push(message),+ api: (route, options) => { requests.push({route, options}); return Promise.resolve({ok:true, resolved:'dark'}); },+ };+ vm.runInNewContext(section(' var ALLOWED_THEMES =', ' // 页面主题由 daemon'), context);+ await context.selectTheme('system');+ assert.equal(context.currentThemeId, 'system');+ assert.deepEqual(requests.map(r=>JSON.parse(r.options.body).id), ['system']);+ assert.match(notices[0], /深色/);+ // 壁纸目标在「跟随系统」下与浅色/深色一致:不会把 system 当作自定义主题目录+ assert.equal(context.themeSelectValue(), 'nebula');+});+test('wallpaper controls are exclusive to the selected frosted theme', () => {const wallpaper = {style:{}}, shadow = {style:{}};let loads=0;- const context = {sessState:{themeTakeover:true}, loadWallpapers:()=>loads++, themePane:{querySelector: selector => selector==='#wbs-wallpaper-card'?wallpaper:shadow}};+ const context = {sessState:{themeTakeover:true}, loadWallpaperRotation() {}, loadWallpapers:()=>loads++, themePane:{querySelector: selector => selector==='#wbs-wallpaper-card'?wallpaper:shadow}};vm.runInNewContext(section('function syncWallpaperCardVisibility(', ' // 关闭接管后'),context);- for(const id of ['default','dark','eye-care','cyber-purple','nebula']) {+ for(const id of ['system','default','dark','eye-care','cyber-purple','nebula']) {context.syncWallpaperCardVisibility(id);assert.equal(wallpaper.style.display, id==='nebula'?'':'none');assert.equal(shadow.style.display, wallpaper.style.display);}assert.equal(loads,1);});++for (const nativeMode of ['default', 'dark']) test('CodeBuddy reopens the saved system selection over native ' + nativeMode, async () => {+ const context = {+ CAPS: { nativeComposer: true }, themePane: null,+ document: { documentElement: { getAttribute: () => nativeMode === 'dark' ? 'dark' : 'light', classList: { contains: () => false } }, body: { getAttribute: () => '' } },+ syncWallpaperCardVisibility() {}, api: async () => ({ current: 'system' }),+ };+ vm.runInNewContext(section(' var ALLOWED_THEMES =', ' // 页面主题由 daemon'), context);+ await context.loadThemes();+ assert.equal(context.currentThemeId, 'system');+});diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.jsindex 66c3a4d..59a1277 100644--- a/test/renderer-escaping.test.js+++ b/test/renderer-escaping.test.js@@ -89,9 +89,9 @@ test('model, wallpaper, and account cards escape each dynamic HTML sink', () =>const accounts = sourceBetween('function render(data)', 'function updateAccountSummary()');assert.equal((accounts.match(/escAttr\(a\.uid\)/g) || []).length, 3);assert.doesNotMatch(accounts, /data-primary-uid/);- assert.equal((accounts.match(/escAttr\(a\.nickname \|\| '未命名'\)/g) || []).length, 2);- assert.match(accounts, /var nameVal = state\.mask \? maskAccountName\(rawName\) : rawName;/);- assert.match(accounts, /var idVal = state\.mask \? maskAccountId\(rawId\) : rawId;/);+ assert.equal((accounts.match(/escAttr\(accountDisplayName\(a, state\.mask\)\)/g) || []).length, 2);+ assert.match(accounts, /var nameVal = accountDisplayName\(a, state\.mask\);/);+ assert.match(accounts, /var idVal = accountDisplayId\(a, state\.mask\);/);assert.match(accounts, /wbs-name">' \+ esc\(nameVal\)/);assert.match(accounts, /wbs-val">' \+ esc\(idVal\)/);assert.match(accounts, /wbs-val[^\n]+esc\(ts\.label\)/);@@ -99,6 +99,16 @@ test('model, wallpaper, and account cards escape each dynamic HTML sink', () =>assert.doesNotMatch(accounts, /var idVal = a\.phone \? a\.phone/);});+test('clear account mode does not echo an official redaction placeholder', () => {+ const helpers = sourceBetween('function looksOfficiallyMasked(', 'function maskAccountName(');+ const getDisplay = new Function(`${helpers}; return { looksOfficiallyMasked, accountDisplayName, accountDisplayId };`);+ const { looksOfficiallyMasked, accountDisplayName, accountDisplayId } = getDisplay();+ assert.equal(looksOfficiallyMasked('135****6735'), true);+ assert.equal(accountDisplayName({ nickname: '135****6735', phone: '135****6735', uin: '998877' }, false), '135****6735');+ assert.equal(accountDisplayId({ phone: '135****6735', uin: '998877' }, false), '135****6735');+ assert.equal(accountDisplayName({ nickname: 'Alice', uin: '998877' }, false), 'Alice');+});+test('account masking preference persists per WorkDaddy profile', () => {assert.match(source, /var WBS_ACCOUNT_MASK_KEY = 'workdaddy\.account\.mask\.' \+ PROFILE_ID;/);assert.match(source, /localStorage\.getItem\(WBS_ACCOUNT_MASK_KEY\) === '1'/);diff --git a/test/session-copy-list-refresh.test.js b/test/session-copy-list-refresh.test.jsindex 83c8776..fb3d3c6 100644--- a/test/session-copy-list-refresh.test.js+++ b/test/session-copy-list-refresh.test.js@@ -57,6 +57,69 @@ test('completed copy batches publish the new WorkBuddy list before reporting donassert.equal(h.active(), 'existing-session');});+async function manualCopy({ kind = 'workbuddy', owner = 'target', connected = true, reject = false, status = 'copied' } = {}) {+ const stored = new Set(), visible = new Set(), calls = [];+ const ctx = {+ PROFILE: { kind }, cdp: { connected },+ currentAccount: () => ({ uid: owner }),+ readBody: async () => ({ ids: ['a', 'b'], targetUid: 'target' }),+ normalizeSessionIdBatch: ids => ids,+ accountSwitchInProgress: false, sessionCopyLocks: new Map(),+ sqlPlaceholders: () => '?,?',+ sqliteQuery: async () => [{ id: 'a' }, { id: 'b' }],+ copySessionRecord: async row => {+ if (status === 'copied') stored.add(row.id);+ return { status };+ },+ cdpSend: async (method, params) => {+ calls.push(method);+ assert.equal(stored.size, 2, 'manual refresh must follow the whole batch');+ if (reject) throw Error('renderer disconnected');+ const value = await vm.runInNewContext(params.expression, {+ window: { wb: { conversations: {+ ensureList: async () => { for (const id of stored) visible.add(id); },+ } } },+ });+ return { result: { value } };+ },+ reloadIdeWorkbenchWindows() {},+ json: (_res, code, body) => ({ code, body }),+ setTimeout, clearTimeout, log() {},+ };+ const refreshStart = source.indexOf('async function refreshWorkBuddySessionList(');+ vm.runInNewContext(source.slice(refreshStart, source.indexOf('async function refreshCopiedSessionList(', refreshStart)), ctx);+ const routeStart = source.indexOf("if (req.method === 'POST' && p === '/api/sessions/copy')");+ const routeEnd = source.indexOf(' // 迁移会话:', routeStart);+ vm.runInNewContext("function serve(req, res) { const p = '/api/sessions/copy';\n" + source.slice(routeStart, routeEnd) + '\n}', ctx);+ const response = await ctx.serve({ method: 'POST' }, {});+ assert.equal(ctx.sessionCopyLocks.size, 0);+ return { response, stored, visible, calls };+}++test('manual copies publish the whole batch in the current WorkBuddy list before returning success', async () => {+ const h = await manualCopy();+ assert.equal(h.response.code, 200);+ assert.equal(h.response.body.copied, 2);+ assert.deepEqual([...h.visible], ['a', 'b']);+ assert.deepEqual(h.calls, ['Runtime.evaluate'], 'copy must refresh without reloading or navigating');+});++for (const options of [{ kind: 'codebuddy' }, { owner: 'other-account' }, { connected: false }, { status: 'skipped' }]) {+ test('manual copy refresh respects profile, account, connection and unchanged-copy boundaries: ' + JSON.stringify(options), async () => {+ const h = await manualCopy(options);+ assert.equal(h.response.code, 200);+ assert.equal(h.calls.length, 0);+ });+}++test('manual copies remain successful if the renderer disconnects after the data is committed', async () => {+ const h = await manualCopy({ reject: true });+ assert.equal(h.response.code, 200);+ assert.equal(h.response.body.copied, 2);+ assert.equal(h.stored.size, 2);+ assert.equal(h.calls.length, 1);+});+for (const options of [{ kind: 'codebuddy' }, { owner: 'other-account' }, { connected: false }, { status: 'skipped' }]) {test('list refresh respects profile, account, connection and unchanged-copy boundaries: ' + JSON.stringify(options), async () => {const h = harness(options);diff --git a/test/stash-queue.test.js b/test/stash-queue.test.jsindex 210176b..b452c76 100644--- a/test/stash-queue.test.js+++ b/test/stash-queue.test.js@@ -232,6 +232,17 @@ test('modern queue path uses the top-level notifying adapter and clears stale adassert.match(inject, /stashSessionAtClick = sessionId/);});+test('modern WorkBuddy queue rows put the stash tag before the renamed actions group', () => {+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ const start = inject.indexOf('function syncQueueTags()');+ const end = inject.indexOf('\n function watchQueueOrder()', start);+ assert.ok(start >= 0 && end > start);+ const sync = inject.slice(start, end);+ assert.match(sync, /\.conversation-message-queue-item-actions/);+ assert.match(sync, /\.cb-message-queue-item-actions/);+ assert.match(sync, /actions\.insertBefore\(tag, actions\.firstChild\)/);+});+test('real modern queue actions remain owned by WorkBuddy official handlers', () => {const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');const start = inject.indexOf('function handleModernQueueActionClick(event)');diff --git a/test/system-theme.test.js b/test/system-theme.test.jsnew file mode 100644index 0000000..bcdef6b--- /dev/null+++ b/test/system-theme.test.js@@ -0,0 +1,259 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+const applyStart = source.indexOf('async function applyThemeByCdp(id, options = {})');+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,+ currentAccount: () => null, getTheme: () => ({ dark: true, colors: {} }),+ LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',+ wallpaperRotation: { status: () => ({ mode: 'manual' }) },+ setTimeout: resolve => resolve(), log() {},+ resolveSystemTheme: async () => 'dark', startSystemThemePolling() {}, stopSystemThemePolling() {},+ lastResolvedSystemTheme: null, readSavedThemeId: () => 'system',+ cdpSend: async () => ({ result: { value: { applied: true, ready: true } } }),+ ...overrides,+ };+ vm.runInNewContext(applySource, context);+ return context;+}++for (const automatic of [false, true]) test('later manual choice cancels a pending system lookup: automatic=' + automatic, async () => {+ let resolve, evaluations = 0;+ const context = applyContext({+ resolveSystemTheme: () => new Promise(done => { resolve = done; }),+ cdpSend: async () => { evaluations++; return { result: { value: { applied: true } } }; },+ });+ const pending = context.applyThemeByCdp('system', { automatic });+ await context.applyThemeByCdp('dark');+ resolve('default');+ const info = await pending;+ assert.equal(info.cancelled, true);+ assert.equal(evaluations, 1, 'the cancelled system choice must not reach the renderer');+ assert.equal(context.lastResolvedSystemTheme, null);+});++test('disabling takeover during a system lookup prevents application', async () => {+ let resolve, takeover = true;+ const context = applyContext({+ readSessionState: () => ({ themeTakeoverEnabled: takeover }),+ resolveSystemTheme: () => new Promise(done => { resolve = done; }),+ cdpSend: async () => { throw new Error('must not apply'); },+ });+ const pending = context.applyThemeByCdp('system');+ takeover = false;+ resolve('dark');+ assert.equal((await pending).cancelled, true);+});++test('failed system application keeps the last successful baseline for retry', async () => {+ const context = applyContext({+ lastResolvedSystemTheme: 'default',+ cdpSend: async () => { throw new Error('synthetic disconnect'); },+ cdpActivatePage: async () => {},+ connectCdp: async () => {},+ });+ await assert.rejects(context.applyThemeByCdp('system'), /synthetic disconnect/);+ assert.equal(context.lastResolvedSystemTheme, 'default');+});++test('a manual selection stops polling before its renderer request completes', async () => {+ let stopped = false, finish;+ const context = applyContext({+ stopSystemThemePolling: () => { stopped = true; },+ cdpSend: () => new Promise(resolve => { finish = resolve; }),+ });+ const pending = context.applyThemeByCdp('dark');+ assert.equal(stopped, true);+ finish({ result: { value: { applied: true } } });+ await pending;+});++function systemContext(overrides = {}) {+ const start = source.indexOf('function execCaptureText(');+ assert.ok(start >= 0, 'system theme helpers are present');+ const context = {+ PROFILE: { capabilities: { theme: true } }, process: { platform: 'linux' },+ cdp: { connected: true }, readSavedThemeId: () => 'system',+ readSessionState: () => ({ themeTakeoverEnabled: true }),+ setInterval: () => ({ unref() {} }), clearInterval() {},+ cdpSend: async () => ({ result: { value: 'dark' } }),+ ...overrides,+ };+ vm.createContext(context);+ vm.runInContext(source.slice(start, source.indexOf('function readSavedThemeId()', start)), context);+ return context;+}++for (const platform of ['linux', 'darwin', 'win32']) test('OS detection errors fall back to renderer on ' + platform, async () => {+ const context = systemContext({ process: { platform }, execFile: (cmd, args, options, done) => done(new Error('ENOENT')) });+ assert.equal(await context.resolveSystemTheme(), 'dark');+});++test('macOS missing appearance key is light rather than the renderer locked appearance', async () => {+ const context = systemContext({ process: { platform: 'darwin' },+ execFile: (cmd, args, options, done) => done(Object.assign(new Error('missing key'), { code: 1 }), '', 'The domain/default pair of (kCFPreferencesAnyApplication, AppleInterfaceStyle) does not exist'),+ });+ assert.equal(await context.resolveSystemTheme(), 'default');+});++for (const [platform, stdout, expected] of [+ ['win32', 'AppsUseLightTheme REG_DWORD 0x0', 'dark'],+ ['win32', 'AppsUseLightTheme REG_DWORD 0x1', 'default'],+ ['darwin', 'Dark\n', 'dark'],+ ['linux', "'prefer-dark'\n", 'dark'],+ ['linux', "'prefer-light'\n", 'default'],+]) test('OS preference overrides a locked renderer: ' + platform + ' ' + stdout.trim(), async () => {+ const context = systemContext({ process: { platform },+ execFile: (cmd, args, options, done) => done(null, stdout),+ cdpSend: async () => { throw new Error('must use OS preference'); },+ });+ assert.equal(await context.resolveSystemTheme(), expected);+});++test('Windows falls back from reg.exe to PowerShell before querying the renderer', async () => {+ const commands = [];+ const context = systemContext({ process: { platform: 'win32' },+ execFile: (cmd, args, options, done) => {+ commands.push(cmd);+ if (cmd === 'reg') done(new Error('EPERM'));+ else done(null, '0\r\n');+ },+ cdpSend: async () => { throw new Error('must use PowerShell preference'); },+ });+ assert.equal(await context.resolveSystemTheme(), 'dark');+ assert.deepEqual(commands, ['reg', 'powershell']);+});++test('system mode persists as system and failed manual changes resume following', async () => {+ const start = source.indexOf(" if (req.method === 'POST' && p === '/api/theme-apply') {");+ const end = source.indexOf('\n // 保存自定义主题', start);+ let saved = 'default', pollingStarted = 0;+ const context = {+ readBody: async req => req.body, PROFILE: { capabilities: {} }, themeApplyGeneration: 0,+ getTheme: id => id === 'dark',+ applyThemeByCdp: async id => {+ if (id === 'dark') throw new Error('synthetic failure');+ return { system: true, resolved: 'dark', applied: true };+ },+ fs: { writeFileSync: (file, data) => { saved = JSON.parse(data).id; } },+ path, DATA_DIR: '/synthetic', readSavedThemeId: () => saved,+ lastResolvedSystemTheme: 'dark',+ startSystemThemePolling: () => { pollingStarted++; },+ json: (res, status, body) => Object.assign(res, { status, body }), log() {},+ };+ const route = vm.runInNewContext('(async function(req, res, p) {' + source.slice(start, end) + '})', context);+ const success = {};+ await route({ method: 'POST', body: { id: 'system' } }, success, '/api/theme-apply');+ assert.equal(success.status, 200);+ assert.equal(saved, 'system');+ assert.equal(success.body.resolved, 'dark');+ const failed = {};+ await route({ method: 'POST', body: { id: 'dark' } }, failed, '/api/theme-apply');+ assert.equal(failed.status, 500);+ assert.equal(saved, 'system');+ assert.equal(context.lastResolvedSystemTheme, null);+ assert.equal(pollingStarted, 1);+ let reject;+ context.applyThemeByCdp = () => new Promise((resolve, fail) => { reject = fail; });+ const stale = route({ method: 'POST', body: { id: 'dark' } }, {}, '/api/theme-apply');+ await Promise.resolve();+ context.themeApplyGeneration++;+ reject(new Error('stale failure'));+ await stale;+ assert.equal(pollingStarted, 1, 'an older failure must not restart polling during a later selection');+});++test('polling serializes slow lookups and retries an unsuccessful application', async () => {+ let tick, resolve, lookups = 0, applications = 0, saved = 'system';+ const context = systemContext({ ...applyContext(), readSavedThemeId: () => saved,+ setInterval: fn => { tick = fn; return { unref() {} }; },+ });+ // Use the real apply function with the real polling closure and baseline.+ vm.runInContext(applySource, context);+ context.resolveSystemTheme = () => { lookups++; return new Promise(done => { resolve = done; }); };+ context.cdpSend = async () => {+ applications++;+ return { result: { value: { applied: applications > 1 } } };+ };+ context.startSystemThemePolling();+ const first = tick();+ await tick();+ assert.equal(lookups, 1, 'intervals must not overlap');+ resolve('dark'); await first;+ const retry = tick(); resolve('dark'); await retry;+ assert.equal(applications, 2, 'failed apply must be retried even if OS preference is unchanged');+ const unchanged = tick(); resolve('dark'); await unchanged;+ assert.equal(applications, 2, 'unchanged successful preference must not reapply');+ const stale = tick(); saved = 'default'; resolve('default'); await stale;+ assert.equal(applications, 2, 'a changed saved mode cancels a pending poll');+});++for (const profile of ['codebuddy-cn', 'codebuddy-intl']) test(profile + ' follows system without takeover and stops on native manual selection', async () => {+ let 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 }),+ setInterval: fn => { tick = fn; timerCount++; return { unref() {} }; }, clearInterval: () => { stopped++; },+ resolveSystemTheme: async () => mode,+ cdpSend: async (_, params) => {+ calls++;+ assert.ok(params.expression.includes('if (false && typeof MutationObserver'), 'native mode must not install a takeover guard');+ return { result: { value: { applied: mode !== 'default' } } };+ },+ });+ vm.runInContext(applySource, context);+ context.resolveSystemTheme = async () => mode;+ const first = await context.applyThemeByCdp('system', { nativeOnly: true });+ assert.equal(first.resolved, 'default');+ for (mode of ['dark', 'default', 'dark', 'default']) await tick();+ assert.equal(calls, 5);+ assert.equal(timerCount, 1);+ await tick(); assert.equal(calls, 5, 'unchanged preferences do not reapply');+ await context.applyThemeByCdp('dark', { nativeOnly: true });+ assert.equal(stopped, 1, 'manual native selections stop following');+});++for (const nativeOnly of [false, true]) test('native manual selection cancels a pending CodeBuddy system lookup: ' + nativeOnly, async () => {+ let finish, calls = 0;+ const context = applyContext({+ PROFILE: { capabilities: { theme: true, nativeComposer: true, themeTakeover: false } },+ readSessionState: () => ({ themeTakeoverEnabled: false }),+ resolveSystemTheme: () => new Promise(resolve => { finish = resolve; }),+ cdpSend: async (_, params) => {+ calls++;+ assert.ok(params.expression.includes('if (true) {\n wbsClearNativeCustomCss();'), 'inferred native mode must clean up native CSS too');+ return { result: { value: { applied: true } } };+ },+ });+ const pending = context.applyThemeByCdp('system', { nativeOnly: true });+ await context.applyThemeByCdp('dark', { nativeOnly });+ finish('default');+ assert.equal((await pending).cancelled, true);+ assert.equal(calls, 1);+});++test('CodeBuddy restores system mode after reconnect while leaving native manual choices alone', async () => {+ const start = source.indexOf('async function restoreSavedTheme()');+ const restore = source.slice(start, source.indexOf('\n/**', start));+ let saved = 'system', applied = [];+ const context = {+ PROFILE: { capabilities: { theme: true, nativeComposer: true, themeTakeover: false } },+ cdp: { connected: true }, readSavedThemeId: () => saved,+ readSessionState: () => ({ themeTakeoverEnabled: false }),+ applyThemeByCdp: async (id, options) => { applied.push({ id, ...options }); },+ };+ vm.runInNewContext(restore, context);+ await context.restoreSavedTheme();+ assert.deepEqual(applied, [{ id: 'system', automatic: true, nativeOnly: true }]);+ for (saved of ['default', 'dark', 'nebula']) await context.restoreSavedTheme();+ assert.equal(applied.length, 1);+});diff --git a/test/theme-patches.test.js b/test/theme-patches.test.jsindex 5fa5c92..438e470 100644--- a/test/theme-patches.test.js+++ b/test/theme-patches.test.js@@ -102,6 +102,15 @@ test('nebula removes backgrounds from teams composer utility trigger wrappers',assert.match(patch.css, /background-color:transparent !important/);});+test('nebula removes the voice trigger background inside its new wrapper', () => {+ const patch = patches.find(p => p.id === 'patch-107');+ const nestedVoice = '.teams-container .cr-input-toolbar__right>span.cr-voice-trigger-wrap>span.cr-voice-trigger-tooltip';+ assert.equal(patch.themeId, 'nebula');+ for (const prefix of [':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name]', 'body[data-vscode-theme-name="IDE Night"]']) {+ assert.ok(patch.css.includes(prefix + ' ' + nestedVoice), 'nested voice trigger is transparent in ' + prefix);+ }+});+test('generic dark popup text repair excludes the WorkDaddy status popover', () => {const patch = patches.find(item => item.id === 'patch-44');const selectors = patch.css.slice(0, patch.css.indexOf('{')).split(',');diff --git a/test/theme-restore-stability.test.js b/test/theme-restore-stability.test.jsindex d563a20..10683d2 100644--- a/test/theme-restore-stability.test.js+++ b/test/theme-restore-stability.test.js@@ -7,7 +7,7 @@ const path = require('node:path');const vm = require('node:vm');const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');-for (const saved of ['default', 'dark', 'eye-care', 'cyber-purple', 'nebula', 'missing', null]) {+for (const saved of ['default', 'dark', 'eye-care', 'cyber-purple', 'nebula', 'system', 'missing', null]) {test('theme takeover restores the saved choice after navigation: ' + saved, async () => {const start = source.indexOf('function readSavedThemeId()');const restore = source.indexOf('async function restoreSavedTheme()');@@ -26,14 +26,42 @@ for (const saved of ['default', 'dark', 'eye-care', 'cyber-purple', 'nebula', 'm});}+test('follow-system apply resolves once and reuses the normal theme pipeline', async () => {+ const start = source.indexOf('async function applyThemeByCdp(id, options = {})');+ const end = source.indexOf('\n/**', start);+ let pollingStarted = 0, resolutions = 0;+ const context = {+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },+ readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0, stopSystemThemePolling() {},+ currentAccount: () => null, getTheme: () => ({ dark: true, colors: {} }),+ LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',+ setTimeout: resolve => resolve(),+ wallpaperRotation: { status: () => ({ mode: 'manual' }) },+ resolveSystemTheme: async () => { resolutions++; return 'dark'; },+ startSystemThemePolling: () => { pollingStarted++; },+ lastResolvedSystemTheme: null,+ log: () => {},+ cdpSend: async () => ({ result: { value: { applied: true, ready: true } } }),+ };+ vm.runInNewContext(source.slice(start, end), context);+ const info = await context.applyThemeByCdp('system');+ assert.equal(resolutions, 1);+ assert.equal(info.system, true);+ assert.equal(info.resolved, 'dark');+ assert.equal(info.applied, true);+ assert.equal(pollingStarted, 1, 'system mode must start the OS theme polling');+ assert.equal(context.lastResolvedSystemTheme, 'dark');+});+async function themeExpression(id, takeover = true, accountUid = null, options = {}) {const start = source.indexOf('async function applyThemeByCdp(id, options = {})');const end = source.indexOf('\n/**', start);let expression;const context = {+ wallpaperRotation: { status: () => ({ mode: 'manual' }) },PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },readSessionState: () => ({ themeTakeoverEnabled: takeover }),- themeApplyGeneration: 0,+ themeApplyGeneration: 0, stopSystemThemePolling() {},setTimeout: resolve => resolve(),currentAccount: () => accountUid ? { uid: accountUid } : null, getTheme: () => ({ dark: id !== 'default', colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',@@ -74,6 +102,51 @@ function renderer() {return { context, document, observers, flush: () => observers.filter(o => o.active).forEach(o => o.callback([])) };}+for (const initial of ['default', 'dark']) test('system polling follows repeated OS changes from ' + initial + ' using real renderer replies', async () => {+ const page = renderer();+ const intervals = new Map();+ let appearance = initial, timer = 0, evaluations = 0;+ const daemon = {+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },+ readSessionState: () => ({ themeTakeoverEnabled: true }), themeApplyGeneration: 0,+ readSavedThemeId: () => 'system', currentAccount: () => null,+ getTheme: id => ({ dark: id !== 'default', colors: {} }),+ LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',+ wallpaperRotation: { status: () => ({ mode: 'manual' }) },+ setTimeout: resolve => resolve(), log() {},+ setInterval: fn => { const handle = { id: ++timer, unref() {} }; intervals.set(handle, fn); return handle; },+ clearInterval: handle => intervals.delete(handle),+ cdpSend: async (_, params) => {+ evaluations++;+ return { result: { value: vm.runInNewContext(params.expression, page.context) } };+ },+ };+ vm.createContext(daemon);+ const helpers = source.indexOf('function execCaptureText(');+ vm.runInContext(source.slice(helpers, source.indexOf('function readSavedThemeId()', helpers)), daemon);+ const apply = source.indexOf('async function applyThemeByCdp(id, options = {})');+ vm.runInContext(source.slice(apply, source.indexOf('\n/**', apply)), daemon);+ daemon.resolveSystemTheme = async () => appearance;+ const result = await daemon.applyThemeByCdp('system');+ assert.equal(result.applied, initial !== 'default', 'applied describes custom overrides, not success');+ assert.equal(intervals.size, 1, 'both initial appearances must start polling');+ assert.equal(vm.runInContext('lastResolvedSystemTheme', daemon), initial);+ for (const next of ['default', 'dark', 'default', 'dark', 'default']) {+ const changed = appearance !== next;+ appearance = next;+ const before = evaluations;+ await [...intervals.values()][0]();+ assert.equal(evaluations, before + (changed ? 1 : 0), 'only a changed appearance reaches CDP');+ assert.equal(page.document.documentElement.getAttribute('data-theme'), next === 'dark' ? 'dark' : 'light');+ assert.equal(page.document.documentElement.classList.contains('cb-dark'), next === 'dark');+ assert.equal(page.document.body.getAttribute('data-vscode-theme-name'), next === 'dark' ? 'IDE Night' : 'IDE Light');+ assert.equal(vm.runInContext('lastResolvedSystemTheme', daemon), next, 'light must advance the successful baseline');+ assert.equal(intervals.size, 1, 'polling must remain single across changes');+ }+ await daemon.applyThemeByCdp('dark');+ assert.equal(intervals.size, 0, 'a manual appearance stops following');+});+for (const snapshot of ['light', 'dark', null]) test('native sync follows both official theme buttons with snapshot ' + snapshot, () => {const { context, document } = renderer();const intervals = new Map();@@ -232,7 +305,7 @@ test('turning off takeover restores the WorkBuddy appearance saved before takeovcontext.localStorage.setItem('workbuddy.appearance.lastApplied.css', JSON.stringify({ resourceKey: 'special', css: ':root { --wb-bg-primary: pink; }' }));context.localStorage.setItem('workbuddy.appearance.mode::personal::personal::other', 'dark');const daemon = {- cdp: { connected: true }, themeApplyGeneration: 0,+ cdp: { connected: true }, themeApplyGeneration: 0, stopSystemThemePolling() {},readSessionState: () => ({ themeTakeoverEnabled: false }),currentAccount: () => ({ uid }),cdpSend: async (_, params) => { vm.runInNewContext(params.expression, context); return {}; },@@ -363,8 +436,9 @@ test('a pending light reset cannot overwrite takeover re-enabled during a CDP relet takeover = false;let evaluations = 0;const context = {+ wallpaperRotation: { status: () => ({ mode: 'manual' }) },PROFILE: { capabilities: { theme: true } }, cdp: { connected: true, ws: { readyState: 1 } },- readSessionState: () => ({ themeTakeoverEnabled: takeover }), themeApplyGeneration: 0,+ 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 } } }; },@@ -392,7 +466,8 @@ test('release resets light once then follows official dark and special skins acrdocument.adoptedStyleSheets = [];const tick = () => [...intervals.values()].forEach(fn => fn());const daemon = {- PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0,+ wallpaperRotation: { status: () => ({ mode: 'manual' }) },+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0, stopSystemThemePolling() {},readSessionState: () => ({ themeTakeoverEnabled: false }),cdpSend: async (_, params) => { vm.runInNewContext(params.expression, context); return {}; },applyThemeByCdp: async (id, options) => {@@ -479,7 +554,8 @@ test('nebula releases custom CSS and guards, waits for official dark, then reappvm.runInNewContext(await themeExpression('nebula', true, 'current'), context);const stages = [];const daemon = {- PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0,+ wallpaperRotation: { status: () => ({ mode: 'manual' }) },+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0, stopSystemThemePolling() {},setTimeout: resolve => resolve(),readSessionState: () => ({ themeTakeoverEnabled: true }), currentAccount: () => ({ uid: 'current' }),getTheme: id => ({ dark: id !== 'default', colors: {} }),@@ -575,7 +651,8 @@ test('frosted takeover completes even when background renderer timers and animat};let applies = 0;const daemon = {- PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0,+ wallpaperRotation: { status: () => ({ mode: 'manual' }) },+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0, stopSystemThemePolling() {},readSessionState: () => ({ themeTakeoverEnabled: true }), currentAccount: () => null,getTheme: () => ({ dark: true, colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',diff --git a/test/token-stats.test.js b/test/token-stats.test.jsindex df6bf5e..a3062ee 100644--- a/test/token-stats.test.js+++ b/test/token-stats.test.js@@ -164,7 +164,9 @@ test('token statistics UI keeps results under an overlay and exposes presets thrassert.match(source, /class="wbs-token-stats-overlay"/);assert.match(source, /overlay\.hidden = false/);assert.doesNotMatch(source, /data-token-search|data-token-reset/);- assert.doesNotMatch(source, /data-token-from|data-token-until|value="custom"/);+ assert.doesNotMatch(source, /data-token-from|data-token-until/);+ const segments = source.slice(source.indexOf('function usageTimeSegmentHtml('), source.indexOf('function onTokenStats()', source.indexOf('function usageTimeSegmentHtml(')));+ assert.doesNotMatch(segments, /value="custom"/);assert.doesNotMatch(source, /wbs-token-stats-diagnostics/);assert.match(source, /api\('\/api\/token-stats\?cacheStatus=1'\)/);assert.match(source, /if \(!metadata\.cacheReady\)/);diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex d017bd9..1293fa9 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -924,6 +924,14 @@ test('macOS launchers resolve an explicit target configuration before auto-discoassert.match(build, /workbuddy-target\.js" --resolve --profile=/);});+test('macOS launchers persist an automatically discovered enterprise target', () => {+ const relaunch = read('relaunch-with-cdp.sh');+ assert.match(relaunch, /单个企业客户端自动发现时也要持久化目标/);+ assert.match(relaunch, /workbuddy-target\.js" --configure --platform darwin/);+ assert.match(relaunch, /official_name="WorkBuddy"/);+ assert.match(relaunch, /\[ "\$APP_NAME" != "\$official_name" \]/);+});+test('macOS package launcher returns focus to the target WorkBuddy and separates AI identity', () => {const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');assert.match(build, /activate_target_app\(\)/);diff --git a/test/wallpaper-rotation.test.js b/test/wallpaper-rotation.test.jsnew file mode 100644index 0000000..d66efda--- /dev/null+++ b/test/wallpaper-rotation.test.js@@ -0,0 +1,263 @@+'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 { createWallpaperRotation, imageDimensions, updateWallpaperInRenderer } = require('../scripts/wallpaper-rotation');++function png(width = 100, height = 80) {+ const b = Buffer.alloc(33); Buffer.from('89504e470d0a1a0a', 'hex').copy(b);+ b.write('IHDR', 12); b.writeUInt32BE(width, 16); b.writeUInt32BE(height, 20); return b;+}+function setup(t, overrides = {}) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-rotation-'));+ const folder = path.join(dir, 'pictures'); fs.mkdirSync(folder);+ for (const name of ['a.png', 'b.png', '中文 空格.png']) fs.writeFileSync(path.join(folder, name), png());+ const configFile = path.join(dir, 'rotation.json');+ const images = []; let active = true; let time = 1000000; let scheduled;+ const rotation = createWallpaperRotation({ configFile, isActive: () => active,+ apply: async image => { images.push(image); return true; }, invalidate: async () => {},+ random: () => 0.4, now: () => time,+ setTimeout: (fn, ms) => { scheduled = { fn, ms }; return { unref() {} }; }, clearTimeout() {}, ...overrides });+ t.after(async () => { rotation.destroy(); await fs.promises.rm(dir, { recursive: true, force: true }); });+ return { dir, folder, configFile, images, rotation, pause: () => { active = false; }, resume: () => { active = true; },+ advance: ms => { time += ms; }, timer: () => scheduled };+}++test('rotation shuffles without repeats, streams original files and only persists metadata', async t => {+ const s = setup(t); const original = fs.readdirSync(s.folder);+ await s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes: 1 });+ for (let i = 0; i < 5; i++) await s.rotation.next();+ const names = s.images.map(i => i.name);+ assert.equal(new Set(names.slice(0, 3)).size, 3);+ assert.equal(new Set(names.slice(3, 6)).size, 3);+ assert.notEqual(names[2], names[3]);+ assert.deepEqual(fs.readdirSync(s.folder), original);+ assert.deepEqual(fs.readdirSync(s.dir).sort(), ['pictures', 'rotation.json']);+ const image = await s.rotation.openImage(s.images.at(-1).key);+ assert.equal(image.mime, 'image/png');+ assert.deepEqual(await image.handle.readFile(), png()); await image.handle.close();+ await assert.rejects(s.rotation.openImage(s.images[0].key));+ await assert.rejects(s.rotation.openImage('../pictures/a.png'));+});++test('manual mode cancels pending work and cannot be overwritten by an old completion', async t => {+ let finish; let invalidations = 0;+ const s = setup(t, { apply: () => new Promise(resolve => { finish = resolve; }), invalidate: async () => { invalidations++; } });+ const pending = s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes: 1 });+ while (!finish) await new Promise(resolve => setImmediate(resolve));+ await s.rotation.configure({ mode: 'manual' });+ finish(true); await pending;+ assert.equal(s.rotation.status().mode, 'manual');+ assert.equal(s.rotation.status().current, '');+ assert.ok(invalidations >= 2);+ assert.equal(JSON.parse(fs.readFileSync(s.configFile)).mode, 'manual');+});++test('restart restores current selection; inactive clients pause without catching up', async t => {+ const s = setup(t);+ await s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes: 3 });+ const current = s.rotation.status().current;+ s.pause(); s.advance(3600000); await s.rotation.next();+ assert.equal(s.images.length, 1);+ s.resume(); await s.rotation.restore();+ assert.equal(s.images.at(-1).name, current);+ assert.equal(s.images.length, 2);+ const restored = createWallpaperRotation({ configFile: s.configFile, isActive: () => true,+ apply: async image => { assert.equal(image.name, current); return true; }, invalidate: async () => {},+ setTimeout: () => 1, clearTimeout() {} });+ t.after(() => restored.destroy()); await restored.restore();+ assert.equal(restored.status().mode, 'random');+ assert.equal(restored.status().intervalMinutes, 3);+});++test('folder validation rejects bad input and scans only regular top-level supported files', async t => {+ const s = setup(t);+ for (const intervalMinutes of [0, 0.5, NaN, 1441, 'oops']) {+ await assert.rejects(s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes }));+ }+ await assert.rejects(s.rotation.configure({ mode: 'random', directory: 'relative', intervalMinutes: 1 }));+ await assert.rejects(s.rotation.configure({ mode: 'unknown' }));+ fs.mkdirSync(path.join(s.folder, 'sub')); fs.writeFileSync(path.join(s.folder, 'sub', 'hidden.png'), png());+ fs.writeFileSync(path.join(s.folder, 'ignore.svg'), '<svg/>');+ fs.symlinkSync(path.join(s.folder, 'a.png'), path.join(s.folder, 'link.png'));+ await s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes: 1 });+ assert.equal(s.rotation.status().count, 3);+});++test('bad images are skipped and missing directories preserve the current state with an actionable error', async t => {+ const s = setup(t);+ fs.writeFileSync(path.join(s.folder, 'bad.png'), 'broken');+ fs.writeFileSync(path.join(s.folder, 'huge.png'), png(60000, 60000));+ await s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes: 1 });+ for (let i = 0; i < 5; i++) await s.rotation.next();+ assert.ok(s.images.every(i => !['bad.png', 'huge.png'].includes(i.name)));+ const current = s.rotation.status().current;+ fs.renameSync(s.folder, s.folder + '-removed');+ await s.rotation.next();+ assert.equal(s.rotation.status().current, current);+ assert.match(s.rotation.status().error, /目录不可用/);+});++test('image endpoint revalidates real paths and dimensions after a file is replaced', async t => {+ const s = setup(t); await s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes: 1 });+ const selected = s.images.at(-1); const file = path.join(s.folder, selected.name);+ fs.unlinkSync(file); fs.symlinkSync(s.configFile, file);+ await assert.rejects(s.rotation.openImage(selected.key));+});++test('header validation recognises PNG, JPEG and WebP and rejects oversized dimensions', () => {+ assert.deepEqual(imageDimensions(png()), { width: 100, height: 80, mime: 'image/png' });+ const jpeg = Buffer.from('ffd8ffc00011080050006403011100021100031100ffd9', 'hex');+ assert.equal(imageDimensions(jpeg).width, 100);+ const webp = Buffer.alloc(30); webp.write('RIFF'); webp.write('WEBP', 8); webp.write('VP8X', 12);+ webp.writeUIntLE(99, 24, 3); webp.writeUIntLE(79, 27, 3);+ assert.equal(imageDimensions(webp).height, 80);+ assert.throws(() => imageDimensions(png(60000, 60000)));+ assert.throws(() => imageDimensions(Buffer.from('not an image')));+});++function renderer() {+ const revoked = []; const props = new Map(); let resolveImage;+ const win = {};+ const env = { window: win, document: { hidden: false, documentElement: {+ getAttribute: () => 'nebula', style: { setProperty: (k, v) => props.set(k,v), removeProperty: k => props.delete(k) } } },+ fetch: async () => ({ ok: true, blob: async () => ({}) }),+ URL: { createObjectURL: () => 'blob:' + Math.random(), revokeObjectURL: url => revoked.push(url) },+ Image: function () { this.decode = () => new Promise(resolve => { resolveImage = resolve; }); },+ AbortController, setTimeout, clearTimeout };+ vm.createContext(env); vm.runInContext('var update = ' + updateWallpaperInRenderer.toString(), env);+ return { env, win, revoked, props, finish: () => resolveImage(), wait: async () => { while (!resolveImage) await new Promise(resolve => setImmediate(resolve)); } };+}++test('renderer swaps only after decode, releases old URLs and cancels late completions', async () => {+ const r = renderer(); const first = r.env.update({ url: '/image', token: 'synthetic' });+ await r.wait(); assert.equal(r.props.size, 0); r.finish(); assert.equal(await first, true);+ assert.equal(r.props.size, 1);+ const second = r.env.update({ url: '/next', token: 'synthetic' });+ await new Promise(resolve => setImmediate(resolve));+ r.win.__wbsWallpaperRuntime.dispose(); r.finish();+ assert.equal(await second, false); assert.equal(r.props.size, 0);+ assert.equal(new Set(r.revoked).size, 2);+ assert.equal(r.revoked.length, 2, 'each URL is released exactly once');+ const third = r.env.update({ url: '/restart', token: 'synthetic' });+ await new Promise(resolve => setImmediate(resolve)); r.finish();+ assert.equal(await third, true);+ r.win.__wbsWallpaperRuntime.dispose();+});+++test('concurrent next requests share one load instead of queueing repeated changes', async t => {+ let finish; let blocked = false;+ const s = setup(t, { apply: async image => {+ s.images.push(image);+ if (blocked) await new Promise(resolve => { finish = resolve; });+ return true;+ } });+ await s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes: 1 });+ blocked = true;+ const pending = Array.from({ length: 20 }, () => s.rotation.next());+ while (!finish) await new Promise(resolve => setImmediate(resolve));+ finish(); await Promise.all(pending);+ assert.equal(s.images.length, 2);+});++test('scheduler waits for the interval and resumes once after an inactive period', async t => {+ const s = setup(t);+ await s.rotation.configure({ mode: 'random', directory: s.folder, intervalMinutes: 3 });+ s.advance(60000); await s.timer().fn();+ assert.equal(s.images.length, 1);+ s.advance(120000); await s.timer().fn();+ assert.equal(s.images.length, 2);+ s.pause(); s.advance(3600000); await s.timer().fn();+ assert.equal(s.images.length, 2);+ s.resume(); await s.timer().fn();+ assert.equal(s.images.length, 3);+ await s.timer().fn();+ assert.equal(s.images.length, 3, 'no catch-up burst after resume');+});++test('daemon routes stream authenticated original bytes and reject stale image tickets', async t => {+ const http = require('node:http');+ const s = setup(t);+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ const start = source.indexOf('function handleApi(req, res)');+ const end = source.indexOf('\n/*', start + 10);+ const context = {+ URL, HOST: '127.0.0.1', PROFILE: { capabilities: { theme: true } }, wallpaperRotation: s.rotation,+ isAllowedApiOrigin: origin => origin === 'file://',+ isApiRequestAuthorized: req => req.headers['x-workdaddy-token'] === 'synthetic-test-token',+ json(res, status, body) { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body)); },+ readBody: async req => { let body = ''; for await (const c of req) body += c; return JSON.parse(body); },+ };+ // Compile the actual handler without starting the daemon or touching account files.+ vm.runInNewContext(source.slice(start, end), context);+ const server = http.createServer(context.handleApi);+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+ t.after(() => new Promise(resolve => server.close(resolve)));+ const base = 'http://127.0.0.1:' + server.address().port;+ const headers = { 'X-WorkDaddy-Token': 'synthetic-test-token', Origin: 'file://' };+ assert.equal((await fetch(base + '/api/wallpaper-rotation')).status, 401);+ let response = await fetch(base + '/api/wallpaper-rotation', { method: 'POST', headers,+ body: JSON.stringify({ mode: 'random', directory: s.folder, intervalMinutes: 5 }) });+ assert.equal(response.status, 200);+ const saved = await response.json(); assert.equal(saved.mode, 'random');+ const url = base + '/api/wallpaper-rotation/image?key=' + s.images.at(-1).key;+ assert.equal((await fetch(url)).status, 401);+ response = await fetch(url, { headers });+ assert.equal(response.status, 200);+ assert.equal(response.headers.get('access-control-allow-origin'), 'file://');+ assert.equal(response.headers.get('content-type'), 'image/png');+ assert.deepEqual(Buffer.from(await response.arrayBuffer()), png());+ await fetch(base + '/api/wallpaper-rotation', { method: 'POST', headers, body: '{"mode":"manual"}' });+ assert.equal((await fetch(url, { headers })).status, 404);+ response = await fetch(base + '/api/wallpaper-rotation', { method: 'POST', headers, body: '{"mode":"bogus"}' });+ assert.equal(response.status, 400);+});++test('panel permits pasting the first directory, keeps modes exclusive and saves a custom interval', async () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const start = source.indexOf(' var wallpaperRotationState = null;');+ const end = source.indexOf(' // 官方壁纸网格:', start);+ const node = extra => ({ value: '', hidden: false, dataset: {}, listeners: {},+ addEventListener(event, fn) { this.listeners[event] = fn; }, focus() {}, select() {}, ...extra });+ const radios = ['manual', 'random'].map(value => node({ value, checked: value === 'manual' }));+ const ids = {};+ for (const id of ['random', 'manual', 'directory', 'interval', 'minutes', 'pick', 'next', 'custom-wrap', 'status']) ids['#wbs-wallpaper-' + id] = node();+ ids['#wbs-wallpaper-interval'].value = '10'; ids['#wbs-wallpaper-minutes'].value = '10';+ const requests = [];+ let persisted = { mode: 'manual', directory: '', intervalMinutes: 10, current: '', paused: false };+ const env = { alive: true, state: { open: false }, root: {}, document: { activeElement: null }, setBuildInterval() {},+ themePane: { querySelector: id => ids[id], querySelectorAll: selector => selector.startsWith('input[name=') ? radios : [] },+ toast: message => assert.fail(message), api: async (route, options) => {+ requests.push({ route, options });+ if (route.endsWith('/pick')) return { cancelled: true };+ if (options?.body) persisted = { ...persisted, ...JSON.parse(options.body) };+ return { ...persisted };+ } };+ vm.createContext(env); vm.runInContext(source.slice(start, end), env);+ const flush = () => new Promise(resolve => setImmediate(resolve));+ env.wireWallpaperRotation(); await flush();+ radios[1].checked = true; radios[1].listeners.change();+ assert.equal(ids['#wbs-wallpaper-random'].hidden, false);+ assert.equal(ids['#wbs-wallpaper-manual'].hidden, true);+ assert.equal(ids['#wbs-wallpaper-next'].disabled, true);+ assert.equal(requests.some(r => r.route.endsWith('/pick')), false, 'first selection allows typing instead of forcing a native picker');+ await env.loadWallpaperRotation();+ assert.equal(ids['#wbs-wallpaper-random'].hidden, false, 'polling preserves the unsaved folder entry');+ ids['#wbs-wallpaper-directory'].value = '/pictures';+ ids['#wbs-wallpaper-directory'].listeners.change(); await flush();+ assert.equal(persisted.mode, 'random'); assert.equal(persisted.directory, '/pictures');+ ids['#wbs-wallpaper-interval'].value = 'custom'; ids['#wbs-wallpaper-interval'].listeners.change();+ assert.equal(ids['#wbs-wallpaper-custom-wrap'].hidden, false);+ ids['#wbs-wallpaper-minutes'].value = '17'; ids['#wbs-wallpaper-minutes'].listeners.change(); await flush();+ assert.equal(persisted.intervalMinutes, 17);+ ids['#wbs-wallpaper-pick'].listeners.click(); await flush();+ assert.equal(persisted.directory, '/pictures', 'cancel leaves the chosen directory intact');+ radios[0].checked = true; radios[0].listeners.change(); await flush();+ assert.equal(persisted.mode, 'manual');+ assert.equal(ids['#wbs-wallpaper-random'].hidden, true);+ assert.equal(ids['#wbs-wallpaper-manual'].hidden, false);+});diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.jsindex f8cda4c..ae6371d 100644--- a/test/windows-native-flow.test.js+++ b/test/windows-native-flow.test.js@@ -172,6 +172,18 @@ test('the current CodeBuddy CN installer path uses exact-path checks without reqassert.match(matchSource, /target\.Binary != "" \|\| codeBuddyBinaryMatches\(profile, record\.Path\)/);});+test('native lifecycle matching keeps WorkBuddy CN separate from CodeBuddy CN', () => {+ const native = read('scripts/windows-native/main.go');+ const start = native.indexOf('func workBuddyImage(');+ const end = native.indexOf('\nfunc processNamesForBinary(', start);+ assert.ok(start >= 0 && end > start);+ const source = native.slice(start, end);+ assert.match(source, /if profile == profileCodeCN \{\s*return "CodeBuddy CN\.exe"/);+ assert.match(source, /if profile == profileAI \{\s*return "WorkBuddyAI\.exe"/);+ assert.match(source, /if profile == profileCN \{\s*return "WorkBuddy\.exe"/);+ assert.match(source, /return "WorkBuddy\.exe"/);+});+test('CodeDaddy installer rejects a wrong executable before native process inspection', () => {const installer = read('scripts/win/workdaddy.iss');assert.match(installer, /function SelectedClientFile\(const Candidate: String\): Boolean/);diff --git a/test/workbuddy-compat.test.js b/test/workbuddy-compat.test.jsindex 580ae5a..49e530a 100644--- a/test/workbuddy-compat.test.js+++ b/test/workbuddy-compat.test.js@@ -231,6 +231,14 @@ test('account import accepts legacy plaintext and preserves encrypted token enveassert.equal(lib.wdCompatText(envelope), '(已加密)');});+test('token phone claim fills an officially redacted phone field without exposing other claims', () => {+ const payload = Buffer.from(JSON.stringify({ preferred_username: '13592246735', email: '[email protected]' })).toString('base64url');+ const token = `header.${payload}.signature`;+ assert.equal(lib.wdCompatTokenPhone(token), '13592246735');+ assert.equal(lib.wdCompatTokenPhone('header.invalid.signature'), '');+ assert.equal(lib.wdCompatTokenPhone(''), '');+});+test('Windows encrypted-field key lookup honors the configured WorkBuddy target path', { skip: process.platform !== 'win32' }, () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-compat-target-'));const previousProfile = process.env.WBSWITCH_PROFILE;diff --git a/test/workbuddy-launch-env.test.js b/test/workbuddy-launch-env.test.jsnew file mode 100644index 0000000..46481e7--- /dev/null+++ b/test/workbuddy-launch-env.test.js@@ -0,0 +1,169 @@+'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 { EventEmitter } = require('node:events');+const { getClientLaunchArgs } = require('../scripts/client-launch-settings.js');+const { getWorkBuddyLaunchEnv } = require('../scripts/workbuddy-launch-env.js');++function fixture(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-update-424-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ return dir;+}++function launchContext(profile, dataDir, env, spawn) {+ const ctx = {+ PROFILE: profile, DATA_DIR: dataDir, CDP_PORT: 9223,+ process: { platform: 'win32', env }, IS_WIN: true, IS_LINUX: false, path,+ getClientLaunchArgs,+ getWorkBuddyLaunchEnv,+ log() {}, selectCdpPort: async () => 9223,+ resolveWorkBuddyBinary: () => 'C:\\WorkBuddy.exe', sleep: async () => {}, restoreWorkBuddyWindow: async () => {},+ spawn(command, args, options) {+ spawn(command, Array.from(args), options);+ const child = new EventEmitter(); child.pid = 123; child.unref = () => {};+ queueMicrotask(() => child.emit('spawn'));+ return child;+ },+ };+ for (const [file, startMarker, endMarker] of [+ ['win-launcher.js', 'function launchWorkBuddy(wb)', '\nasync function waitForWorkBuddyCdp'],+ ['daemon.js', 'function relaunchWorkBuddy()', '\n/**'],+ ]) {+ const source = fs.readFileSync(path.join(__dirname, '../scripts', file), 'utf8');+ const start = source.indexOf(startMarker);+ vm.runInNewContext(source.slice(start, source.indexOf(endMarker, start)), ctx);+ }+ return ctx;+}++// Replay the official updater's two independent inputs: an environment override+// wins over the remembered endpoint, but startup restores installers from TEMP+// before checking the feed (main/update-service{,.win32}.js in WorkBuddy).+function replayOfficialUpdater(env, dataRoot) {+ const endpoint = env.WORKBUDDY_UPDATE_URL || JSON.parse(fs.readFileSync(path.join(dataRoot, 'cache/update-endpoint.json'), 'utf8')).endpoint;+ const cache = path.join(env.TEMP, 'workbuddy-update-x64');+ const installers = fs.existsSync(cache) ? fs.readdirSync(cache).filter(name => /^WorkBuddy-Setup-(.+)\.exe$/i.test(name)) : [];+ return { endpoint, cache, installers };+}++for (const [id, endpoint] of [+ ['workbuddy-cn', 'https://www.workbuddy.cn'],+ ['workbuddy-ai', 'https://www.workbuddy.ai'],+]) {+ test(`#424 ${id}: startup and daemon relaunch ignore the sibling feed and shared cached installer`, async t => {+ const dir = fixture(t);+ const dataRoot = path.join(dir, id === 'workbuddy-cn' ? '.workbuddy' : '.workbuddy-ai');+ const siblingEndpoint = id === 'workbuddy-cn' ? 'https://www.workbuddy.ai' : 'https://www.workbuddy.cn';+ const sharedTemp = path.join(dir, 'shared-temp');+ const sharedCache = path.join(sharedTemp, 'workbuddy-update-x64');+ fs.mkdirSync(sharedCache, { recursive: true });+ fs.writeFileSync(path.join(sharedCache, 'WorkBuddy-Setup-99.0.0.exe'), 'wrong-client-fixture');+ fs.mkdirSync(path.join(dataRoot, 'cache'), { recursive: true });+ const remembered = JSON.stringify({ endpoint: siblingEndpoint });+ fs.writeFileSync(path.join(dataRoot, 'cache/update-endpoint.json'), remembered);+ const env = Object.freeze({ TEMP: sharedTemp, TMP: sharedTemp, WORKBUDDY_UPDATE_URL: siblingEndpoint,+ WORKBUDDY_CONFIG_DIR: path.join(dir, 'sibling'), CODEBUDDY_CONFIG_DIR: path.join(dir, 'sibling'),+ WORKBUDDY_DATA_FOLDER_NAME: '.wrong-client', UNRELATED: 'keep' });+ const launches = [];+ const ctx = launchContext({ id, dataRoot, cdp: { mode: 'environment' } }, dir, env,+ (_command, args, options) => launches.push({ args, env: options.env }));+ for (const mode of ['environment', 'argument']) {+ ctx.PROFILE.cdp.mode = mode;+ ctx.launchWorkBuddy('C:\\WorkBuddy.exe');+ await ctx.relaunchWorkBuddy();+ }+ assert.equal(launches.length, 4);+ for (const launch of launches) {+ const restored = replayOfficialUpdater(launch.env, dataRoot);+ assert.equal(restored.endpoint, endpoint, 'the selected profile must own the update feed');+ assert.deepEqual(restored.installers, [], 'an old wrong-client installer must never be restored');+ assert.notEqual(launch.env.TEMP, sharedTemp);+ assert.equal(launch.env.TEMP, launch.env.TMP);+ assert.ok(fs.statSync(launch.env.TEMP).isDirectory());+ assert.equal(launch.env.WORKBUDDY_CONFIG_DIR, dataRoot);+ assert.equal(launch.env.CODEBUDDY_CONFIG_DIR, dataRoot);+ assert.equal(launch.env.WORKBUDDY_DATA_FOLDER_NAME, path.basename(dataRoot));+ assert.equal(launch.env.UNRELATED, 'keep');+ if (launch.args.length === 0) assert.equal(launch.env.WORKBUDDY_REMOTE_DEBUGGING_PORT, '9223');+ else assert.deepEqual(launch.args, ['--remote-debugging-port=9223']);+ }+ assert.equal(new Set(launches.map(launch => launch.env.TEMP)).size, 1, 'cache survives restarts');+ assert.equal(fs.readFileSync(path.join(sharedCache, 'WorkBuddy-Setup-99.0.0.exe'), 'utf8'), 'wrong-client-fixture');+ assert.equal(fs.readFileSync(path.join(dataRoot, 'cache/update-endpoint.json'), 'utf8'), remembered);+ assert.equal(env.WORKBUDDY_UPDATE_URL, siblingEndpoint, 'parent environment is never changed');+ });+}++test('#424 a correct feed must also exclude the wrong shared installer', async t => {+ const dir = fixture(t);+ const sharedCache = path.join(dir, 'workbuddy-update-x64');+ fs.mkdirSync(sharedCache);+ fs.writeFileSync(path.join(sharedCache, 'WorkBuddy-Setup-99.0.0.exe'), 'wrong-client-fixture');+ const env = { TEMP: dir, TMP: dir, WORKBUDDY_UPDATE_URL: 'https://www.workbuddy.cn' };+ const ctx = launchContext({ id: 'workbuddy-cn', dataRoot: path.join(dir, '.workbuddy') }, dir, env,+ (_command, _args, options) => assert.deepEqual(replayOfficialUpdater(options.env).installers, []));+ ctx.launchWorkBuddy('C:\\WorkBuddy.exe');+ await ctx.relaunchWorkBuddy();+});++test('CN and AI have independent persistent caches even with the same WorkDaddy data directory', t => {+ const dir = fixture(t);+ const cn = { id: 'workbuddy-cn', dataRoot: path.join(dir, '.workbuddy') };+ const ai = { id: 'workbuddy-ai', dataRoot: path.join(dir, '.workbuddy-ai') };+ const cnEnv = getWorkBuddyLaunchEnv(cn, dir, 'win32', {});+ const aiEnv = getWorkBuddyLaunchEnv(ai, dir, 'win32', cnEnv);+ assert.notEqual(cnEnv.TEMP, aiEnv.TEMP);+ for (const [profile, env] of [[cn, cnEnv], [ai, aiEnv]]) {+ const cache = path.join(env.TEMP, 'workbuddy-update-x64');+ fs.mkdirSync(cache);+ fs.writeFileSync(path.join(cache, 'WorkBuddy-Setup-100.0.0.exe'), profile.id);+ const nextEnv = getWorkBuddyLaunchEnv(profile, dir, 'win32', aiEnv);+ const restored = replayOfficialUpdater(nextEnv);+ assert.equal(nextEnv.TEMP, env.TEMP, 'inherited TEMP must not cause nesting');+ assert.deepEqual(restored.installers, ['WorkBuddy-Setup-100.0.0.exe'], 'valid new updates remain available');+ assert.equal(fs.readFileSync(path.join(restored.cache, restored.installers[0]), 'utf8'), profile.id);+ }+});++test('Windows case variants cannot shadow the profile overrides', t => {+ const dir = fixture(t);+ const profile = { id: 'workbuddy-cn', dataRoot: path.join(dir, '.workbuddy') };+ const inherited = Object.freeze({ temp: 'wrong', Tmp: 'wrong', TeMp: 'wrong', workbuddy_update_url: 'wrong',+ WorkBuddy_Config_Dir: 'wrong', codebuddy_config_dir: 'wrong', workbuddy_data_folder_name: '.wrong', Path: 'keep' });+ const env = getWorkBuddyLaunchEnv(profile, dir, 'win32', inherited);+ for (const key of ['TEMP', 'TMP', 'WORKBUDDY_UPDATE_URL', 'WORKBUDDY_CONFIG_DIR', 'CODEBUDDY_CONFIG_DIR', 'WORKBUDDY_DATA_FOLDER_NAME']) {+ assert.deepEqual(Object.keys(env).filter(name => name.toUpperCase() === key), [key]);+ }+ assert.equal(env.WORKBUDDY_UPDATE_URL, 'https://www.workbuddy.cn');+ assert.equal(env.Path, 'keep');+});++test('other platforms, CodeBuddy and enterprise targets preserve their launch environments without creating directories', t => {+ const dir = fixture(t);+ const env = Object.freeze({ TEMP: 'custom', WORKBUDDY_UPDATE_URL: 'https://updates.example.test', CODEBUDDY_CONFIG_DIR: 'custom' });+ for (const [profile, platform] of [+ [{ id: 'workbuddy-cn' }, 'darwin'], [{ id: 'workbuddy-ai' }, 'linux'],+ [{ id: 'codebuddy-cn' }, 'win32'], [{ id: 'codebuddy-intl' }, 'win32'],+ [{ id: 'workbuddy-cn', customTarget: true }, 'win32'], [{ id: 'workbuddy-ai', customTarget: true }, 'win32'],+ ]) {+ const childEnv = getWorkBuddyLaunchEnv(profile, dir, platform, env);+ assert.deepEqual(childEnv, env);+ assert.notEqual(childEnv, env);+ }+ assert.deepEqual(fs.readdirSync(dir), []);+});++test('both launch paths fail before spawning when cache isolation is unavailable', async t => {+ const dir = fixture(t);+ fs.writeFileSync(path.join(dir, 'client-tmp'), 'cannot-create-directory');+ let spawned = false;+ const ctx = launchContext({ id: 'workbuddy-cn', dataRoot: path.join(dir, '.workbuddy') }, dir, {}, () => { spawned = true; });+ assert.throws(() => ctx.launchWorkBuddy('C:\\WorkBuddy.exe'), /独立临时目录/);+ await assert.rejects(ctx.relaunchWorkBuddy(), /独立临时目录/);+ assert.equal(spawned, false);+});