WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
修复删除账号失败;修复多任务执行时非激活会话无法自动允许跳过的问题;会话导入导出更可靠;账号页不再强制把当前账号放在第一位,默认按积分过期时间排序;优化 Windwows 安装和更新流程;
[email protected]f6a73cb8b75c
diff --git a/AGENTS.md b/AGENTS.mdindex bdd5238..f874dcb 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -106,6 +106,7 @@ The queue item's 暂存提示词 tag is rendered by `syncQueueTags` (in `scripts## Release Version Consistency- A release version must be identical in the package filename, macOS `Info.plist` (`CFBundleShortVersionString`/`CFBundleVersion`), and the packaged `scripts/daemon.js` `DAEMON_VERSION`. A package named `1.0.10` that runs daemon code reporting `1.0.6` is invalid.+- Update availability has one source of truth: compare the latest GitHub or cached release version with the running `DAEMON_VERSION` every time. Never persist or trust a cached `hasUpdate` decision across daemon versions, and clear any existing update card/red dot when no newer version exists.- Build scripts must always rewrite the staged daemon version from the release `VERSION`; never rely on the version embedded in the reusable `WorkDaddy.app` shell or on a conditional test-only override.- Windows releases are `Setup.exe` only. The `*-win64.zip` created by the installer pipeline is temporary staging and must be deleted before artifact upload or GitHub Release publication; ZIP remains supported only as an updater fallback for historical releases.- Before publishing or handing off a package, inspect the actual DMG/Setup.exe payload and record the daemon version, app metadata version, profile branding, and required update scripts. Do not infer package correctness from the filename alone.diff --git a/release/macos/WorkDaddy-1.1.8.dmg b/release/macos/WorkDaddy-1.1.9.dmgsimilarity index 74%rename from release/macos/WorkDaddy-1.1.8.dmgrename to release/macos/WorkDaddy-1.1.9.dmgindex 53f8fec..56d0a77 100644Binary files a/release/macos/WorkDaddy-1.1.8.dmg and b/release/macos/WorkDaddy-1.1.9.dmg differdiff --git a/release/macos/WorkDaddy-AI-1.1.8.dmg b/release/macos/WorkDaddy-AI-1.1.9.dmgsimilarity index 74%rename from release/macos/WorkDaddy-AI-1.1.8.dmgrename to release/macos/WorkDaddy-AI-1.1.9.dmgindex 7f92570..cc29d25 100644Binary files a/release/macos/WorkDaddy-AI-1.1.8.dmg and b/release/macos/WorkDaddy-AI-1.1.9.dmg differdiff --git a/release/windows/WorkDaddy-AI-Setup-1.1.8.exe b/release/windows/WorkDaddy-AI-Setup-1.1.9.exesimilarity index 76%rename from release/windows/WorkDaddy-AI-Setup-1.1.8.exerename to release/windows/WorkDaddy-AI-Setup-1.1.9.exeindex 25fa456..72dbfd9 100644Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.8.exe and b/release/windows/WorkDaddy-AI-Setup-1.1.9.exe differdiff --git a/release/windows/WorkDaddy-Setup-1.1.8.exe b/release/windows/WorkDaddy-Setup-1.1.9.exesimilarity index 75%rename from release/windows/WorkDaddy-Setup-1.1.8.exerename to release/windows/WorkDaddy-Setup-1.1.9.exeindex 3abdc4f..bd885a5 100644Binary files a/release/windows/WorkDaddy-Setup-1.1.8.exe and b/release/windows/WorkDaddy-Setup-1.1.9.exe differdiff --git a/scripts/daemon.js b/scripts/daemon.jsindex db633e1..9aab1c7 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -94,6 +94,7 @@ const {moveAutoCopySession,removeAutoCopySession,removeAutoCopyAccount,+ collectLineageMembersForDelete,getAutoCopyMapping,setAutoCopyMapping,deleteAutoCopyMapping,@@ -266,8 +267,20 @@ const DATA_DIR = defaultDataDir();// 1.1.39:账号脱敏状态按 profile 持久化;WorkDaddy 触发页面重载后在主执行上下文创建时提前注入。// 1.1.40:跨账号重载跟随新主 frame,并在会话自动复制占用事件循环前等待组件实际挂载。// 1.1.41:后台会话自动复制在文件边界让出 I/O;账号重载期间暂停复制,优先完成组件挂载。-const DAEMON_VERSION = '1.1.41';-const DAEMON_BUILD_ID = 'release-1.1.41-20260905-prioritize-switch-reload';+// 1.1.42:删除账号时同步清理旧版 HelloBuddy 迁移源,避免重启后账号备份复活。+// 1.1.43:更新缓存只保存发布信息,每次按当前 daemon 版本重新判断,避免同版本重复提示。+// 1.1.45:导出使用 gzip + AES-GCM v3,导入兼容 v2;页面刷新失败不阻塞导入响应。+// 1.1.46:删除会话按 lineage 级联删除其他账号的同源副本(DB+消息文件+复制规则),+// 修复「删除某账号会话后切走再切回,auto-copy 把副本复制回来导致会话复活」。+// 1.1.47:会话导入返回逐条失败原因,导入结果停留在弹窗供用户查看。+// 1.1.48:会话导入不再自动刷新页面,结果弹窗曾提供手动刷新入口。+// 1.1.49:会话导入完成后完全不刷新页面,只展示导入结果并由用户关闭弹窗。+// 1.1.50:新增 /api/cdp-click 真实鼠标点击(CDP Input.dispatchMouseEvent)——官方侧栏/确认+// 类 UI 拒绝 isTrusted=false 的 click(),仅原生输入可触发;供自动批准等链路使用。+// 1.1.51:Rule1/Auto-Continue 完成标记由零宽字符改为 Markdown 引用定义 [wbs-reply-done]: #+// (零宽会被官方存储链路转义成字面 \u200b 显形);inject 完成检测同步兼容。+const DAEMON_VERSION = '1.1.51';+const DAEMON_BUILD_ID = 'release-1.1.51-20260906-rule1-markdown-marker';const HOST = '127.0.0.1';const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app@@ -645,7 +658,8 @@ function checkUpdate(force) {updateState.checkedAt = Date.now();updateState.status = 'idle';updateState.message = updateState.hasUpdate ? '发现新版本 v' + latest : '已是最新版本';- try { fs.writeFileSync(UPDATE_CHECK_CACHE, JSON.stringify({ latest, hasUpdate: updateState.hasUpdate, dmgUrl: updateState.dmgUrl, dmgSize: updateState.dmgSize, dmgSha256: updateState.dmgSha256, assetName: updateState.assetName, notes: updateState.notes, checkedAt: updateState.checkedAt })); } catch (_) {}+ // 缓存发布信息,不缓存依赖当前运行版本的判断结果。+ try { fs.writeFileSync(UPDATE_CHECK_CACHE, JSON.stringify({ latest, dmgUrl: updateState.dmgUrl, dmgSize: updateState.dmgSize, dmgSha256: updateState.dmgSha256, assetName: updateState.assetName, notes: updateState.notes, checkedAt: updateState.checkedAt })); } catch (_) {}log(`[update] 检查完成: latest=${latest} hasUpdate=${updateState.hasUpdate} (current=${DAEMON_VERSION})`);updateDebug('check-result', { current: DAEMON_VERSION, latest, hasUpdate: updateState.hasUpdate, assetName: updateState.assetName, assetSize: updateState.dmgSize, assetSha256: updateState.dmgSha256 });return updateState;@@ -659,14 +673,16 @@ function checkUpdate(force) {// 尝试读缓存兜底(上次成功的结果)try {const c = JSON.parse(fs.readFileSync(UPDATE_CHECK_CACHE, 'utf8'));- updateState.latest = c.latest;- updateState.hasUpdate = !!c.hasUpdate;+ const cachedLatest = String(c.latest || '').replace(/^v/, '');+ updateState.latest = cachedLatest;+ updateState.hasUpdate = semverCompare(cachedLatest, DAEMON_VERSION) > 0;updateState.dmgUrl = c.dmgUrl;updateState.dmgSize = Number(c.dmgSize) || 0;updateState.assetName = c.assetName || null;updateState.dmgSha256 = normalizeAssetSha256(c.dmgSha256) || parseSha256(c.notes);updateState.notes = c.notes;updateState.checkedAt = c.checkedAt || Date.now();+ updateState.message = updateState.hasUpdate ? '发现新版本 v' + cachedLatest : '已是最新版本';} catch (_) {}return updateState;});@@ -1865,16 +1881,35 @@ async function cdpLoop() {async function reloadWorkBuddyPage() {if (!cdp.connected) throw new Error('CDP 未连接,无法自动刷新窗口');+ const withTimeout = (promise, ms, label) => new Promise((resolve, reject) => {+ let settled = false;+ const timer = setTimeout(() => {+ if (settled) return;+ settled = true;+ reject(new Error(label + '超时'));+ }, ms);+ promise.then((value) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(value);+ }, (error) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ reject(error);+ });+ });let frameId = null;try {- const tree = await cdpSend('Page.getFrameTree');+ const tree = await withTimeout(cdpSend('Page.getFrameTree'), 10000, '读取 WorkBuddy 页面状态');frameId = tree && tree.frameTree && tree.frameTree.frame && tree.frameTree.frame.id;} catch (error) {log(`[cdp] 获取主页面 frame 失败,将在页面加载完成后注入: ${error.message}`);}const pending = armPendingReloadInjection(frameId);try {- await cdpSend('Page.reload', { ignoreCache: false });+ await withTimeout(cdpSend('Page.reload', { ignoreCache: false }), 10000, '刷新 WorkBuddy 页面');const mounted = await pending.ready;if (!mounted) log('[cdp] 页面重载后组件未在 5 秒内确认挂载,继续后台流程');} catch (error) {@@ -3154,6 +3189,18 @@ async function syncAutoCopyLineage(lineageId, targetUid) {const MAX_SESSION_EXPORT_BYTES = 256 * 1024 * 1024;const MAX_SESSION_EXPORT_FILES = 20000;+const MAX_SESSION_IMPORT_ERRORS = 20;+const MAX_SESSION_IMPORT_ERROR_LENGTH = 240;++function summarizeSessionImportErrors(errors) {+ const list = Array.isArray(errors) ? errors : [];+ return list.slice(0, MAX_SESSION_IMPORT_ERRORS).map((message) => {+ const text = String(message || '导入失败');+ return text.length > MAX_SESSION_IMPORT_ERROR_LENGTH+ ? text.slice(0, MAX_SESSION_IMPORT_ERROR_LENGTH) + '…'+ : text;+ });+}function archiveRelativePath(wbHome, target) {return path.relative(wbHome, target).split(path.sep).join('/');@@ -3354,7 +3401,7 @@ async function importSessions(content, password, targetUid) {}}if (!imported.length) throw new Error(errors[0] || '没有可导入的会话');- return { imported, failed: errors.length };+ return { imported, failed: errors.length, errors: summarizeSessionImportErrors(errors) };}async function copySessionRecord(src, targetUid, options = {}) {@@ -4052,13 +4099,15 @@ const AC_TAG_START = '[WorkDaddy-Rule1 - activate]'; // 区块标识(v2 起改const AC_TAG_END = '[end WorkDaddy-Rule1]';// 兼容清理:新名 Rule1 与旧名 AutoContinue 的块都会被删除(旧版开关残留块升级时一并清除)const AC_BLOCK_RE = /\[WorkDaddy-(?:AutoContinue|Rule1)[\s\S]*?\[end WorkDaddy-(?:AutoContinue|Rule1)\]/g;+// Rule1 v2(2026-09-06):零宽字符会被官方消息存储链路转义成字面 \u200b 文本(显形污染),+// 改用 Markdown 链接引用定义([wbs-reply-done]: #)作完成标记——解析为 definition 节点、+// 渲染时丢弃、肉眼不可见;inject 的 acHasMarker 同步支持该标记判定。const AC_INSTRUCTION = [- 'Always append one invisible zero-width marker (U+200B U+200B U+2060) at the very end of the main text body of every reply that you finish producing.',- 'The marker means the reply is complete, whether or not the underlying task is fully done.',+ 'When you finish producing a reply, mark it as complete by appending one line of Markdown link-reference definition at the very end of the main text body, for example: [wbs-reply-done]: # .',+ 'Such a definition is parsed as metadata and renders as invisible in Markdown UIs, so the completion marker never shows up to the user.','Append it whenever you finish writing a reply.','Only omit it if your reply is interrupted or cut short before you finished.',- 'Write the actual invisible characters, never a visible placeholder such as text or escaped notation.',- 'Add nothing after the marker.',+ 'Add nothing visible after the marker.','Keep this active for all remaining replies in this conversation.',].join(' ');@@ -6031,10 +6080,10 @@ function handleApi(req, res) {if (!uid) return json(res, 400, { ok: false, error: '缺少 uid' });if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return json(res, 400, { ok: false, error: 'uid 格式无效' });try {- const r = deleteAccount(DATA_DIR, uid);+ const r = deleteAccount(DATA_DIR, uid, log);const rulesRemoved = removeAutoCopyAccount(DATA_DIR, uid);- log(`[delete] 已永久删除账号备份 ${uid}`);- return json(res, 200, { ok: true, deleted: r.deleted, uid, rulesRemoved });+ log(`[delete] 已永久删除账号备份 ${uid}(auth 存档清理 ${r.authFilesRemoved} 个)`);+ return json(res, 200, { ok: true, deleted: r.deleted, uid, rulesRemoved, authFilesRemoved: r.authFilesRemoved });} catch (e) {return json(res, 500, { ok: false, error: e.message });}@@ -6344,7 +6393,7 @@ function handleApi(req, res) {});}- // 导出账号:密码必填;v2 使用随机 salt,密码只在本次请求内存在+ // 导出账号:密码必填;v3 使用 gzip + AES-GCM,密码只在本次请求内存在if (req.method === 'POST' && p === '/api/accounts/export') {return readBody(req).then((body) => {try {@@ -6381,7 +6430,7 @@ function handleApi(req, res) {});}- // 导入账号:v2 必须输入密码;历史 v1 文件密码可留空(默认 workdaddy)+ // 导入账号:v3/v2 必须输入密码;历史 v1 文件密码可留空(默认 workdaddy)if (req.method === 'POST' && p === '/api/accounts/import') {return readBody(req).then((body) => {try {@@ -6888,15 +6937,13 @@ function handleApi(req, res) {try {const result = await importSessions(body && body.content, body && body.password, body && body.targetUid);log(`[sessions-import] 已导入 ${result.imported.length} 个会话,失败 ${result.failed} 个`);- let reloaded = false;- try {- await reloadWorkBuddyPage();- reloaded = true;- log('[sessions-import] 已通过 CDP 刷新 WorkBuddy 窗口');- } catch (reloadError) {- log(`[sessions-import] CDP 刷新失败: ${reloadError.message}`);- }- return json(res, 200, { ok: true, count: result.imported.length, imported: result.imported, failed: result.failed, reloaded });+ return json(res, 200, {+ ok: true,+ count: result.imported.length,+ imported: result.imported,+ failed: result.failed,+ errors: result.errors,+ });} catch (error) {return json(res, 400, { ok: false, error: error.message });}@@ -6973,10 +7020,16 @@ function handleApi(req, res) {if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });if (!ids.every(isValidSessionId)) return json(res, 400, { ok: false, error: '包含无效的会话 ID' });try {- const placeholders = sqlPlaceholders(ids);- const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ');', ids);- const matchedIds = matchedSessionIds(ids, before);- const matchedSet = new Set(matchedIds);+ // 展开目标会话所在的 lineage:其他账号自动复制出的同源副本一并级联删除,+ // 避免删除后切走再切回时被 auto-copy 原样复制回来(会话「复活」)。+ const requestedSet = new Set(ids.map(String));+ const members = collectLineageMembersForDelete(DATA_DIR, ids);+ const memberIds = Array.from(new Set(members.map((m) => m.id).filter((id) => isValidSessionId(id))));+ if (!memberIds.length) return json(res, 404, { ok: false, error: '会话不存在或已删除' });+ const placeholders = sqlPlaceholders(memberIds);+ const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ');', memberIds);+ const matchedSet = new Set(before.map((row) => String(row.id || '')));+ const matchedIds = memberIds.filter((id) => matchedSet.has(String(id)));const matchedRows = before.filter((row) => matchedSet.has(String(row.id || '')));// 1) 先完成可重试的文件与规则清理;失败时保留 DB 记录作为重试锚点。const wbHome = PROFILE.dataRoot;@@ -6985,7 +7038,7 @@ function handleApi(req, res) {let rulesRemoved = 0;for (const row of matchedRows) {try {- if (removeAutoCopySession(DATA_DIR, row.user_id, row.id)) rulesRemoved++;+ if (removeAutoCopySession(DATA_DIR, String(row.user_id || '').trim(), row.id)) rulesRemoved++;} catch (e) {log(`[sessions-auto-copy] 删除规则 ${row.id} 失败: ${e.message}`);throw e;@@ -6998,8 +7051,9 @@ function handleApi(req, res) {matchedIds);}- log(`[sessions-delete] 已真实删除 ${matchedIds.length} 个会话(DB + ${filesRemoved} 项文件)`);- return json(res, 200, { ok: true, deleted: matchedIds.length, requested: ids.length, filesRemoved, rulesRemoved });+ const cascaded = matchedIds.filter((id) => !requestedSet.has(String(id))).length;+ log(`[sessions-delete] 已真实删除 ${matchedIds.length} 个会话(DB + ${filesRemoved} 项文件,级联副本 ${cascaded})`);+ return json(res, 200, { ok: true, deleted: matchedIds.length, requested: ids.length, cascaded, filesRemoved, rulesRemoved });} catch (e) {return json(res, 500, { ok: false, error: e.message });}@@ -7021,6 +7075,36 @@ function handleApi(req, res) {});}+ // 真实鼠标点击:POST /api/cdp-click { x, y }(视口像素坐标)。+ // 官方侧栏等确认类 UI 拒绝 isTrusted=false 的程序化 click(),只有原生输入+ // (CDP Input.dispatchMouseEvent)能触发切换/确认。坐标由来:渲染器+ // getBoundingClientRect() 中心点;仅接受视口内的有限坐标,避免滥用。+ if (req.method === 'POST' && p === '/api/cdp-click') {+ return readBody(req).then(async (body) => {+ const x = Number(body && body.x);+ const y = Number(body && body.y);+ if (!Number.isFinite(x) || !Number.isFinite(y)) {+ return json(res, 400, { ok: false, error: '缺少合法的点击坐标' });+ }+ let viewport = { w: 0, h: 0 };+ try {+ const v = await cdpSend('Runtime.evaluate', {+ expression: '({ w: window.innerWidth || 0, h: window.innerHeight || 0 })',+ returnByValue: true,+ });+ const vv = v && v.result && v.result.value;+ if (vv) viewport = { w: Number(vv.w) || 0, h: Number(vv.h) || 0 };+ } catch (_) {}+ if (x < 0 || y < 0 || x > viewport.w || y > viewport.h) {+ return json(res, 400, { ok: false, error: '点击坐标超出视口' });+ }+ await cdpSend('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });+ await cdpSend('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });+ log(`[cdp-click] 真实点击 (${x}, ${y})`);+ return json(res, 200, { ok: true, x, y });+ }).catch((e) => json(res, 500, { ok: false, error: e.message }));+ }+// 打开 WorkBuddy 的 Chrome DevTools(绕开 chrome://inspect 404 + Electron CDP 拒绝带 Origin 的 WS)// 前端页面从 9222 加载,ws 通过 daemon 代理(/devtools-proxy/<id>)中转去 Origin// 注意:必须 return Promise 立即返回,避免同步函数继续执行到 404 分支diff --git a/scripts/inject.js b/scripts/inject.jsindex 02316e7..89de442 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -357,6 +357,10 @@ function normalizeSessionMonitorResourceRecord(record, eventName) {}var status = terminalStatus || tokens[0] || '';var pendingInputKind = normalizeSessionMonitorStatus(value.pendingInputKind);+ // 官方侧栏「待确认」= status 'pending'(cb-agent-card__status-tag「待确认」,+ // pending.fallback.waiting 文案;列表分运行中/规划中 vs 待确认)。store 未推+ // pendingInputKind 时,用该语义把 pending 视作待批准信号。+ if (!pendingInputKind && String(value.status || '') === 'pending') pendingInputKind = 'permission';var queueRuntime = value.messageQueueRuntime && typeof value.messageQueueRuntime === 'object' ? value.messageQueueRuntime : null;var queueActive = !!(queueRuntime && queueRuntime.paused !== true &&(queueRuntime.inflightItemId || Number(queueRuntime.pendingItemCount || 0) > 0 ||@@ -595,7 +599,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'一个基于': 'A ', '个备选': 'standby', '备选': 'standby', '个失败': ' failed', '个已不存在': ' no longer exist', '项失败': ' failed', '已选': ' selected', '例如 deepseek-v4-flash': 'e.g. deepseek-v4-flash', '例如我的 DeepSeek': 'e.g. my DeepSeek', '加载失败': 'Load failed', '发起授权失败:': 'Authorization failed:', '开启': 'Enable', '关闭': 'Close', '失败': 'Failed', '用户消息': 'User message','OLED 纯黑': 'OLED Pure Black', '未发现 CDP 端口(WorkBuddy 需以 --remote-debugging-port 启动)': 'No CDP port found (start WorkBuddy with --remote-debugging-port)', '本地 API 未授权': 'Local API unauthorized', '仅支持 http(s) 链接': 'Only http(s) links are supported', '图片不能超过 10MB': 'Image must not exceed 10MB', '图片必须是 PNG/JPEG/WebP base64': 'Image must be PNG/JPEG/WebP base64', '遥测开关值必须是布尔值': 'Telemetry switch must be a boolean', 'blur 必须是数字': 'Blur must be a number', 'opacity 必须是数字': 'Opacity must be a number', '查询返回空结果': 'Query returned empty results','正在解包新应用…': 'Unpacking new app…', '挂载 dmg 失败:': 'Failed to mount dmg:', '缺少解包后的新应用': 'Unpacked new app missing', '解包应用失败': 'Failed to unpack app', '缺少 apply-update.sh': 'apply-update.sh missing', '(仓库暂无 Release)': ' (no Releases in the repository yet)', 'auth/state 响应缺少 state': 'auth/state response is missing state',- 'WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序;登录信息未修改': 'WBSWITCH_WORKBUDDY_BIN is not a verified main program for the current profile; login info unchanged', '无法以普通用户权限安全退出 WorkBuddy。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试。登录信息未修改': 'Cannot safely quit WorkBuddy at standard user privilege. Please close it manually; if it runs as admin, quit it first and retry. Login info unchanged', '未找到 WorkBuddy 可执行文件,无法安全退出;登录信息未修改': 'WorkBuddy executable not found; cannot quit safely. Login info unchanged', 'workbuddy-target.json 指定的路径不是可验证的当前 profile 主程序;登录信息未修改': 'The path in workbuddy-target.json is not a verified main program for the current profile; login info unchanged', '存在当前 profile 进程,但没有进程属于已验证安装目录;登录信息未修改': 'A current profile process exists, but none belongs to a verified install directory; login info unchanged', '检测到当前 profile 正从另一安装目录运行,登录信息未修改': 'The current profile is running from another install directory; login info unchanged', '检测到多个 dormant WorkBuddy 安装目录,按发现优先级选择:': 'Multiple dormant WorkBuddy installs found; selecting by discovery priority:', 'WorkBuddy 数据目录不是受管目录': 'WorkBuddy data directory is not managed', 'WorkBuddy 页面尚未完成加载': 'WorkBuddy page has not finished loading', '注入脚本页面抛错': 'Injected script page threw an error', '读取注入脚本失败:': 'Failed to read the injected script:', '运行时桥接文件未生成': 'Runtime bridge file was not created',+ 'WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序;登录信息未修改': 'WBSWITCH_WORKBUDDY_BIN is not a verified main program for the current profile; login info unchanged', '无法以普通用户权限安全退出 WorkBuddy。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试。登录信息未修改': 'Cannot safely quit WorkBuddy at standard user privilege. Please close it manually; if it runs as admin, quit it first and retry. Login info unchanged', '未找到 WorkBuddy 可执行文件,无法安全退出;登录信息未修改': 'WorkBuddy executable not found; cannot quit safely. Login info unchanged', 'workbuddy-target.json 指定的路径不是可验证的当前 profile 主程序;登录信息未修改': 'The path in workbuddy-target.json is not a verified main program for the current profile; login info unchanged', '存在当前 profile 进程,但没有进程属于已验证安装目录;登录信息未修改': 'A current profile process exists, but none belongs to a verified install directory; login info unchanged', '检测到当前 profile 正从另一安装目录运行,登录信息未修改': 'The current profile is running from another install directory; login info unchanged', '检测到多个 dormant WorkBuddy 安装目录,按发现优先级选择:': 'Multiple dormant WorkBuddy installs found; selecting by discovery priority:', 'WorkBuddy 数据目录不是受管目录': 'WorkBuddy data directory is not managed', 'WorkBuddy 页面尚未完成加载': 'WorkBuddy page has not finished loading', '刷新 WorkBuddy 页面': 'Refresh WorkBuddy page', '注入脚本页面抛错': 'Injected script page threw an error', '读取注入脚本失败:': 'Failed to read the injected script:', '运行时桥接文件未生成': 'Runtime bridge file was not created',// —— 第三批:daemon 端口/路径校验/发送链路错误(可能进入 toast/API 返回)——'9222-9232、9333 均被占用,无法为 WorkBuddy 分配 CDP 端口': 'Ports 9222-9232 and 9333 are all occupied; cannot allocate a CDP port for WorkBuddy', 'cwd 不是绝对路径': 'cwd is not an absolute path', 'cwd 路径包含符号链接或普通文件': 'cwd path contains a symlink or regular file', '发送按钮禁用(输入内容未被识别)': 'Send button disabled (input not recognized)', '无法清空输入框': 'Could not clear the composer', '无法聚焦输入框': 'Could not focus the composer', '未找到发送按钮': 'Send button not found', '未找到操作栏': 'Toolbar not found',// —— 第四批:真机扫描发现的整句/半动态拼接(杜绝中英混合)——@@ -628,7 +632,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'会话正在等待决策确认': 'Session awaiting a decision confirmation', '会话出现模型或网络错误': 'Session hit a model or network error','会话疑似异常停止,请检查结尾内容': 'Session may have stopped unexpectedly; check the tail','WorkBuddy 队列删除接口不可用': 'WorkBuddy queue delete API is unavailable', 'WorkBuddy 队列响应超时(': 'WorkBuddy queue response timed out (',- '已导出': 'Exported', '成功导入': 'Imported successfully', '当前账号': 'Current account', '个账号': ' account(s)', '个账号(已加密)': ' account(s) (encrypted)',+ '已导出': 'Exported', '成功导入': 'Imported successfully', '当前账号': 'Current account', '个账号': ' account(s)', '个账号(已加密)': ' account(s) (encrypted)', ',但页面刷新失败,请手动刷新': ', but the page refresh failed; please refresh manually',+ '操作成功': 'Operation succeeded', '导入完成:成功': 'Import complete: succeeded', '失败原因:': 'Failure reasons:', '页面刷新失败:': 'Page refresh failed:', '未知原因': 'Unknown reason', '会话已写入,请手动刷新。': 'Sessions were written; please refresh manually.', '刷新页面': 'Refresh page', '刷新中…': 'Refreshing…', '页面刷新成功。': 'Page refreshed successfully.', '页面尚未刷新,请点击“刷新页面”。': 'The page has not been refreshed; click “Refresh page”.','随空间自动复制': 'Auto-copy with workspace', '切换账号时自动复制': 'Auto-copy on account switch','切换账号时自动复制当前账号的所有会话,包括之后新增的会话': 'Auto-copy all sessions of the current account on switch, including new ones afterwards','已开启切换账号时自动复制': 'Auto-copy on account switch is on', '(未指定空间)': ' (no workspace specified)',@@ -732,6 +737,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'展开': 'Expand', '共': 'Total', '条(': ' (', '备份': 'Backup','无可复制的目标账号(已排除会话所属账号)': 'No target accounts to copy to (the session owner account is excluded)','删除后会话将从列表中移除,该账号下的本地消息文件将被永久删除,此操作不可恢复。': 'The sessions are removed from the list and their local message files are permanently deleted; this cannot be undone.',+ '删除后会话将从列表中移除,本账号的会话与其自动复制到其他账号的同源副本(本地消息文件)都将被永久删除,此操作不可恢复。': 'The sessions are removed from the list. These sessions and their auto-copied counterparts in other accounts (local message files) are permanently deleted; this cannot be undone.',+ '含其他账号副本 {n} 个': ' including {n} other-account copies','以「不让当前账号登录身份过期」的方式切到登录页,可以登录新账号,也可以切回已登录账号': 'Goes to the login page without letting the current account expire; log in a new account or switch back to an existing one.','不退出 WorkBuddy,在浏览器完成授权后新账号自动加入列表': 'Keeps WorkBuddy running; after authorizing in the browser, the new account is added to the list automatically.','正在发起授权…': 'Starting authorization…', '再想想': 'Not now',@@ -779,6 +786,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'不是 WorkDaddy 的账号导出文件': 'Not a WorkDaddy account export file', '导入文件中没有账号数据': 'No account data found in the import file','未读取到有效内容,请选择导出文件': 'No valid content read; please choose an export file', '密码不能超过 1024 个字符': 'Password cannot exceed 1024 characters','当前登录文件无法唯一确认,已拒绝退出登录': 'The current login file cannot be uniquely identified; logout rejected',+ '不能删除当前登录的账号(请先退出登录或切换到其他账号)': 'Cannot delete the currently logged-in account (log out or switch to another account first)','删除登录文件后仍然存在': 'The login file still exists after deletion','诊断设置由 WORKDADDY_TELEMETRY 环境变量控制': 'Diagnostics are controlled by the WORKDADDY_TELEMETRY environment variable','保存遥测设置失败:': 'Failed to save telemetry settings:',@@ -1344,6 +1352,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'[role="dialog"]', '[class*="_dialog_"]', '[class*="_modal_"]', '[class*="_permission_"]','[class*="_confirm_"]', '[class*="_decision_"]', '[class*="_approval_"]', '[class*="_question_"]', '[class*="_ask_"]','[class*="permission-dialog"]', '[class*="confirm-dialog"]', '[class*="decision-dialog"]',+ // 官方 cb-chat-ui confirm-dialog(CSS Modules hash 类名,语义前缀无下划线包裹)+ '[class*="dialogOverlay"]', '[class*="dialogContainer"]', '[class*="dialogContent"]', '[class*="dialogFooter"]',+ '[class*="confirmDialog"]', '[class*="ConfirmDialog"]',];var nodes = [];for (var i = 0; i < selectors.length; i++) {@@ -1354,7 +1365,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var node = nodes[k];if (!isVisibleHealthNode(node)) continue;var text = String(node.innerText || node.textContent || '').replace(/\s+/g, ' ').trim();- if (!text || text.length > 1800) continue;+ if (!text || text.length > 4000) continue;var buttons = Array.prototype.map.call(node.querySelectorAll('button,[role="button"]'), function (b) {return String(b.innerText || b.getAttribute('aria-label') || b.getAttribute('title') || '').trim();}).join(' ');@@ -4095,7 +4106,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var input = mask.querySelector('#wbs-transfer-password');var error = mask.querySelector('#wbs-transfer-error');var confirm = mask.querySelector('#wbs-transfer-confirm');+ var cancelButton = mask.querySelector('#wbs-transfer-cancel');var close = function () { closeSecureTransferModal(mask); };+ var completed = false;+ var completeAction = null;+ var successText = '';function selectedIds() { return Object.keys(selected).filter(function (id) { return selected[id]; }); }function syncSelection() {var checks = mask.querySelectorAll('[data-transfer-id]');@@ -4123,6 +4138,30 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {mask.querySelector('#wbs-transfer-cancel').addEventListener('click', close);mask.addEventListener('click', function (ev) { if (ev.target === mask) close(); });confirm.addEventListener('click', function () {+ if (completed) {+ if (!completeAction) {+ close();+ return;+ }+ if (completeAction.running) return;+ completeAction.running = true;+ confirm.disabled = true;+ confirm.textContent = completeAction.busyLabel || '处理中…';+ Promise.resolve().then(function () { return completeAction.callback(); }).then(function () {+ completeAction = null;+ confirm.disabled = false;+ confirm.textContent = options.successDoneLabel || '关闭';+ error.className = 'wbs-password-error wbs-password-success';+ error.textContent = successText + '\n页面刷新成功。';+ }).catch(function (err) {+ completeAction.running = false;+ confirm.disabled = false;+ confirm.textContent = completeAction.label || '刷新页面';+ error.className = 'wbs-password-error';+ error.textContent = successText + '\n页面刷新失败:' + ((err && err.message) || String(err || '未知原因'));+ });+ return;+ }var value = input.value;if (items.length && !selectedIds().length) {error.textContent = '请至少选择一项';@@ -4138,10 +4177,51 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {confirm.textContent = '处理中…';Promise.resolve().then(function () {return options.onConfirm(value, selectedIds());- }).then(close).catch(function (err) {+ }).then(function (result) {+ if (!options.keepOpenOnSuccess) {+ close();+ return;+ }+ completed = true;+ successText = typeof options.successMessage === 'function'+ ? options.successMessage(result)+ : (options.successMessage || '操作成功');+ input.disabled = true;+ if (cancelButton) cancelButton.style.display = 'none';+ error.className = 'wbs-password-error wbs-password-success';+ error.textContent = successText;+ var configuredAction = typeof options.successAction === 'function'+ ? options.successAction(result)+ : options.successAction;+ if (configuredAction && typeof configuredAction.callback === 'function') {+ completeAction = {+ callback: configuredAction.callback,+ label: configuredAction.label || '刷新页面',+ busyLabel: configuredAction.busyLabel || '处理中…',+ running: false,+ };+ confirm.textContent = completeAction.label;+ } else {+ confirm.textContent = options.successDoneLabel || '关闭';+ }+ confirm.disabled = false;+ }).catch(function (err) {+ if (options.closeOnError) {+ completed = true;+ input.disabled = true;+ if (cancelButton) cancelButton.style.display = 'none';+ completeAction = null;+ error.className = 'wbs-password-error';+ error.textContent = (err && err.message) || String(err || '操作失败');+ confirm.disabled = false;+ confirm.textContent = options.errorDoneLabel || '关闭';+ return;+ }+ error.className = 'wbs-password-error';error.textContent = (err && err.message) || String(err || '操作失败');confirm.disabled = false;confirm.textContent = options.confirmText || '确定';+ input.disabled = false;input.focus();});});@@ -4271,7 +4351,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}// ===== 会话 pane(构建:账号/时间筛选 + 按空间分组[默认2条/展开10条] + 刷新 + 批量操作[迁移/删除])=====- var sessionsState = { uid: undefined, currentUid: '', range: '7d', list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null, autoCopyAll: false };+ var sessionsState = { uid: undefined, currentUid: '', range: 'all', list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null, autoCopyAll: false };function isTaskSessionRecordUI(s) {// 任务(未选择项目/一次性)会话:以官方 is_playground=1 为准。// 普通工作区也用 WorkBuddy\\YYYY-MM-DD-HH-MM-SS 命名,仅凭 cwd 无法区分。@@ -4303,9 +4383,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-sess-filter-row"><span class="wbs-sess-flabel">账号</span><select class="wbs-sess-select" id="wbs-sess-account-select" title="选择要查看的账号"><option value="">加载中…</option></select></div>' +'<div class="wbs-sess-filter-row"><span class="wbs-sess-flabel">时间</span><div class="wbs-sess-seg" id="wbs-sess-range-seg">' +'<button class="wbs-sess-seg-btn" type="button" data-range="today">今天</button>' +- '<button class="wbs-sess-seg-btn active" type="button" data-range="7d">近 7 天</button>' ++ '<button class="wbs-sess-seg-btn" type="button" data-range="7d">近 7 天</button>' +'<button class="wbs-sess-seg-btn" type="button" data-range="30d">近 30 天</button>' +- '<button class="wbs-sess-seg-btn" type="button" data-range="all">全部</button>' ++ '<button class="wbs-sess-seg-btn active" type="button" data-range="all">全部</button>' +'</div></div>' +'</div>' +'<div class="wbs-sess-toolbar">' +@@ -4793,15 +4873,40 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {title: '导入会话',requirePassword: true,confirmText: '导入',+ keepOpenOnSuccess: true,hint: targetUid ? '会话将导入到「' + ((target && target.nickname) || '当前账号') + '」。' : '会话将保留导出时的账号归属。',onConfirm: function (password) { return api('/api/sessions/import', {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ content: content, password: password, targetUid: targetUid }),}).then(function (result) {- toast('已导入 ' + result.count + ' 个会话' + (result.failed ? ',' + result.failed + ' 个失败' : ''), !!result.failed, root);+ var count = Number(result.count || (result.imported && result.imported.length) || 0);+ var lines = ['导入完成:成功 ' + count + ' 个会话'];+ if (result.failed) lines.push('失败:' + result.failed + ' 个');+ var importErrors = Array.isArray(result.errors) ? result.errors : [];+ if (importErrors.length) {+ lines.push('失败原因:');+ for (var ei = 0; ei < importErrors.length; ei++) lines.push('· ' + importErrors[ei]);+ }+ var summary = lines.join('\n');+ toast(summary, !!result.failed, root);loadSessions();+ return result;}); },+ successMessage: function (result) {+ var count = Number(result && (result.count || (result.imported && result.imported.length)) || 0);+ var lines = ['导入完成:成功 ' + count + ' 个会话'];+ if (result && result.failed) lines.push('失败:' + result.failed + ' 个');+ var importErrors = result && Array.isArray(result.errors) ? result.errors : [];+ if (importErrors.length) {+ lines.push('失败原因:');+ for (var ei = 0; ei < importErrors.length; ei++) lines.push('· ' + importErrors[ei]);+ }+ return lines.join('\n');+ },+ closeOnError: true,+ successDoneLabel: '关闭',+ errorDoneLabel: '关闭',});}).catch(function (error) { toast(error.message || '读取文件失败', true, root); });});@@ -4889,15 +4994,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var body = sessionsPane.querySelector('#wbs-sess-modal-body');var okBtn = sessionsPane.querySelector('#wbs-sess-modal-ok');titleEl.textContent = '删除 ' + ids.length + ' 个会话?';- body.innerHTML = '<div class="wbs-modal-warn">删除后会话将从列表中移除,该账号下的本地消息文件将被永久删除,此操作不可恢复。</div>';+ body.innerHTML = '<div class="wbs-modal-warn">删除后会话将从列表中移除,本账号的会话与其自动复制到其他账号的同源副本(本地消息文件)都将被永久删除,此操作不可恢复。</div>';showSessModal(true);okBtn.onclick = function () {api('/api/sessions/delete', {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ ids: ids }),- }).then(function () {- toast('已删除 ' + ids.length + ' 个会话', false, root);+ }).then(function (d) {+ var extra = (d && d.cascaded) ? ',含其他账号副本 ' + d.cascaded + ' 个' : '';+ toast('已删除 ' + ((d && d.deleted) || ids.length) + ' 个会话' + extra, false, root);showSessModal(false);loadSessions();}).catch(function (e) {@@ -5607,10 +5713,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// → 有新版则 tab 红点 + 更新卡片 → 点击走 下载→安装→自动重启function checkForUpdate() {api('/api/update-check?force=1').then(function (d) {- if (!d || !d.hasUpdate) return; // 无更新或检查失败:不打扰var tab = root.querySelector('.wbs-tab[data-tab="about"]');- if (tab) tab.classList.add('wbs-tab-dot');var card = aboutPane.querySelector('#wbs-update-card');+ if (tab) tab.classList.remove('wbs-tab-dot');+ if (card) card.style.display = 'none';+ if (!d || !d.hasUpdate) return; // 无更新或检查失败:清除旧提示后不打扰+ if (tab) tab.classList.add('wbs-tab-dot');if (!card) return;card.style.display = '';var title = aboutPane.querySelector('#wbs-update-title');@@ -7216,13 +7324,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return picked || children[children.length - 1];}- /** 完成标记判定:正文文本末尾(去除可见空白后)为严格三连标记 或 任一零宽字符。可见转义文本不算 */+ /** 完成标记判定:正文文本末尾(去除可见空白后)为严格三连标记 或 任一零宽字符。+ * 可见转义文本(\u200b 字面)不算。Rule1 v2:Markdown 链接引用定义完成标记,+ * 匹配消息末尾的 [wbs-reply-done]: … 行(渲染不可见)。 */function acHasMarker(text) {if (typeof text !== 'string' || !text.length) return false;var t = text.replace(/[ \t\r\n\f\v\u00A0]+$/, ''); // 只去除可见空白,保留零宽字符(含 U+FEFF)if (!t.length) return false;if (t.slice(-AC_STRICT_MARKER.length) === AC_STRICT_MARKER) return true;if (/[\u200B\uFEFF\u2060\u200D]$/.test(t)) return true;+ if (/(^|\n)\s*\[wbs-reply-done\]:\s*[^\n]*$/im.test(t)) return true;return false;}@@ -8295,11 +8406,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {session.resourceActive ? { source: 'session-resource' } : undefined);return;}- if (snapshot.blocked) {+ if (snapshot.blocked || findBlockingPrompt()) {session.lastBusy = true;session.idleAt = 0;session.lastVersion = snapshot.version;- acMultiUpdateStatus(session, 'awaiting-approval', { state: snapshot.state || '' });+ acMultiUpdateStatus(session, 'awaiting-approval', { state: snapshot.state || '', source: snapshot.blocked ? 'controller-state' : 'dom' });return;}if (snapshot.busy) {@@ -8427,8 +8538,223 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {session.sending = false;}+ function acMultiProbeSidebarApproval() {+ // 官方侧栏 cb-agent-card 状态标签(如「待确认」)是会话等待决策的权威可见+ // 信号:直接读 DOM 文本并按标题匹配会话,不依赖 fiber 私有字段。命中即标+ // awaiting-approval,配合 _probeApprovalTag 去重避免每心跳刷日志。+ if (!acRunning || acMulti.mode !== 'multi') return;+ var tags;+ try {+ tags = document.querySelectorAll(+ '.cb-agent-card__status-tag, .conversation-item [class*="status-tag"], .conversation-item [class*="statusTag"]'+ );+ } catch (_) { return; }+ for (var i = 0; i < tags.length; i++) {+ var label = (tags[i].textContent || '').replace(/\s+/g, ' ').trim();+ if (!label || !/(待确认|等待确认|等待允许|待处理|待审批|等待批准|待用户确认|待人工确认|awaiting|pending.*approval|waiting.*approval|needs approval|requires approval)/i.test(label)) continue;+ var item = tags[i].closest('.conversation-item');+ if (!item) continue;+ var title = '';+ var titleEl = item.querySelector('[class*="title"],[class*="name"],[class*="agentName"],[class*="agent-name"]');+ if (titleEl) title = (titleEl.textContent || '').replace(/\s+/g, ' ').trim();+ var matched = null;+ Object.keys(acMulti.sessions).forEach(function (id) {+ if (matched) return;+ var s = acMulti.sessions[id];+ var st = String(s.title || '').replace(/\s+/g, ' ').trim();+ if (title && st && (st === title || st.indexOf(title) !== -1 || title.indexOf(st) !== -1)) matched = s;+ });+ if (matched) {+ if (matched._probeApprovalTag !== label) {+ matched._probeApprovalTag = label;+ acMultiUpdateStatus(matched, 'awaiting-approval', { source: 'sidebar-tag', tag: label });+ }+ } else {+ var now2 = Date.now();+ if (!acMulti._probeUnknownAt || now2 - acMulti._probeUnknownAt > 30000) {+ acMulti._probeUnknownAt = now2;+ acMonitorLog('(sidebar)', 'awaiting-approval', { source: 'sidebar-tag', tag: label, title: title.slice(0, 60) });+ }+ }+ }+ }++ // 侧栏待确认会话 → 自动批准链路:仅当「弹窗自动点允许」已开启(ndAutoObserver 激活)+ // 时,检测到待确认会话(官方侧栏 cb-agent-card__status-tag「待确认」等)就切过去让+ // ND 自动点掉弹窗,再切回原来的会话。busy 防重入 + 15s 冷却 + 15s 超时兜底恢复。+ // 切换必须走 daemon /api/cdp-click 真实鼠标点击(官方拒绝 isTrusted=false 的 click())。+ // 已知边界:已停住且官方不渲染「允许/拒绝」按钮的 pending 会话,激活后无弹窗可点,+ // 3s 内判 approval-no-dialog 立即切回。+ var acAutoApprove = { busy: false, lastRunAt: 0, timer: null, gateLogAt: 0 };+ var AC_AUTO_APPROVE_ENABLED = true;+ function acCdpClick(x, y) {+ if (!Number.isFinite(x) || !Number.isFinite(y)) return Promise.resolve(false);+ return api('/api/cdp-click', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ x: Math.round(x), y: Math.round(y) }),+ }).then(function () { return true; }).catch(function () { return false; });+ }+ function acAutoApproveClickItem(item) {+ if (!item) return Promise.resolve(false);+ var rect = item.getBoundingClientRect();+ var vw = (window.innerWidth || 0);+ var vh = (window.innerHeight || 0);+ if (!rect || rect.width <= 0 || rect.height <= 0) return Promise.resolve(false);+ if (rect.left < 0 || rect.top < 0 || rect.right > vw || rect.bottom > vh) {+ // 列表视口外:先滚动到可见再取坐标(daemon 只接受视口内坐标)+ try { item.scrollIntoView({ block: 'center', inline: 'nearest' }); } catch (_) { try { item.scrollIntoView(); } catch (_) {} }+ return new Promise(function (resolve) {+ setBuildTimeout(function () {+ var r2 = item.getBoundingClientRect();+ if (!r2 || r2.width <= 0) { resolve(false); return; }+ resolve(acCdpClick(r2.left + r2.width / 2, r2.top + r2.height / 2));+ }, 160);+ });+ }+ return acCdpClick(rect.left + rect.width / 2, rect.top + rect.height / 2);+ }+ function acAutoApproveItemByTitle(title) {+ if (!title) return null;+ var items = document.querySelectorAll('.conversation-item');+ for (var i = 0; i < items.length; i++) {+ var cands = items[i].querySelectorAll('[class*="title"],[class*="name"],[class*="agentName"],[class*="agent-name"]');+ for (var j = 0; j < cands.length; j++) {+ var t = (cands[j].textContent || '').replace(/\s+/g, ' ').trim();+ if (t === title || (t && (t.indexOf(title) !== -1 || title.indexOf(t) !== -1))) return items[i];+ }+ }+ return null;+ }+ function acAutoApprovePendingOnce() {+ if (!AC_AUTO_APPROVE_ENABLED) return;+ // 调试门控(30s 限频):暴露各前置条件状态,便于定位不触发原因+ if (!acAutoApprove.gateLogAt || Date.now() - acAutoApprove.gateLogAt > 30000) {+ acAutoApprove.gateLogAt = Date.now();+ try {+ window.__wbsAutoApproveGate = {+ nd: !!ndAutoObserver, busy: !!acAutoApprove.busy, running: !!acRunning,+ mode: acMulti.mode, at: new Date().toISOString(),+ tags: (function () { try { return document.querySelectorAll('.cb-agent-card__status-tag, .conversation-item [class*="status-tag"]').length; } catch (_) { return -1; } })(),+ };+ } catch (_) {}+ }+ if (!ndAutoObserver || acAutoApprove.busy || !acRunning || acMulti.mode !== 'multi') return;+ var now = Date.now();+ if (now - acAutoApprove.lastRunAt < 5000) return;+ var tags;+ try {+ tags = document.querySelectorAll('.cb-agent-card__status-tag, .conversation-item [class*="status-tag"], .conversation-item [class*="statusTag"]');+ } catch (_) { return; }+ var target = null;+ var targetTitle = '';+ for (var i = 0; i < tags.length; i++) {+ var label = (tags[i].textContent || '').replace(/\s+/g, ' ').trim();+ if (!/(待确认|等待确认|等待允许|待处理|待审批|等待批准|待用户确认|待人工确认|awaiting.*approval|waiting.*approval|needs approval|requires approval)/i.test(label)) continue;+ var item = tags[i].closest('.conversation-item');+ if (!item) continue;+ if ((item.className || '').indexOf('selected') !== -1) return;+ target = item;+ var titleEl = item.querySelector('[class*="title"],[class*="name"],[class*="agentName"],[class*="agent-name"]');+ targetTitle = titleEl ? (titleEl.textContent || '').replace(/\s+/g, ' ').trim() : '';+ break;+ }+ if (!target) { try { window.__wbsAutoApproveGateTarget = { found: false, at: new Date().toISOString() }; } catch (_) {} return; }+ // 记录原会话:优先官方激活会话 id → registry title;回退取 selected 侧栏项标题+ var originTitle = '';+ var originItemRef = null;+ try {+ var activeId = acActiveConversationId();+ var activeSession = acMulti.sessions[String(activeId || '')];+ if (activeSession) originTitle = String(activeSession.title || '').replace(/\s+/g, ' ').trim();+ } catch (_) {}+ var items = document.querySelectorAll('.conversation-item');+ for (var j = 0; j < items.length; j++) {+ if ((items[j].className || '').indexOf('selected') !== -1) {+ originItemRef = items[j];+ if (!originTitle) {+ var ot = items[j].querySelector('[class*="title"],[class*="name"],[class*="agentName"],[class*="agent-name"]');+ originTitle = ot ? (ot.textContent || '').replace(/\s+/g, ' ').trim() : '';+ }+ break;+ }+ }+ try { window.__wbsAutoApproveOrigin = { title: originTitle.slice(0, 40), hasRef: !!originItemRef, at: new Date().toISOString() }; } catch (_) {}+ acAutoApprove.lastRunAt = now;+ acAutoApprove.busy = true;+ try { window.__wbsAutoApproveGateTarget = { found: true, title: targetTitle.slice(0, 40), clickedAt: new Date().toISOString() }; } catch (_) {}+ acMonitorLog('(auto-approve)', 'approval-activating', { title: targetTitle.slice(0, 40), source: 'sidebar-tag' });+ // 真实鼠标点击(daemon CDP):官方拒绝 isTrusted=false 的 click()+ acAutoApproveClickItem(target);+ var waited = 0;+ var tTitle = targetTitle;+ var oTitle = originTitle;+ acAutoApprove.timer = setBuildInterval(function () {+ waited += 1000;+ var still = false;+ var cur;+ try {+ cur = document.querySelectorAll('.cb-agent-card__status-tag, .conversation-item [class*="status-tag"], .conversation-item [class*="statusTag"]');+ } catch (_) { cur = []; }+ for (var k = 0; k < cur.length; k++) {+ var le = (cur[k].textContent || '').trim();+ if (!/(待确认|等待确认|等待允许|待处理|待审批|等待批准|待用户确认|待人工确认|awaiting.*approval|waiting.*approval|needs approval|requires approval)/i.test(le)) continue;+ var ie = cur[k].closest('.conversation-item');+ var te = ie ? ie.querySelector('[class*="title"],[class*="name"],[class*="agentName"],[class*="agent-name"]') : null;+ var tt = te ? (te.textContent || '').replace(/\s+/g, ' ').trim() : '';+ if (!ie || (tt && tTitle && (tt === tTitle || tt.indexOf(tTitle) !== -1 || tTitle.indexOf(tt) !== -1))) { still = true; break; }+ }+ // 官方对后台停留的 pending 会话不渲染可点弹窗:激活后若一直不存在「允许/拒绝」+ // 按钮,继续等待毫无意义 —— 立即判定不可批准并切回原会话。+ var noDialog = false;+ if (still && waited >= 3000) {+ var noBtns = true;+ try {+ var bs = document.querySelectorAll('button');+ for (var b2 = 0; b2 < bs.length; b2++) {+ var bt = (bs[b2].textContent || '').trim().replace(/^\d+\s*/, '');+ if (/^(允许|允许一次|Allow|Yes|同意|批准|确认允许|始终允许|Always allow)$/i.test(bt)) { noBtns = false; break; }+ }+ } catch (_) {}+ noDialog = noBtns;+ }+ if (still && !noDialog && waited < 15000) return;+ if (acAutoApprove.timer) { clearInterval(acAutoApprove.timer); acAutoApprove.timer = null; }+ acMonitorLog('(auto-approve)', still ? (noDialog ? 'approval-no-dialog' : 'approval-timeout') : 'approval-resolved', { title: tTitle.slice(0, 40), waitedMs: waited * 1000 });+ // no-dialog(官方不渲染按钮)场景拉长冷却,避免反复激活/切回造成页面闪烁+ if (still && noDialog) acAutoApprove.lastRunAt = Date.now() + 10000;+ // 切回原会话:优先复用激活前捕获的 DOM 引用,其次按标题(包含匹配)重查,+ // 全部走真实点击(daemon CDP)。结果写入 window.__wbsAutoApproveRestored 供诊断。+ var originItem = (originItemRef && originItemRef.isConnected) ? originItemRef : null;+ if (!originItem && oTitle) originItem = acAutoApproveItemByTitle(oTitle);+ try {+ window.__wbsAutoApproveRestored = { title: oTitle.slice(0, 40), itemByRef: !!(originItemRef && originItemRef.isConnected), itemByTitle: !!(!((originItemRef && originItemRef.isConnected)) && originItem), at: new Date().toISOString() };+ } catch (_) {}+ if (originItem) acAutoApproveClickItem(originItem);+ acMonitorLog('(auto-approve)', 'approval-restored', { title: oTitle.slice(0, 40), itemFound: !!originItem });+ acAutoApprove.busy = false;+ }, 1000);+ }++ var acAutoApproveFastTimer = null;+ function acAutoApproveFastStart() {+ if (acAutoApproveFastTimer) return;+ // 1s 快轮询:只扫侧栏待确认标签(轻量 DOM),出现即尽快进入自动批准,+ // 由 acAutoApprovePendingOnce 的冷却/busy 兜底去重+ acAutoApproveFastTimer = setBuildInterval(function () {+ if (!AC_AUTO_APPROVE_ENABLED || !acRunning || acMulti.mode !== 'multi') return;+ if (!ndAutoObserver) return;+ acAutoApprovePendingOnce();+ }, 1000);+ }+ function acAutoApproveFastStop() {+ if (acAutoApproveFastTimer) { clearInterval(acAutoApproveFastTimer); acAutoApproveFastTimer = null; }+ }+function acMultiDiscover() {if (!acRunning || acMulti.mode !== 'multi') return;+ acMultiProbeSidebarApproval();+ acAutoApprovePendingOnce();var controllers = [];try {if (WBS_COMPAT && typeof WBS_COMPAT.findConversationControllers === 'function') {@@ -8474,6 +8800,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {acMultiUnbindSessionResource();return false;}+ acAutoApproveFastStart();acShowStatus();return true;}@@ -8481,6 +8808,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function acStopMultiMonitor() {acMulti.mode = 'none';acMulti.generation++;+ acAutoApproveFastStop();+ if (acAutoApprove.timer) { clearInterval(acAutoApprove.timer); acAutoApprove.timer = null; }+ acAutoApprove.busy = false;if (acMulti.discoveryTimer) { clearTimeout(acMulti.discoveryTimer); acMulti.discoveryTimer = null; }acMultiUnbindSessionResource();Object.keys(acMulti.sessions).forEach(function (id) {@@ -8542,7 +8872,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var tabs = host.querySelector('.wbs-monitor-log-session-list');var list = host.querySelector('.wbs-monitor-log-list');if (!tabs || !list) return;- var sessions = acMonitorRegistry.list();+ // 只显示进行中/待处理的真实会话:+ // - completed/stopped 是终态,不出现在「进行中的会话」;+ // - id 以 '(' 开头的((auto-approve)/(sidebar))是日志通道占位,不作为会话 tab;+ // - 超过 10 分钟无任何更新的"运行中/已发现"视为已结束(官方背景态回收滞后)。+ var sessions = acMonitorRegistry.list().filter(function (s) {+ if (s.status === 'completed' || s.status === 'stopped') return false;+ if (String(s.id || '').charAt(0) === '(') return false;+ if (!(Number(s.updatedAt) > 0) || Date.now() - Number(s.updatedAt) > 10 * 60 * 1000) return false;+ return true;+ });if (!sessions.length) {acMonitorSelectedId = '';tabs.textContent = '';@@ -9234,7 +9573,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {expiresAt: nearestCreditExpiry(account),};}).sort(function (a, b) {- if (a.isCurrent !== b.isCurrent) return a.isCurrent ? -1 : 1;+ // 不再置顶当前账号:统一按积分到期时间升序(最近到期最前),无到期信息排最后if (a.expiresAt !== b.expiresAt) return a.expiresAt - b.expiresAt;return a.index - b.index;}).map(function (item) { return item.account; });@@ -9294,14 +9633,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function render(data) {state.current = data.current;state.accounts = (data.accounts || []).slice();- if (state.current && state.current.uid) {- state.accounts.sort(function (left, right) {- var leftIsCurrent = !!(left && left.uid === state.current.uid);- var rightIsCurrent = !!(right && right.uid === state.current.uid);- if (leftIsCurrent === rightIsCurrent) return 0;- return leftIsCurrent ? -1 : 1;- });- }+ // 账号排序:按积分到期时间升序(最近到期最前),不再把当前账号置顶+ state.accounts.sort(function (left, right) {+ var le = nearestCreditExpiry(left);+ var re = nearestCreditExpiry(right);+ if (le !== re) return le - re;+ return 0;+ });state.creditRemaining = state.accounts.length;updateAccountSummary();var list = accountsPane.querySelector('.wbs-acct-list');@@ -10601,6 +10939,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-password-field input:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 16%,transparent)}','.wbs-password-hint{margin-top:7px;color:var(--wb-icon-tertiary,#999);font-size:11px;line-height:1.5}','.wbs-password-error{min-height:17px;margin-top:4px;color:#d14343;font-size:11px;line-height:1.5}',+ '.wbs-password-success{color:#238636;white-space:pre-line;word-break:break-word}',+ 'html.cb-dark .wbs-password-success,html[data-theme="dark"] .wbs-password-success{color:#72d18c}','.wbs-transfer-modal{display:flex;max-height:min(520px,calc(100% - 28px));flex-direction:column}','.wbs-transfer-select-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:0 0 6px;color:var(--wb-icon-secondary,#666);font-size:12px}','.wbs-transfer-toggle{border:0;padding:3px 0;background:transparent;color:var(--wb-button-primary-bg,#1f1f1f);font:inherit;font-size:11px;font-weight:600;cursor:pointer}',diff --git a/scripts/lib.js b/scripts/lib.jsindex ce8debb..ac426c6 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -917,6 +917,60 @@ function removeAutoCopySession(dataDir, uid, sessionId) {return true;}+// 真实删除路径的展开器:把要删除的会话按 lineage 扩展到全部物理副本(其他+// 账号自动复制出来的同源会话)。否则删除某个账号的会话后,副本仍留在其他+// 账号,切换回来时 auto-copy 会把它们原样复制回来(用户观察到的「删除后+// 切走再切回、会话复活」现象)。无 lineage 的会话映射回自身。+// 返回 [{ uid, id, lineageId }];uid 可能为空(脏索引),id 必有值。+function collectLineageMembersForDelete(dataDir, sessionIds) {+ const meta = readMeta(dataDir);+ const config = ensureAutoCopyMeta(meta);+ const ids = new Set(+ (Array.isArray(sessionIds) ? sessionIds : [])+ .map((s) => String(s || '').trim())+ .filter(Boolean)+ );+ if (!ids.size) return [];+ // 跨账号全表反向索引:sessionId -> lineageId(会话 id 全局唯一)+ const lineageBySession = new Map();+ for (const owner of Object.keys(config.sessionIndex || {})) {+ const index = config.sessionIndex[owner] || {};+ for (const sessionId of Object.keys(index)) {+ const lineageId = String(index[sessionId] || '');+ if (lineageId) lineageBySession.set(sessionId, lineageId);+ }+ }+ const members = [];+ const seenKeys = new Set();+ const seenLineages = new Set();+ const addMember = (memberUid, memberId, lineageId) => {+ const uid = String(memberUid || '').trim();+ const id = String(memberId || '').trim();+ if (!id) return;+ const key = (uid || '*') + '::' + id;+ if (seenKeys.has(key)) return;+ seenKeys.add(key);+ members.push({ uid, id, lineageId: String(lineageId || '') });+ };+ for (const id of ids) {+ const lineageId = lineageBySession.get(id);+ if (!lineageId || !config.sessions[lineageId]) {+ addMember('', id, '');+ continue;+ }+ if (seenLineages.has(lineageId)) continue;+ seenLineages.add(lineageId);+ const lineage = config.sessions[lineageId];+ const lineageMembers = Array.isArray(lineage.members) ? lineage.members : [];+ if (!lineageMembers.length) {+ addMember('', id, lineageId);+ continue;+ }+ lineageMembers.forEach((m) => addMember(m && m.uid, m && m.id, lineageId));+ }+ return members;+}+function removeAutoCopyAccount(dataDir, uid) {const sourceUid = String(uid || '').trim();if (!sourceUid) return 0;@@ -1248,15 +1302,69 @@ function listAccounts(dataDir) {);}+/** 删除 auth 目录中属于该 uid 的全部登录文件(官方固定文件 + 带时间戳的历史存档)。+ * 只删 listAuthRecords 能发现(parseAuthFile 可解析并匹配)的记录,确保之后的+ * backupCurrent 扫描不会再把这个账号重新备份回来——这是「删除账号重启后又出现」+ * 的根因:删除只清了 backups 目录,auth 目录里残留的存档会在下一次扫描时复活账号。 */+function deleteAuthFilesForUid(uid, log = () => {}) {+ if (!AUTH_FILE) return { removed: 0 };+ if (!DYNAMIC_AUTH_DISCOVERY) {+ const record = parseAuthFile(AUTH_FILE, { strict: false });+ if (record && record.uid === uid && fs.existsSync(AUTH_FILE)) {+ fs.unlinkSync(AUTH_FILE);+ log(`[delete] 已删除固定登录文件 ${path.basename(AUTH_FILE)}`);+ return { removed: 1 };+ }+ return { removed: 0 };+ }+ const dir = authDir();+ let names;+ try { names = fs.readdirSync(dir); } catch (_) { return { removed: 0 }; }+ let removed = 0;+ for (const name of names) {+ if (!safeAuthFileName(name)) continue;+ const file = path.join(dir, name);+ const record = parseAuthFile(file);+ if (record && record.uid === uid && fs.existsSync(file)) {+ try {+ fs.unlinkSync(file);+ removed += 1;+ } catch (e) {+ log(`[delete] 删除认证存档 ${name} 失败: ${e.message}`);+ }+ }+ }+ return { removed };+}+/** 永久删除某个账号的备份文件(不影响当前登录) */-function deleteAccount(dataDir, uid) {+function deleteAccount(dataDir, uid, log = () => {}) {if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号切换`);+ // 防御:面板已对当前登录账号隐藏删除按钮;走到这里说明状态异常,+ // 拒绝直接删官方正在读取的登录位(删了 WorkBuddy 也会重新写回,删不干净)。+ const current = resolveCurrentAuth();+ if (current.file && !current.ambiguous) {+ const record = parseAuthFile(current.file, { strict: false });+ if (record && record.uid === uid) {+ throw new Error('不能删除当前登录的账号(请先退出登录或切换到其他账号)');+ }+ }migrateLegacyDataDir(dataDir);- const file = backupPath(dataDir, uid);+ // 关键:先清掉 auth 目录里该 uid 的全部登录文件(固定文件 + 历史存档),+ // 否则 backupCurrent 的下一次扫描会把账号重新备份回来(删除后复活的根因)。+ const authResult = deleteAuthFilesForUid(uid, log);+ const files = [backupPath(dataDir, uid)];+ // 旧版 HelloBuddy 目录仍会在每次启动时迁移缺失的账号备份。删除新目录+ // 的文件后若留下旧源文件,下一次 daemon 启动就会把账号重新复制回来。+ if (!IS_WIN && samePath(dataDir, PLATFORM_DATA_DIR)) {+ files.push(backupPath(LEGACY_DATA_DIR, uid));+ }let deletedFile = false;- if (fs.existsSync(file)) {- fs.unlinkSync(file);- deletedFile = true;+ for (const file of files) {+ if (fs.existsSync(file)) {+ fs.unlinkSync(file);+ deletedFile = true;+ }}const mf = metaFile(dataDir);try {@@ -1268,7 +1376,7 @@ function deleteAccount(dataDir, uid) {} catch (_) {/* meta 不存在则忽略 */}- return { deleted: deletedFile, uid };+ return { deleted: deletedFile, uid, authFilesRemoved: authResult.removed };}/** 切换登录账号:把备份文件复制回登录信息文件(先校验 uid 匹配) */@@ -1393,6 +1501,7 @@ module.exports = {moveAutoCopySession,removeAutoCopySession,removeAutoCopyAccount,+ collectLineageMembersForDelete,getAutoCopyMapping,setAutoCopyMapping,deleteAutoCopyMapping,diff --git a/scripts/secure-transfer.js b/scripts/secure-transfer.jsindex c1ac963..ccd50de 100644--- a/scripts/secure-transfer.js+++ b/scripts/secure-transfer.js@@ -2,9 +2,12 @@const crypto = require('node:crypto');const path = require('node:path');+const zlib = require('node:zlib');const MAX_PASSWORD_LENGTH = 1024;const EXPORT_KDF = 'aes-256-gcm+scrypt';+const EXPORT_VERSION = 3;+const EXPORT_COMPRESSION = 'gzip';function requiredPassword(value) {const password = typeof value === 'string' ? value : '';@@ -17,19 +20,20 @@ function exportSecretKey(password, salt) {return crypto.scryptSync(String(password), salt, 32);}-function encryptExport(plain, password) {+function encryptBinary(plain, password) {const checkedPassword = requiredPassword(password);const salt = crypto.randomBytes(16);const iv = crypto.randomBytes(12);const cipher = crypto.createCipheriv('aes-256-gcm', exportSecretKey(checkedPassword, salt), iv);- const encrypted = Buffer.concat([cipher.update(String(plain), 'utf8'), cipher.final()]);+ const input = Buffer.isBuffer(plain) ? plain : Buffer.from(String(plain), 'utf8');+ const encrypted = Buffer.concat([cipher.update(input), cipher.final()]);return {data: Buffer.concat([iv, cipher.getAuthTag(), encrypted]).toString('base64'),salt: salt.toString('base64'),};}-function decryptExport(data, password, saltBase64) {+function decryptBinary(data, password, saltBase64) {const checkedPassword = requiredPassword(password);const packed = Buffer.from(String(data || ''), 'base64');if (packed.length <= 28) throw new Error('导出数据不完整或已损坏');@@ -38,12 +42,22 @@ function decryptExport(data, password, saltBase64) {try {const decipher = crypto.createDecipheriv('aes-256-gcm', exportSecretKey(checkedPassword, salt), packed.subarray(0, 12));decipher.setAuthTag(packed.subarray(12, 28));- return Buffer.concat([decipher.update(packed.subarray(28)), decipher.final()]).toString('utf8');+ return Buffer.concat([decipher.update(packed.subarray(28)), decipher.final()]);} catch (_) {throw new Error('密码错误或导出文件已损坏');}}+// v2 exports remain readable through the text helpers; new exports use the+// binary helper so compression happens before encryption and is authenticated.+function encryptExport(plain, password) {+ return encryptBinary(plain, password);+}++function decryptExport(data, password, saltBase64) {+ return decryptBinary(data, password, saltBase64).toString('utf8');+}+function normalizeExportKind(kind) {const value = String(kind || '').trim();if (!/^[a-z][a-z0-9-]{0,63}$/.test(value)) throw new Error('无效的导出类型');@@ -55,13 +69,15 @@ function createEncryptedExport(kind, payload, password, createdAt) {if (!payload || typeof payload !== 'object' || payload.exportType !== 'WorkDaddy-' + normalizedKind) {throw new Error('导出数据类型不匹配');}- const encrypted = encryptExport(JSON.stringify(payload), password);+ const compressed = zlib.gzipSync(Buffer.from(JSON.stringify(payload), 'utf8'));+ const encrypted = encryptBinary(compressed, password);return JSON.stringify({wbsExport: 'WorkDaddy',- version: 2,+ version: EXPORT_VERSION,exportType: normalizedKind,createdAt: createdAt || new Date().toISOString(),kdf: EXPORT_KDF,+ compression: EXPORT_COMPRESSION,salt: encrypted.salt,data: encrypted.data,});@@ -72,12 +88,17 @@ function openEncryptedExport(content, expectedKind, password) {let envelope;try { envelope = JSON.parse(String(content || '')); }catch (_) { throw new Error('文件不是有效的导出 JSON'); }- if (!envelope || envelope.wbsExport !== 'WorkDaddy' || Number(envelope.version) < 2) {+ if (!envelope || envelope.wbsExport !== 'WorkDaddy' || ![2, EXPORT_VERSION].includes(Number(envelope.version))) {throw new Error('不是有效的 WorkDaddy 加密导出文件');}if (envelope.exportType && envelope.exportType !== normalizedKind) throw new Error('导出文件类型不匹配');let payload;- try { payload = JSON.parse(decryptExport(envelope.data, password, envelope.salt)); }+ try {+ const plaintext = Number(envelope.version) === EXPORT_VERSION+ ? zlib.gunzipSync(decryptBinary(envelope.data, password, envelope.salt)).toString('utf8')+ : decryptExport(envelope.data, password, envelope.salt);+ payload = JSON.parse(plaintext);+ }catch (error) {if (/密码|损坏|salt/.test(String(error && error.message))) throw error;throw new Error('导出数据无法解析或已损坏');@@ -118,6 +139,8 @@ function resolveArchiveTarget(root, relativePath) {}module.exports = {+ EXPORT_VERSION,+ EXPORT_COMPRESSION,MAX_PASSWORD_LENGTH,createEncryptedExport,decryptExport,diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.issindex 59f08dd..2d9b2be 100644--- a/scripts/win/workdaddy.iss+++ b/scripts/win/workdaddy.iss@@ -76,7 +76,7 @@ Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType:Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: none; ValueName: "WorkDaddy AI"; Flags: deletevalue[Run]-Filename: "{app}\WorkDaddyLauncher.exe"; Description: "{#StartDescription}"; WorkingDir: "{app}"; Flags: nowait postinstall skipifsilent runasoriginaluser+Filename: "{app}\WorkDaddyLauncher.exe"; Description: "{#StartDescription}"; WorkingDir: "{app}"; Flags: nowait postinstall skipifsilent runasoriginaluser; Check: ShouldAutoLaunch[UninstallRun]Filename: "{app}\WorkDaddyLauncher.exe"; Parameters: "--stop-lifecycle --profile ""{#ProfileId}"" --app-dir ""{app}"""; WorkingDir: "{app}"; Flags: runhidden waituntilterminated; RunOnceId: "StopWorkDaddyLifecycle"@@ -87,6 +87,7 @@ Type: filesandordirs; Name: "{app}"[Code]varPreserveExistingLifecycle: Boolean;+ ElevatedInstallConfirmed: Boolean;ClientPage: TInputFileWizardPage;ClientSourceLabel: TNewStaticText;ClientVersionLabel: TNewStaticText;@@ -103,6 +104,11 @@ beginResult := not PreserveExistingLifecycle;end;+function ShouldAutoLaunch(): Boolean;+begin+ Result := not IsAdmin;+end;+function RunNativeHelper(const Mode: String; var ResultCode: Integer): Boolean;varParameters: String;@@ -737,21 +743,42 @@ beginend;end;+function ConfirmElevatedInstall(): Boolean;+begin+ if ElevatedInstallConfirmed then+ begin+ Result := True;+ exit;+ end;++ Result := MsgBox(+ '当前安装程序是以管理员权限运行的。' + #13#10 + #13#10 ++ '仍可继续安装,但安装器不会自动启动或结束 WorkDaddy/WorkBuddy。请先手动退出它们,安装完成后再双击桌面快捷方式。' + #13#10 + #13#10 ++ '是否仍然继续安装?',+ mbConfirmation,+ MB_YESNO+ ) = IDYES;+ if Result then+ ElevatedInstallConfirmed := True;+end;+function PrepareToInstall(var NeedsRestart: Boolean): String;varResultCode: Integer;beginResult := '';- if IsAdminInstallMode then+ if not ValidateClientSelection(False) thenbegin- Result := '当前安装程序是以管理员权限运行的,无法继续安装。为避免 WorkDaddy 后台出现权限不一致,请点击“取消”,关闭安装程序后直接双击安装包重新运行;不要选择“以管理员身份运行”。UAC 无需关闭。';+ Result := '没有可用的 WorkBuddy 客户端路径。请返回“WorkBuddy 客户端”页面选择 .exe 主程序。';exit;end;- if not ValidateClientSelection(False) then+ if IsAdmin and not ConfirmElevatedInstall thenbegin- Result := '没有可用的 WorkBuddy 客户端路径。请返回“WorkBuddy 客户端”页面选择 .exe 主程序。';+ Result := '你已选择不继续管理员安装。可以取消安装,或返回后重新选择继续。';exit;end;+ if IsAdmin then+ exit;if not EnsureWorkBuddyClosed() thenbeginResult := '无法确认 WorkBuddy 已退出。可能原因是客户端仍有后台进程、进程权限高于当前用户、系统正在退出客户端,或安全软件阻止了进程检测。请手动结束当前客户端后重新运行安装程序。';diff --git a/test/account-sort.test.js b/test/account-sort.test.jsnew file mode 100644index 0000000..f200563--- /dev/null+++ b/test/account-sort.test.js@@ -0,0 +1,25 @@+'use strict';++// 账号页排序契约:当前账号不再置顶,一律按积分到期时间升序(最近到期最前)。++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const path = require('path');++const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');++test('account list sorts by credit expiry without pinning the current account', () => {+ // sortAccountsByCreditExpiry:置顶条件必须移除,只保留到期时间 + 稳定序+ const start = inject.indexOf('function sortAccountsByCreditExpiry()');+ assert.ok(start >= 0, 'sortAccountsByCreditExpiry must exist');+ const body = inject.slice(start, inject.indexOf('function reorderAccountCards', start));+ assert.ok(body.indexOf('a.isCurrent ? -1 : 1') === -1,+ 'current account must not be pinned to the top');+ assert.match(body, /a\.expiresAt - b\.expiresAt/, 'must sort by nearest credit expiry ascending');+ // render():去置顶,按到期时间+ const renderStart = inject.indexOf('function render(data)');+ const renderBody = inject.slice(renderStart, inject.indexOf('state.creditRemaining', renderStart));+ assert.ok(renderBody.indexOf('leftIsCurrent ? -1 : 1') === -1, 'render must not pin current account');+ assert.match(renderBody, /nearestCreditExpiry\(left\)/, 'render must order by credit expiry');+});\ No newline at end of filediff --git a/test/auth-discovery.test.js b/test/auth-discovery.test.jsindex 8f78eac..b472f23 100644--- a/test/auth-discovery.test.js+++ b/test/auth-discovery.test.js@@ -111,6 +111,71 @@ test('explicit WBSWITCH_AUTH_FILE keeps the legacy single-file behavior', () =>}});+test('deleting a migrated account also removes the legacy source so it stays deleted after restart', () => {+ if (os.platform() === 'win32') return;+ const f = fixture();+ const dataDir = path.join(f.root, 'Library', 'Application Support', 'WorkDaddy');+ const legacyDir = path.join(f.root, 'Library', 'Application Support', 'HelloBuddy');+ try {+ const legacyAccounts = path.join(legacyDir, 'accounts');+ fs.mkdirSync(path.join(legacyAccounts), { recursive: true });+ fs.writeFileSync(path.join(legacyAccounts, 's.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot')));++ const deleted = run(f.root, dataDir, 'process.stdout.write(JSON.stringify(lib.deleteAccount(process.env.WBSWITCH_DATA_DIR, "s")))');+ assert.equal(deleted.deleted, true);+ assert.equal(fs.existsSync(path.join(dataDir, 'accounts', 's.info')), false);+ assert.equal(fs.existsSync(path.join(legacyAccounts, 's.info')), false);++ // A fresh process models the next daemon start/list request.+ const accounts = run(f.root, dataDir, 'process.stdout.write(JSON.stringify(lib.listAccounts(process.env.WBSWITCH_DATA_DIR)))');+ assert.deepEqual(accounts, []);+ } finally {+ fs.rmSync(f.root, { recursive: true, force: true });+ }+});++test('deleting an account also removes its auth archives so a later backup scan cannot resurrect it', () => {+ const f = fixture();+ try {+ // 真实复活形态:当前登录 = b(官方固定位);s 只有历史存档(lastLogin 残留)。+ // 删除只清 accounts/s.info 的话,下次 backupCurrent 扫描 auth 目录又会把 s 备份回来。+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');+ fs.writeFileSync(canonical, JSON.stringify(auth('b', 'https://www.workbuddy.cn/auth/realms/copilot')));+ fs.writeFileSync(path.join(f.authDir, 's-archive.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot', true)));+ // 先让扫描发现并备份 s+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');+ assert.equal(fs.existsSync(path.join(f.dataDir, 'accounts', 's.info')), true);++ const deleted = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.deleteAccount(process.env.WBSWITCH_DATA_DIR,"s")))');+ assert.equal(deleted.deleted, true);+ assert.ok(deleted.authFilesRemoved >= 1, '应清理 auth 目录中的存档');+ assert.equal(fs.existsSync(path.join(f.dataDir, 'accounts', 's.info')), false);+ assert.equal(fs.existsSync(path.join(f.authDir, 's-archive.info')), false);+ assert.equal(fs.existsSync(canonical), true); // 其他账号的固定登录位不受影响++ // 新进程模拟 daemon 重启后的备份扫描:s 不得复活+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');+ assert.equal(fs.existsSync(path.join(f.dataDir, 'accounts', 's.info')), false);+ const accounts = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.listAccounts(process.env.WBSWITCH_DATA_DIR).map(x=>x.uid)))');+ assert.deepEqual(accounts, ['b']);+ } finally {+ fs.rmSync(f.root, { recursive: true, force: true });+ }+});++test('deleting the currently logged-in account is refused', () => {+ const f = fixture();+ try {+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');+ fs.writeFileSync(canonical, JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot')));+ const result = run(f.root, f.dataDir, `try { lib.deleteAccount(process.env.WBSWITCH_DATA_DIR,'s'); process.stdout.write('unexpected') } catch (e) { process.stdout.write(JSON.stringify(e.message)) }`);+ assert.match(result, /当前登录/);+ assert.equal(fs.existsSync(canonical), true);+ } finally {+ fs.rmSync(f.root, { recursive: true, force: true });+ }+});+test('missing filename metadata refuses a switch instead of falling back to a guessed file', () => {const f = fixture();try {diff --git a/test/auto-copy-rules.test.js b/test/auto-copy-rules.test.jsindex 9f3362b..21fc342 100644--- a/test/auto-copy-rules.test.js+++ b/test/auto-copy-rules.test.js@@ -25,6 +25,7 @@ const {moveAutoCopySession,removeAutoCopySession,removeAutoCopyAccount,+ collectLineageMembersForDelete,setAutoCopyMapping,getAutoCopyMapping,getAutoCopySessionMemberRecords,@@ -130,6 +131,47 @@ test('deleting the last lineage member removes mappings, while other members retassert.equal(getAutoCopyMapping(dataDir, lineageId, 's'), null);});+test('delete expansion covers every physical copy of one lineage across accounts', () => {+ const dataDir = tempDataDir();+ setAutoCopyRule(dataDir, { uid: 'bala', kind: 'session', key: 'sess-bala', enabled: true });+ const lineageId = getAutoCopySession(dataDir, 'bala', 'sess-bala').lineageId;+ addAutoCopySessionMember(dataDir, lineageId, 'h', 'sess-h');+ addAutoCopySessionMember(dataDir, lineageId, 'x', 'sess-x');+ // 另一个独立 lineage,删除请求不涉及,必须原样保留+ setAutoCopyRule(dataDir, { uid: 'h', kind: 'session', key: 'keep-h', enabled: true });++ assert.deepEqual(+ collectLineageMembersForDelete(dataDir, ['sess-bala']),+ [+ { uid: 'bala', id: 'sess-bala', lineageId },+ { uid: 'h', id: 'sess-h', lineageId },+ { uid: 'x', id: 'sess-x', lineageId },+ ]+ );+ // 只按会话 id 命中 lineage,与传入账号无关;孤儿 id 映射回自身(uid 为空)+ assert.deepEqual(collectLineageMembersForDelete(dataDir, ['sess-h']).map((m) => m.id), ['sess-bala', 'sess-h', 'sess-x']);+ assert.deepEqual(collectLineageMembersForDelete(dataDir, ['keep-h']).map((m) => m.id), ['keep-h']);+ assert.deepEqual(collectLineageMembersForDelete(dataDir, ['nope', 'sess-bala', 'sess-bala']).map((m) => m.id),+ ['nope', 'sess-bala', 'sess-h', 'sess-x']);+ assert.deepEqual(collectLineageMembersForDelete(dataDir, []), []);+});++test('delete expansion dedupes repeated members and survives dirty indices', () => {+ const dataDir = tempDataDir();+ setAutoCopyRule(dataDir, { uid: 'bala', kind: 'session', key: 'sess-bala', enabled: true });+ const lineageId = getAutoCopySession(dataDir, 'bala', 'sess-bala').lineageId;+ addAutoCopySessionMember(dataDir, lineageId, 'h', 'sess-h');+ addAutoCopySessionMember(dataDir, lineageId, 'h', 'sess-h');+ const meta = JSON.parse(fs.readFileSync(metaFile(dataDir), 'utf8'));+ // 脏索引:lineage 已删但 sessionIndex 残留,或 lineage 引用缺失成员 —— 只影响被收集成员集合+ delete meta.autoCopy.sessions[lineageId];+ fs.writeFileSync(metaFile(dataDir), JSON.stringify(meta, null, 2), { mode: 0o600 });++ const members = collectLineageMembersForDelete(dataDir, ['sess-bala', 'sess-bala']);+ assert.deepEqual(members.map((m) => m.id), ['sess-bala']);+ assert.equal(members[0].uid, '');+});+test('lineage member lookup is deduplicated and one member can be removed without deleting the lineage', () => {const dataDir = tempDataDir();setAutoCopyRule(dataDir, { uid: 'source', kind: 'session', key: 'source-session', enabled: true });diff --git a/test/cdp-click-api.test.js b/test/cdp-click-api.test.jsnew file mode 100644index 0000000..31c4a1e--- /dev/null+++ b/test/cdp-click-api.test.js@@ -0,0 +1,39 @@+'use strict';++// /api/cdp-click:真实鼠标点击路由的契约测试(坐标校验 + 视口边界 + 只发左键单击)。++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const path = require('path');++const daemonPath = path.join(__dirname, '..', 'scripts', 'daemon.js');+const daemon = fs.readFileSync(daemonPath, 'utf8');++test('cdp-click route exists and validates coordinates before dispatching', () => {+ const start = daemon.indexOf("p === '/api/cdp-click'");+ assert.ok(start >= 0, 'route must exist');+ const before = daemon.slice(0, start);+ const end = daemon.indexOf("p === '/api/devtools-url'", start);+ const route = daemon.slice(start, end < 0 ? start + 4000 : end);++ assert.match(route, /Number\.isFinite\(x\)/);+ assert.match(route, /Number\.isFinite\(y\)/);+ assert.match(route, /'点击坐标超出视口'/);+ assert.match(route, /Input\.dispatchMouseEvent/, 'must use real mouse events (isTrusted=true)');+ assert.match(route, /type: 'mousePressed'/);+ assert.match(route, /type: 'mouseReleased'/);+ assert.match(route, /button: 'left'/);+ assert.match(route, /clickCount: 1/);+ // 坐标先做视口校验再派发+ const viewportCheck = route.indexOf('x > viewport.w');+ const press = route.indexOf("type: 'mousePressed'");+ assert.ok(viewportCheck >= 0 && press >= 0 && viewportCheck < press,+ 'viewport bounds must be validated before dispatching the click');+});++test('cdp-click route is registered before the 404 fallback', () => {+ const routeAt = daemon.indexOf("p === '/api/cdp-click'");+ const notFoundAt = daemon.lastIndexOf('return json(res, 404');+ assert.ok(routeAt >= 0 && notFoundAt > routeAt, 'route must not fall through to 404');+});\ No newline at end of filediff --git a/test/secure-transfer.test.js b/test/secure-transfer.test.jsindex 6ea35c5..5072c2a 100644--- a/test/secure-transfer.test.js+++ b/test/secure-transfer.test.js@@ -5,7 +5,10 @@ const path = require('node:path');const test = require('node:test');const {+ EXPORT_COMPRESSION,+ EXPORT_VERSION,createEncryptedExport,+ encryptExport,openEncryptedExport,remapSessionArchivePath,resolveArchiveTarget,@@ -21,6 +24,9 @@ test('encrypted transfers require a password, randomize ciphertext, and bind theconst second = createEncryptedExport('quick-phrases', payload, 'correct horse', '2026-08-28T00:00:00.000Z');assert.notEqual(first, second, 'salt and IV must make repeated exports distinct');+ const envelope = JSON.parse(first);+ assert.equal(envelope.version, EXPORT_VERSION);+ assert.equal(envelope.compression, EXPORT_COMPRESSION);assert.doesNotMatch(first, /继续执行|correct horse/);assert.deepEqual(openEncryptedExport(first, 'quick-phrases', 'correct horse'), payload);assert.throws(() => createEncryptedExport('quick-phrases', payload, ' '), /密码不能为空/);@@ -29,6 +35,25 @@ test('encrypted transfers require a password, randomize ciphertext, and bind theassert.throws(() => openEncryptedExport(first, 'quick-phrases', 'wrong password'), /密码错误|损坏/);});+test('new imports remain compatible with the previous v2 encrypted export format', () => {+ const payload = {+ exportType: 'WorkDaddy-quick-phrases',+ version: 1,+ phrases: [{ text: '旧版短语' }],+ };+ const encrypted = encryptExport(JSON.stringify(payload), 'legacy password');+ const legacy = JSON.stringify({+ wbsExport: 'WorkDaddy',+ version: 2,+ exportType: 'quick-phrases',+ createdAt: '2026-08-28T00:00:00.000Z',+ kdf: 'aes-256-gcm+scrypt',+ salt: encrypted.salt,+ data: encrypted.data,+ });+ assert.deepEqual(openEncryptedExport(legacy, 'quick-phrases', 'legacy password'), payload);+});+test('session archive paths remap only managed session payload locations', () => {const oldId = '11111111-1111-4111-8111-111111111111';const newId = '22222222-2222-4222-8222-222222222222';@@ -76,7 +101,7 @@ test('daemon and injected panel expose password-protected account, session, andassert.match(inject, /requirePassword:\s*true/);});-test('successful session import reloads WorkBuddy through CDP without restarting it', () => {+test('session import never reloads WorkBuddy and only returns import results', () => {const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');const routeStart = daemon.indexOf("if (req.method === 'POST' && p === '/api/sessions/import')");const routeEnd = daemon.indexOf("if (req.method === 'POST' && p === '/api/sessions/copy')", routeStart);@@ -84,8 +109,33 @@ test('successful session import reloads WorkBuddy through CDP without restartingassert.notEqual(routeEnd, -1);const route = daemon.slice(routeStart, routeEnd);const imported = route.indexOf('await importSessions(');- const reloaded = route.indexOf('await reloadWorkBuddyPage()');- assert.ok(imported >= 0 && reloaded > imported, 'reload must happen only after session import succeeds');- assert.match(route, /reloaded\s*=\s*true/);+ assert.ok(imported >= 0, 'session import must complete before its response');+ assert.doesNotMatch(route, /await reloadWorkBuddyPage\(\)/, 'session import must not refresh automatically');+ assert.doesNotMatch(daemon, /\/api\/sessions\/reload/);assert.doesNotMatch(route, /quitWorkBuddy|relaunchWorkBuddy/);});++test('session import returns bounded import diagnostics without refresh controls', () => {+ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ const routeStart = daemon.indexOf("if (req.method === 'POST' && p === '/api/sessions/import')");+ const routeEnd = daemon.indexOf("if (req.method === 'POST' && p === '/api/sessions/copy')", routeStart);+ const route = daemon.slice(routeStart, routeEnd);+ const importUiStart = inject.indexOf("title: '导入会话'");+ const importUiEnd = inject.indexOf('// 删除选中', importUiStart);+ const importUi = inject.slice(importUiStart, importUiEnd);++ assert.match(daemon, /MAX_SESSION_IMPORT_ERRORS\s*=\s*20/);+ assert.match(daemon, /MAX_SESSION_IMPORT_ERROR_LENGTH\s*=\s*240/);+ assert.match(daemon, /errors:\s*summarizeSessionImportErrors\(errors\)/);+ assert.match(route, /errors:\s*result\.errors/);+ assert.doesNotMatch(route, /reloaded|reloadError/);+ assert.doesNotMatch(daemon, /\/api\/sessions\/reload/);+ assert.match(inject, /keepOpenOnSuccess:\s*true/);+ assert.match(inject, /successMessage:\s*function \(result\)/);+ assert.match(importUi, /successDoneLabel:\s*'关闭'/);+ assert.match(inject, /closeOnError:\s*true/);+ assert.doesNotMatch(importUi, /successAction|刷新页面|页面刷新/);+ assert.match(inject, /cancelButton\.style\.display\s*=\s*'none'/);+ assert.match(inject, /if \(completed\)[\s\S]*?if \(!completeAction\)[\s\S]*?close\(\);/);+});diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.jsindex 04bd803..c218906 100644--- a/test/session-delete-confinement.test.js+++ b/test/session-delete-confinement.test.js@@ -174,8 +174,9 @@ test('delete route validates before SQL and deletes the matched set only', () =>const selectAt = route.indexOf("SELECT id, user_id FROM sessions");assert.ok(normalizeAt >= 0 && normalizeAt < validateAt, 'the raw batch must be bounded before path validation');assert.ok(validateAt < selectAt, 'all IDs must be validated before SELECT or DELETE');- assert.match(route, /SELECT id, user_id FROM sessions WHERE id IN \(' \+ placeholders \+ '\);', ids/);- assert.match(route, /const matchedIds = matchedSessionIds\(ids, before\)/);+ assert.match(route, /SELECT id, user_id FROM sessions WHERE id IN \(' \+ placeholders \+ '\);', memberIds/);+ assert.match(route, /collectLineageMembersForDelete\(DATA_DIR, ids\)/);+ assert.match(route, /\.filter\(\(id\) => isValidSessionId\(id\)\)/);assert.match(route, /DELETE FROM sessions WHERE id IN \(" \+ sqlPlaceholders\(matchedIds\) \+ "\);",\s+matchedIds/s);assert.match(route, /for \(const id of matchedIds\) filesRemoved \+= deleteSessionFiles\(wbHome, id\)/);assert.doesNotMatch(route, /for \(const id of ids\) filesRemoved/);diff --git a/test/session-filter.test.js b/test/session-filter.test.jsnew file mode 100644index 0000000..7cb8c95--- /dev/null+++ b/test/session-filter.test.js@@ -0,0 +1,21 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');++test('session panel defaults its time filter to all sessions', () => {+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ const paneStart = inject.indexOf('var sessionsState =');+ const paneEnd = inject.indexOf('function isTaskSessionRecordUI', paneStart);+ const state = inject.slice(paneStart, paneEnd);+ assert.match(state, /range:\s*'all'/);++ const rangeStart = inject.indexOf("id=\"wbs-sess-range-seg\"");+ const rangeEnd = inject.indexOf("'</div></div>'", rangeStart);+ const range = inject.slice(rangeStart, rangeEnd);+ assert.match(range, /data-range=\"all\">全部/);+ assert.match(range, /class=\"wbs-sess-seg-btn active\"[^>]*data-range=\"all\">全部<\/button>/);+ assert.doesNotMatch(range, /active[^>]*data-range=\"7d\"/);+});diff --git a/test/session-monitor.test.js b/test/session-monitor.test.jsindex c480ffb..bacbaa2 100644--- a/test/session-monitor.test.js+++ b/test/session-monitor.test.js@@ -86,7 +86,8 @@ test('session resource normalizer treats background terminal updates as final',event: 'sessionUpdated',});assert.equal(normalize({ id: 'task-b', status: 'model_streaming' }, 'sessionUpdated').active, true);- assert.equal(normalize({ id: 'task-b', status: 'pending' }, 'sessionUpdated').active, false);+ // 官方 status='pending' = 侧栏「待确认」(等待交互/允许),视为 active 待批准信号+ assert.equal(normalize({ id: 'task-b', status: 'pending' }, 'sessionUpdated').active, true);assert.equal(normalize({ id: 'task-b', status: 'pending', activePromptStartedAt: 123 }, 'sessionUpdated').active, true);assert.equal(normalize({ id: 'task-b', status: 'pending', pendingInputKind: 'permission' }, 'sessionUpdated').active, true);assert.equal(normalize({diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 8e77ffb..e1d1cde 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -652,14 +652,20 @@ test('Windows Setup waits for WorkBuddy and stops only a native-verified profileassert.match(installer, /ResultCode = 11/);assert.match(installer, /runtime\\node\\\*/);assert.match(installer, /无法安全停止 WorkDaddy 后台进程/);- assert.match(installer, /IsAdminInstallMode/);+ assert.match(installer, /function ConfirmElevatedInstall/);+ assert.match(installer, /if IsAdmin and not ConfirmElevatedInstall/);+ assert.match(installer, /MB_YESNO/);+ assert.match(installer, /IDYES/);+ assert.match(installer, /if IsAdmin then\s+exit;/);+ assert.doesNotMatch(installer, /if IsAdminInstallMode then/);assert.match(installer, /当前安装程序是以管理员权限运行的/);- assert.match(installer, /不要选择“以管理员身份运行”/);+ assert.match(installer, /仍然继续安装/);+ assert.match(installer, /runasoriginaluser[^\r\n]*Check: ShouldAutoLaunch/);+ assert.match(installer, /function ShouldAutoLaunch[\s\S]*Result := not IsAdmin/);assert.match(installer, /普通安装器不会跨权限强行结束/);assert.match(installer, /按 Ctrl\+Shift\+Esc 打开任务管理器/);assert.match(installer, /旧版 WorkDaddy 的状态文件与实际程序不一致/);assert.match(installer, /不要手动删除 WorkDaddy 数据目录/);- assert.doesNotMatch(installer, /安装器本身可以使用管理员权限运行/);assert.doesNotMatch(installer, /旧版 WorkDaddy 正以管理员权限运行/);assert.doesNotMatch(installer, /prepare-win-install|windows-process-boundary|PowerShell/i);});@@ -815,11 +821,15 @@ test('account cards keep the compact three-row layout', () => {assert.doesNotMatch(script, /wbs-checkin-cell/);});-test('account cards place the current logged-in account first', () => {+test('account cards sort by credit expiry without pinning the current account', () => {const script = read('inject.js');assert.match(script, /state\.current = data\.current;\s*state\.accounts = \(data\.accounts \|\| \[\]\)\.slice\(\);/);- assert.match(script, /state\.accounts\.sort\(function \(left, right\) \{[\s\S]*left\.uid === state\.current\.uid[\s\S]*right\.uid === state\.current\.uid[\s\S]*return leftIsCurrent \? -1 : 1;[\s\S]*\}\);/);- assert.match(script, /function sortAccountsByCreditExpiry\(\) \{[\s\S]*isCurrent:[\s\S]*if \(a\.isCurrent !== b\.isCurrent\) return a\.isCurrent \? -1 : 1;[\s\S]*if \(a\.expiresAt !== b\.expiresAt\)/);+ // render():不再把当前账号置顶,统一按积分到期时间升序+ assert.doesNotMatch(script, /state\.accounts\.sort\(function \(left, right\) \{[\s\S]*left\.uid === state\.current\.uid[\s\S]*right\.uid === state\.current\.uid[\s\S]*return leftIsCurrent \? -1 : 1;[\s\S]*\}\);/);+ assert.match(script, /function render\(data\) \{[\s\S]*state\.accounts\.sort\(function \(left, right\) \{[\s\S]*nearestCreditExpiry\(left\)[\s\S]*nearestCreditExpiry\(right\)[\s\S]*le - re[\s\S]*\}\);/);+ // sortAccountsByCreditExpiry:去掉当前账号置顶,仅按到期时间 + 稳定序+ assert.match(script, /function sortAccountsByCreditExpiry\(\) \{[\s\S]*isCurrent:[\s\S]*a\.expiresAt !== b\.expiresAt[\s\S]*a\.expiresAt - b\.expiresAt[\s\S]*a\.index - b\.index/);+ assert.doesNotMatch(script, /function sortAccountsByCreditExpiry\(\) \{[\s\S]*if \(a\.isCurrent !== b\.isCurrent\) return a\.isCurrent \? -1 : 1;/);});test('quick-phrase layering does not reposition WorkBuddy native chat toolbar', () => {@@ -964,6 +974,31 @@ test('about page reports the running daemon version instead of stale package metassert.doesNotMatch(about, /build\.version = pjson\.version/);});+test('cached update metadata is rechecked against the running daemon version', () => {+ const daemon = read('daemon.js');+ const checkStart = daemon.indexOf('function checkUpdate(force)');+ const downloadStart = daemon.indexOf('\nfunction downloadUpdate()', checkStart);+ assert.ok(checkStart >= 0 && downloadStart > checkStart);+ const checkUpdate = daemon.slice(checkStart, downloadStart);+ assert.match(checkUpdate, /const cachedLatest = String\(c\.latest \|\| ''\)\.replace\(\/\^v\//);+ assert.match(checkUpdate, /updateState\.hasUpdate = semverCompare\(cachedLatest, DAEMON_VERSION\) > 0/);+ assert.doesNotMatch(checkUpdate, /updateState\.hasUpdate = !!c\.hasUpdate/);+});++test('about page clears stale update UI when no newer version exists', () => {+ const inject = read('inject.js');+ const checkStart = inject.indexOf('function checkForUpdate()');+ const logStart = inject.indexOf('\n function updateLogTimestamp()', checkStart);+ assert.ok(checkStart >= 0 && logStart > checkStart);+ const checkForUpdate = inject.slice(checkStart, logStart);+ assert.match(checkForUpdate, /tab\.classList\.remove\('wbs-tab-dot'\)/);+ assert.match(checkForUpdate, /card\.style\.display = 'none'/);+ assert.ok(+ checkForUpdate.indexOf("classList.remove('wbs-tab-dot')") < checkForUpdate.indexOf('if (!d || !d.hasUpdate)'),+ 'stale update indicators must be cleared before returning'+ );+});+test('update failures preserve stage, attempt id, and apply log details for feedback', () => {const daemon = read('daemon.js');const inject = read('inject.js');diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.jsindex f22c996..70aa035 100644--- a/test/windows-native-flow.test.js+++ b/test/windows-native-flow.test.js@@ -81,7 +81,7 @@ test('WorkBuddy GUI startup stays visible while the watchdog stays hidden', () =assert.match(watchdog, /spawn\(process\.execPath, args, \{ stdio: 'ignore', windowsHide: true/);});-test('installer waits for the exact profile client with a visible recheck dialog', () => {+test('installer confirms elevated setup but keeps lifecycle work and auto-launch standard-only', () => {const installer = read('scripts/win/workdaddy.iss');assert.match(installer, /function EnsureWorkBuddyClosed/);@@ -91,10 +91,16 @@ test('installer waits for the exact profile client with a visible recheck dialogassert.match(installer, /Caption := '\u53d6\u6d88'/);assert.match(installer, /--terminate-workbuddy/);assert.match(installer, /--stop-lifecycle/);- assert.match(installer, /IsAdminInstallMode/);+ assert.match(installer, /function ConfirmElevatedInstall/);+ assert.match(installer, /if IsAdmin and not ConfirmElevatedInstall/);+ assert.match(installer, /MB_YESNO/);+ assert.match(installer, /IDYES/);+ assert.match(installer, /if IsAdmin then\s+exit;/);+ assert.doesNotMatch(installer, /if IsAdminInstallMode then/);assert.match(installer, /当前安装程序是以管理员权限运行的/);assert.match(installer, /ExecAsOriginalUser\(/);- assert.match(installer, /runasoriginaluser/);+ assert.match(installer, /runasoriginaluser[^\r\n]*Check: ShouldAutoLaunch/);+ assert.match(installer, /function ShouldAutoLaunch[\s\S]*Result := not IsAdmin/);assert.match(installer, /PrivilegesRequired=lowest/);assert.match(installer, /CloseApplications=no/);});