WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
release: merge 1.2.14 changes
[email protected]32005447383c
diff --git a/scripts/assets/dmg-layout/codedaddy-cn.DS_Store b/scripts/assets/dmg-layout/codedaddy-cn.DS_Storeindex 3a32712..22c9462 100644Binary files a/scripts/assets/dmg-layout/codedaddy-cn.DS_Store and b/scripts/assets/dmg-layout/codedaddy-cn.DS_Store differdiff --git a/scripts/assets/dmg-layout/codedaddy.DS_Store b/scripts/assets/dmg-layout/codedaddy.DS_Storeindex 4b5e4a9..1f846e2 100644Binary files a/scripts/assets/dmg-layout/codedaddy.DS_Store and b/scripts/assets/dmg-layout/codedaddy.DS_Store differdiff --git a/scripts/assets/dmg-layout/workdaddy-ai.DS_Store b/scripts/assets/dmg-layout/workdaddy-ai.DS_Storeindex fecce98..f6ca4ff 100644Binary files a/scripts/assets/dmg-layout/workdaddy-ai.DS_Store and b/scripts/assets/dmg-layout/workdaddy-ai.DS_Store differdiff --git a/scripts/assets/dmg-layout/workdaddy.DS_Store b/scripts/assets/dmg-layout/workdaddy.DS_Storeindex b08ea9c..5e63bed 100644Binary files a/scripts/assets/dmg-layout/workdaddy.DS_Store and b/scripts/assets/dmg-layout/workdaddy.DS_Store differdiff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex a1dedea..3904cfd 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 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-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[ -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.@@ -555,7 +555,6 @@ if [ -z "$SKIP_FINDER" ]; thenecho "错误:Finder 未能把 DMG 窗口布局写入 .DS_Store" >&2exit 1fi- rm -rf -- "$MOUNT_DIR/.fseventsd"elseecho "==> 跳过 Finder 布局(WORKDADDY_SKIP_FINDER=1,无 GUI 会话)"# 无 GUI 时使用预置布局:把既有的 .DS_Store(窗口尺寸/图标位置/背景引用)放进卷根,@@ -577,6 +576,13 @@ elseecho "==> 已注入预置 Finder 布局: $DSSTORE_SOURCE"fifi+# Finder/系统可能在挂载期间创建元数据目录。它们属于卷的内部状态,不能出现在+# 安装窗口中;统一在两个构建分支收尾清理并设置 Finder 隐藏标志。+rm -rf -- "$MOUNT_DIR/.fseventsd"+# macOS 可能在卸载/重新挂载时重建 .fseventsd;保留一个带隐藏标志的+# 占位目录,避免 Finder 把系统元数据目录当作安装内容显示。+mkdir -p "$MOUNT_DIR/.fseventsd"+chflags hidden "$MOUNT_DIR/.background" "$MOUNT_DIR/.fseventsd" 2>/dev/null || truehdiutil detach "$DMG_DEVICE" >/dev/nullDMG_DEVICE=""rm -f "$OUT"diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 967ca75..25b0132 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -28,6 +28,7 @@ const path = require('path');const os = require('os');const crypto = require('crypto');const net = require('net');+const { inspectPersona, copyPersona } = require('./persona.js');let sessionSync = require('./session-sync.js');const {createCodeBuddyFiles} = require('./codebuddy-files.js');const { createAccountCreditCache } = require('./account-credit-cache.js');@@ -488,8 +489,11 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// launcher 的 httpGet 预算同步对齐到 HTTP_GET_TIMEOUT_MS;Windows app.asar// 页面归属与 CDP 目标等待窗口也同步修复。// 1.2.35:账号页合并加密备份 token 刷新后的有效期快照,并按自然日限制成功刷新一次。-const DAEMON_VERSION = '1.2.35';-const DAEMON_BUILD_ID = 'release-1.2.35-20261012-panel-token-daily-limit';+// 1.2.37:新版账号个人身份档案支持确认复制、备份及 CDP 刷新,兼容旧版全局目录。+// 1.2.38:防止 --probe-client-running 探测进程再次派生探测进程;监控仅由持有单实例锁的 daemon 启动。+// 1.2.39:限制 macOS pgrep 探针和父进程等待时间,避免系统过载时探针长期堆积。+const DAEMON_VERSION = '1.2.39';+const DAEMON_BUILD_ID = 'release-1.2.39-20261013-probe-timeout-cap';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -2680,7 +2684,9 @@ function safeClientRunning() {if (IS_LINUX) {return linuxWorkBuddyPids(WORKBUDDY_BINARY).length > 0;}- const result = spawnSync('pgrep', ['-f', WORKBUDDY_APP], { stdio: 'ignore', timeout: 5000 });+ const result = spawnSync('pgrep', ['-f', WORKBUDDY_APP], {+ stdio: 'ignore', timeout: IS_MAC ? CLIENT_RUNNING_MAC_SCAN_TIMEOUT_MS : 5000,+ });if (result.error || result.status === null) return null;return result.status === 0;} catch (_) {@@ -2698,13 +2704,20 @@ function safeClientRunning() {// 事件循环数秒,放在主线程里只会把「每次请求慢」变成「周期性不可用」。const clientRunningState = { value: null, checkedAt: 0 };const CLIENT_RUNNING_REFRESH_MS = 5000;+// macOS 的 pgrep 会扫描所有进程;系统过载时必须快速返回未知,不能让多个慢探针叠加。+const CLIENT_RUNNING_MAC_SCAN_TIMEOUT_MS = 2000;+// Windows 的验证包含 CIM 查询,保留较长预算;macOS 探针则在扫描超时前结束。+const CLIENT_RUNNING_PROBE_TIMEOUT_MS = IS_MAC ? 4000 : 15000;let clientRunningRefreshInFlight = false;function refreshClientRunning() {+ // 探测子进程会从本文件顶部开始执行;即使未来有调用路径早于启动门禁,+ // 也不能让它再次派生 --probe-client-running,避免形成进程链。+ if (PROBE_CLIENT_RUNNING) return Promise.resolve(clientRunningState.value);if (clientRunningRefreshInFlight) return Promise.resolve(clientRunningState.value);clientRunningRefreshInFlight = true;return new Promise((resolve) => {execFile(process.execPath, [__filename, '--probe-client-running'], {- encoding: 'utf8', timeout: 15000, windowsHide: true,+ encoding: 'utf8', timeout: CLIENT_RUNNING_PROBE_TIMEOUT_MS, windowsHide: true,}, (error, stdout) => {// 探测失败(超时/异常/输出不可解析)时保留上一次已知值,绝不让状态接口失败if (!error) {@@ -2716,9 +2729,10 @@ function refreshClientRunning() {});});}-// 启动时立即刷新一次,随后按固定间隔在后台刷新(unref 避免阻止进程退出)-refreshClientRunning().catch(() => {});-if (typeof setInterval === 'function') {+// 仅由取得单实例锁的正常 daemon 启动。不能在模块顶层调用刷新:+// --probe-client-running 也会加载本文件,提前刷新会递归拉起探测子进程。+function startClientRunningMonitor() {+ refreshClientRunning().catch(() => {});const timer = setInterval(() => { refreshClientRunning().catch(() => {}); }, CLIENT_RUNNING_REFRESH_MS);if (timer && typeof timer.unref === 'function') timer.unref();}@@ -10458,6 +10472,43 @@ function handleApi(req, res) {});}+ // Persona contents stay on disk. Only status/source labels reach the panel.+ if (req.method === 'GET' && p === '/api/persona') {+ try {+ if (PROFILE.kind !== 'workbuddy' || !PROFILE.capabilities.accounts) return json(res, 200, { ok: true, eligible: false, status: 'unsupported', sources: [] });+ const current = currentAccount();+ const uid = url.searchParams.get('uid') || String(current && current.uid || '');+ if (!uid) return json(res, 200, { ok: true, eligible: false, status: 'no-account', sources: [] });+ const accounts = listAccounts(DATA_DIR);+ if (current && !accounts.some(a => String(a.uid) === String(current.uid))) accounts.push(current);+ return json(res, 200, { ok: true, ...inspectPersona({ dataRoot: PROFILE.dataRoot, targetUid: uid, accounts }) });+ } catch (error) { return json(res, 400, { ok: false, error: error.message }); }+ }++ if (req.method === 'POST' && p === '/api/persona-copy') {+ return readBody(req).then(async (body) => {+ let release = null;+ try {+ if (PROFILE.kind !== 'workbuddy' || !PROFILE.capabilities.accounts) throw new Error('当前客户端不支持个人身份档案修复');+ release = await assertAccountSwitchIdle();+ const current = currentAccount();+ const accounts = listAccounts(DATA_DIR);+ if (current && !accounts.some(a => String(a.uid) === String(current.uid))) accounts.push(current);+ const result = copyPersona({ dataRoot: PROFILE.dataRoot, backupRoot: DATA_DIR, accounts,+ targetUid: body.uid, sourceUid: body.sourceUid, confirmed: body.confirmed, revision: body.revision });+ let reloaded = false;+ if (current && String(current.uid) === body.uid) {+ try { await reloadWorkBuddyPage({ waitForInjection: false, account: current }); reloaded = true; }+ catch (_) { /* The disk repair is complete; report reload separately. */ }+ }+ log('[persona] 个人身份档案复制完成,已保留修复前备份');+ return json(res, 200, { ok: true, files: result.files, backedUp: true, reloaded,+ hint: reloaded ? '身份档案已复制并刷新窗口' : '身份档案已复制,下次刷新窗口后生效' });+ } catch (error) { return json(res, 400, { ok: false, error: error.message }); }+ finally { if (release) release(); }+ });+ }+if (req.method === 'GET' && p === '/api/accounts') {const accounts = listAccountsWithRuntimeTokenCache();const checkinAutomationEnabled = readAutomations(DATA_DIR).some(task => task.enabled && stepsContainCheckin(task.steps));@@ -12606,6 +12657,7 @@ if (PROBE_CLIENT_RUNNING) {ensureDirs(DATA_DIR, log);if (!acquireDaemonLock()) process.exit(0);+startClientRunningMonitor();const sessionBackupCleanup = sessionSync.pruneSyncBackups(path.join(DATA_DIR, 'session-sync-backups'));if (sessionBackupCleanup.removed || sessionBackupCleanup.retainedRecovery) {log(`[session-sync-backups] 启动清理 ${sessionBackupCleanup.removed} 个无用备份,保留 ${sessionBackupCleanup.retainedRecovery} 个 recovery-needed 备份`);diff --git a/scripts/inject.js b/scripts/inject.jsindex 68d0f1a..d828b85 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -1424,6 +1424,35 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var WBS_ACCOUNT_NOTE_HOVER_KEY = 'workdaddy.account.noteHover.' + PROFILE_ID;var WBS_GROWTH_PLAN_HOVER_KEY = 'workdaddy.account.growthPlanHover.' + PROFILE_ID;var WBS_I18N_EN = {+ "当前账号可能仍在首次身份引导": "This account may still be in identity onboarding",+ "复制个人身份档案": "Copy personal identity files",+ "请先完成身份档案确认": "Complete the identity confirmation first",+ "该账号的个人目录为空或仍带有首次引导标记。可从下方来源复制 IDENTITY、USER、SOUL 和已有的 MEMORY;也可以保留独立身份。": "This account has an empty personal directory or an onboarding marker. Copy IDENTITY, USER, SOUL and any MEMORY from a source below, or keep its independent identity.",+ "确认后将备份并替换目标档案、标记引导完成,移除 BOOTSTRAP。旧版全局档案保持原样。": "Confirmation backs up and replaces the target files, completes onboarding and removes BOOTSTRAP. Legacy global files are preserved.",+ "保留独立身份并切换": "Keep independent identity and switch",+ "复制并切换": "Copy and switch",+ "备份并复制": "Back up and copy",+ " 个档案文件": " identity files",+ "已取消身份档案操作": "Identity operation canceled",+ "身份档案已复制": "Identity files copied",+ "账号切换已取消": "Account switch canceled",+ "当前账号无需修复或没有可用来源": "No repair needed or no available source",+ "旧版全局档案": "Legacy global files",+ "个人身份档案复制完成,已保留修复前备份": "Personal identity files copied; original files backed up",+ "当前客户端不支持个人身份档案修复": "Personal identity repair is unavailable for this client",+ "身份档案已复制并刷新窗口": "Identity files copied and window refreshed",+ "身份档案已复制,下次刷新窗口后生效": "Identity files copied; refresh the window to apply",+ "请先确认复制身份档案": "Confirm copying identity files first",+ "该账号无需修复或没有可用来源": "No repair needed or no available source",+ "目标身份档案已变化,请重新查看并确认": "Target identity files changed; review and confirm again",+ "身份档案来源无效": "Invalid identity source",+ "身份档案路径不能包含符号链接": "Identity paths must not contain symbolic links",+ "身份档案文件过大,未执行复制": "Identity file too large; copy canceled",+ "身份档案状态文件无效,请先手动检查": "Invalid identity state; inspect it manually first",+ "身份档案必须为普通文件": "Identity files must be regular files",+ "复制失败且回滚未完成,请从 WorkDaddy 的 persona 备份目录恢复": "Copy and rollback failed; restore from the WorkDaddy persona backup directory",+ "迁移状态文件过大": "Migration state file too large",+ "账号格式无效": "Invalid account ID",'账号备注': 'Account note','鼠标悬浮显示账号备注': 'Show account note on hover','查看或编辑账号备注': 'View or edit account note',@@ -2462,8 +2491,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return s ? Array.from(s)[0].toUpperCase() : '?';}+ var personaSwitchPreflight = null;function api(path, opts) {opts = opts || {};+ if (path === '/api/switch' && personaSwitchPreflight && !opts._wbsPersonaChecked) {+ var switchBody;+ try { switchBody = JSON.parse(opts.body || '{}'); } catch (_) { switchBody = {}; }+ return personaSwitchPreflight(switchBody.uid).then(function () {+ var checked = Object.assign({}, opts, { _wbsPersonaChecked: true });+ return api(path, checked);+ });+ }var request = {};Object.keys(opts).forEach(function (key) { request[key] = opts[key]; });var headers = {};@@ -2473,6 +2511,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {headers['X-WorkDaddy-Token'] = WBS_API_TOKEN;request.headers = headers;delete request.responseType;+ delete request._wbsPersonaChecked;var response = CAPS.apiTransport === 'cdp' ? window.__wbsApiFetch(path, request, WBS_API_TOKEN) : fetch(API + path, request);return response.then(function (r) {if (r.ok && opts.responseType === 'blob') return r.blob().then(function (blob) {@@ -6583,6 +6622,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<button class="wbs-acct-io wbs-acct-icon" type="button" data-act="account-more" title="账号设置" aria-label="账号设置"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2.75a2 2 0 0 1 2 1.4l.4 1.1 1.15.47 1.06-.48a2 2 0 0 1 2.4.45l.8.8a2 2 0 0 1 .45 2.4l-.48 1.06.47 1.15 1.1.4a2 2 0 0 1 0 3.8l-1.1.4-.47 1.15.48 1.06a2 2 0 0 1-.45 2.4l-.8.8a2 2 0 0 1-2.4.45l-1.06-.48-1.15.47-.4 1.1a2 2 0 0 1-3.8 0l-.4-1.1-1.15-.47-1.06.48a2 2 0 0 1-2.4-.45l-.8-.8a2 2 0 0 1-.45-2.4l.48-1.06-.47-1.15-1.1-.4a2 2 0 0 1 0-3.8l1.1-.4.47-1.15-.48-1.06a2 2 0 0 1 .45-2.4l.8-.8a2 2 0 0 1 2.4-.45l1.06.48 1.15-.47.4-1.1A2 2 0 0 1 12 2.75Z"/><circle cx="12" cy="12.5" r="3"/></svg></button>' +'</div>' +'</div>' ++ // 暂停身份资料提醒入口:保留修复代码,当前版本不在账号页显示。+ // '<div class="wbs-persona-notice" hidden><span>当前账号可能仍在首次身份引导</span><button type="button" class="wbs-modal-btn" data-act="persona-repair">复制个人身份档案</button></div>' +'<div class="wbs-acct-list"></div>' +'<button class="wbs-logout-btn" type="button" data-act="logout">' + LOGOUT_SVG + '<span>登录新账号</span></button>' +'<input type="file" id="wbs-import-file" accept=".json,application/json" style="display:none">';@@ -6602,6 +6643,108 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {root.querySelector('#wbs-import-file').addEventListener('change', onImportFile);}+ var closePersonaDialog = null;+ function openPersonaDialog(info, switching) {+ if (closePersonaDialog) return Promise.reject(new Error('请先完成身份档案确认'));+ return new Promise(function (resolve, reject) {+ var previousFocus = document.activeElement;+ var mask = el('div', 'wbs-modal-mask wbs-persona-mask');+ mask.innerHTML = '<div class="wbs-modal wbs-persona-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-persona-title">' ++ '<div class="wbs-modal-title" id="wbs-persona-title">复制个人身份档案</div>' ++ '<div class="wbs-modal-body">该账号的个人目录为空或仍带有首次引导标记。可从下方来源复制 IDENTITY、USER、SOUL 和已有的 MEMORY;也可以保留独立身份。<br>确认后将备份并替换目标档案、标记引导完成,移除 BOOTSTRAP。旧版全局档案保持原样。</div>' ++ '<div class="wbs-persona-sources"></div><div class="wbs-persona-error" role="alert"></div>' ++ '<div class="wbs-modal-actions"><button type="button" class="wbs-modal-btn" data-persona="cancel">取消</button>' ++ (switching ? '<button type="button" class="wbs-modal-btn" data-persona="skip">保留独立身份并切换</button>' : '') ++ '<button type="button" class="wbs-modal-btn wbs-modal-ok" data-persona="copy">' + (switching ? '复制并切换' : '备份并复制') + '</button></div></div>';+ var list = mask.querySelector('.wbs-persona-sources');+ info.sources.forEach(function (source, index) {+ var label = el('label', 'wbs-persona-source');+ var radio = document.createElement('input');+ radio.type = 'radio'; radio.name = 'wbs-persona-source'; radio.value = source.uid; radio.checked = index === 0;+ label.appendChild(radio);+ var text = document.createElement('span');+ text.textContent = (state.mask && source.uid !== 'legacy' ? maskAccountName(source.nickname) : source.nickname) + '(' + source.files.length + ' 个档案文件)';+ label.appendChild(text); list.appendChild(label);+ });+ var busy = false;+ function finish(accepted) {+ mask.remove(); mask.removeEventListener('keydown', onKey);+ closePersonaDialog = null;+ if (previousFocus && previousFocus.isConnected) previousFocus.focus();+ if (accepted) resolve(); else reject(new Error('已取消身份档案操作'));+ }+ function onKey(event) {+ event.stopPropagation();+ if (event.key === 'Escape') { event.preventDefault(); if (!busy) finish(false); }+ if (event.key === 'Tab') {+ var controls = Array.from(mask.querySelectorAll('input,button')).filter(function (node) { return !node.disabled; });+ var first = controls[0], last = controls[controls.length - 1];+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }+ }+ }+ closePersonaDialog = function () { finish(false); };+ mask.addEventListener('keydown', onKey);+ ['pointerdown', 'mousedown', 'dblclick', 'keyup'].forEach(function (type) { mask.addEventListener(type, function (event) { event.stopPropagation(); }); });+ mask.addEventListener('click', function (event) {+ event.stopPropagation();+ var button = event.target.closest('[data-persona]');+ if (!button || busy) return;+ var action = button.getAttribute('data-persona');+ if (action !== 'copy') { finish(action === 'skip'); return; }+ busy = true;+ mask.querySelectorAll('button,input').forEach(function (node) { node.disabled = true; });+ api('/api/persona-copy', { method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ uid: info.uid, sourceUid: mask.querySelector('input:checked').value, confirmed: true, revision: info.revision })+ }).then(function (result) {+ if (!alive) return;+ toast(result.hint || '身份档案已复制', false, root);+ finish(true); if (!switching) refresh();+ }).catch(function (error) {+ if (!alive) return;+ busy = false; mask.querySelectorAll('button,input').forEach(function (node) { node.disabled = false; });+ mask.querySelector('.wbs-persona-error').textContent = error.message;+ mask.querySelector('[data-persona="cancel"]').focus();+ });+ });+ mountPersistentOverlay(mask);+ mask.querySelector('input').focus();+ });+ }+ function beforePersonaSwitch(uid) {+ if (!uid || !alive) return Promise.reject(new Error('账号切换已取消'));+ return api('/api/persona?uid=' + encodeURIComponent(uid)).then(function (info) {+ if (!alive) throw new Error('账号切换已取消');+ if (info.eligible) return openPersonaDialog(info, true);+ });+ }+ if (CAPS.accounts) {+ // 暂停身份资料修复入口:保留 beforePersonaSwitch/openPersonaDialog,+ // 当前版本切换账号直接执行,不再被身份资料弹窗短路。+ // personaSwitchPreflight = beforePersonaSwitch;+ // var personaButton = accountsPane.querySelector('[data-act="persona-repair"]');+ // if (personaButton) listen(personaButton, 'click', function () {+ // api('/api/persona').then(function (info) {+ // if (!alive) return;+ // if (!info.eligible) { refreshPersonaNotice(); throw new Error('当前账号无需修复或没有可用来源'); }+ // return openPersonaDialog(info, false);+ // }).catch(function (error) { if (alive) toast(error.message, true, root); });+ // });+ }+ registerDisposer(function () {+ if (personaSwitchPreflight === beforePersonaSwitch) personaSwitchPreflight = null;+ if (closePersonaDialog) closePersonaDialog();+ });+ function refreshPersonaNotice() {+ var notice = accountsPane.querySelector('.wbs-persona-notice');+ if (!notice) return;+ notice.hidden = true;+ var requestId = state.personaRefreshId = (state.personaRefreshId || 0) + 1;+ api('/api/persona').then(function (info) {+ if (alive && requestId === state.personaRefreshId) notice.hidden = !info.eligible;+ }).catch(function () {});+ }+function initialAutoCopyAllSeen() {try { return localStorage.getItem(WBS_INITIAL_AUTO_COPY_ALL_KEY) === '1'; } catch (_) { return false; }}@@ -16421,6 +16564,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {.then(function (data) {if (!alive || requestId !== state.accountRefreshId) return;render(data);+ // 暂停身份资料提醒:后续版本重新设计文案和交互后再启用。+ // refreshPersonaNotice();// WorkBuddy can complete today's check-in outside WorkDaddy. Ask the// idempotent official endpoint for the current account only, then// patch that card in place. An enabled check-in task owns the ordered@@ -17811,6 +17956,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-actions{display:flex;gap:8px;justify-content:flex-end;padding-top:2px}','.wbs-sess-del{flex-shrink:0;padding:7px 12px;border:1px solid #ff6b6b;border-radius:9px;background:color-mix(in srgb,#ff6b6b 10%,transparent);color:#ff6b6b;font-size:12px;cursor:pointer;line-height:1;transition:all .15s}','.wbs-sess-del:hover{background:#ff6b6b;color:#fff}',+ '.wbs-persona-notice:not([hidden]){display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px;margin-bottom:8px;border:1px solid var(--wb-border-primary,#ddd);border-radius:9px;background:var(--wb-bg-secondary,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);font-size:12px}',+ '.wbs-modal-mask.wbs-persona-mask{z-index:2147483647;padding:12px;box-sizing:border-box;pointer-events:auto}.wbs-modal.wbs-persona-modal{box-sizing:border-box;width:360px;max-width:100%;max-height:100%;overflow:auto}.wbs-persona-modal .wbs-modal-body{line-height:1.65;overflow-wrap:anywhere}.wbs-persona-sources{display:flex;flex-direction:column;gap:8px;margin-top:12px}.wbs-persona-source{display:flex;align-items:flex-start;gap:6px;font-size:12px;cursor:pointer;overflow-wrap:anywhere}.wbs-persona-source span{min-width:0}.wbs-persona-source input{flex-shrink:0}.wbs-persona-modal .wbs-modal-actions{flex-wrap:wrap}.wbs-persona-error{font-size:12px;color:var(--wb-color-text-primary,#1f1f1f);overflow-wrap:anywhere}.wbs-persona-error:not(:empty){margin-top:10px}.wbs-persona-source:focus-within{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:2px}','.wbs-modal-mask{position:fixed;inset:0;z-index:2147483646;background:rgba(0,0,0,.4);display:flex;align-items:center;justify-content:center}',/* 免打扰确认弹窗:挂载在面板容器内,仅覆盖面板区域(弹窗居中于面板,不盖住 WorkBuddy 窗口) */'.wbs-modal-mask.wbs-modal-mask-panel{position:absolute;inset:0;z-index:2147483645;border-radius:18px}',@@ -17823,6 +17970,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'html.cb-dark .wbs-modal-btn.wbs-modal-danger,html[data-theme="dark"] .wbs-modal-btn.wbs-modal-danger{color:#fff;background:#e03d3d;border-color:#e03d3d}','html.cb-dark .wbs-modal-btn.wbs-modal-danger:hover,html[data-theme="dark"] .wbs-modal-btn.wbs-modal-danger:hover{background:#f04a4a}','html.cb-dark .wbs-modal-mask,html[data-theme="dark"] .wbs-modal-mask{background:rgba(0,0,0,.55)}',+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) .wbs-persona-modal{color-scheme:dark;background:var(--wb-bg-popover,#202126);color:var(--wb-color-text-primary,#e6e6e9)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) .wbs-persona-modal :is(.wbs-modal-title,.wbs-modal-body,.wbs-persona-error){color:inherit}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) .wbs-persona-notice{background:var(--wb-bg-secondary,#292b31);border-color:var(--wb-border-default,#454750);color:var(--wb-color-text-primary,#e6e6e9)}',+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) :is(.wbs-persona-notice,.wbs-persona-modal) .wbs-modal-btn:not(.wbs-modal-ok){background:var(--wb-bg-secondary,#292b31);border-color:var(--wb-border-default,#454750);color:var(--wb-color-text-secondary,#d5d5d9)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) :is(.wbs-persona-notice,.wbs-persona-modal) .wbs-modal-btn:not(.wbs-modal-ok):hover{background:var(--wb-bg-hover,#3c3e45);color:var(--wb-color-text-primary,#e6e6e9)}.wbs-persona-modal :is(button,input):disabled{opacity:.5;cursor:wait}','.wbs-checkin-risk-mask{padding:12px;box-sizing:border-box;pointer-events:auto}','.wbs-modal.wbs-checkin-risk-modal{box-sizing:border-box;width:360px;max-width:100%;max-height:100%;display:flex;flex-direction:column;min-height:0}','.wbs-checkin-risk-modal .wbs-modal-title,.wbs-checkin-risk-modal .wbs-modal-actions{flex-shrink:0}',diff --git a/scripts/persona.js b/scripts/persona.jsnew file mode 100644index 0000000..5d20c83--- /dev/null+++ b/scripts/persona.js@@ -0,0 +1,136 @@+'use strict';++// Only explicit, confirmed repairs cross the global -> personal layout boundary.+// Metadata returned to the renderer never includes identity or memory contents.+const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const { replaceFileWithRetry } = require('./atomic-file-write');+const IDENTITY_FILES = ['IDENTITY.md', 'USER.md', 'SOUL.md', 'MEMORY.md'];+const PERSONA_FILES = [...IDENTITY_FILES, 'workspace-state.json', 'BOOTSTRAP.md'];+const MAX_FILE_SIZE = 20 * 1024 * 1024;++function validUid(uid) { return typeof uid === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(uid); }+function personaDir(root, uid) {+ if (!validUid(uid)) throw new Error('账号格式无效');+ return path.join(path.resolve(root), `user-${uid}-personal`);+}+function assertSafePath(file) {+ let cursor = path.resolve(file);+ for (;;) {+ try { if (fs.lstatSync(cursor).isSymbolicLink()) throw new Error('身份档案路径不能包含符号链接'); }+ catch (error) { if (error.code !== 'ENOENT') throw error; }+ const parent = path.dirname(cursor);+ if (parent === cursor) break;+ cursor = parent;+ }+}+function snapshot(dir) {+ assertSafePath(dir);+ const result = {};+ for (const name of PERSONA_FILES) {+ const file = path.join(dir, name);+ assertSafePath(file);+ try {+ const stat = fs.lstatSync(file);+ if (!stat.isFile()) throw new Error('身份档案必须为普通文件');+ if (stat.size > MAX_FILE_SIZE) throw new Error('身份档案文件过大,未执行复制');+ result[name] = { text: fs.readFileSync(file, 'utf8'), mode: stat.mode & 0o777 };+ } catch (error) { if (error.code !== 'ENOENT') throw error; }+ }+ return result;+}+function stateOf(files) {+ if (!files['workspace-state.json']) return {};+ try {+ const value = JSON.parse(files['workspace-state.json'].text);+ if (value && typeof value === 'object' && !Array.isArray(value)) return value;+ } catch (_) {}+ throw new Error('身份档案状态文件无效,请先手动检查');+}+function fingerprint(files) { return crypto.createHash('sha256').update(JSON.stringify(files)).digest('hex'); }+function nonempty(files, name) { return !!(files[name] && files[name].text.trim()); }+function usableSource(files) {+ // A partial/template source must never suppress the official onboarding.+ return ['IDENTITY.md', 'USER.md', 'SOUL.md'].every(name => nonempty(files, name)) &&+ (!files['BOOTSTRAP.md'] || !!stateOf(files).onboardingCompletedAt);+}+function scopedLayout(root) {+ assertSafePath(root);+ const marker = path.join(root, 'storage/device/global/user-data-migration.json');+ assertSafePath(marker);+ try {+ const stat = fs.statSync(marker);+ if (stat.size > MAX_FILE_SIZE) throw new Error('迁移状态文件过大');+ const data = JSON.parse(fs.readFileSync(marker, 'utf8'));+ if (data && data.migrationItems && data.migrationItems.persona) return true;+ } catch (error) { if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; }+ try {+ return fs.readdirSync(root).some(name => /^user-[A-Za-z0-9_-]{1,128}-personal$/.test(name) && fs.lstatSync(path.join(root, name)).isDirectory());+ } catch (error) { if (error.code !== 'ENOENT') throw error; return false; }+}+function inspectPersona(options) {+ const { dataRoot, targetUid, accounts = [] } = options;+ const dir = personaDir(dataRoot, targetUid);+ if (!accounts.some(a => String(a.uid) === targetUid)) throw new Error('账号不存在');+ if (!scopedLayout(dataRoot)) return { uid: targetUid, status: 'legacy', eligible: false, sources: [] };+ const files = snapshot(dir);+ const state = stateOf(files);+ let status;+ if (state.onboardingCompletedAt || nonempty(files, 'MEMORY.md')) status = 'initialized';+ else if (files['BOOTSTRAP.md']) status = 'bootstrap';+ else if (IDENTITY_FILES.some(name => nonempty(files, name))) status = 'partial';+ else status = fs.existsSync(dir) ? 'empty' : 'missing';+ const revision = fingerprint(files);+ if (status === 'initialized' || status === 'partial') return { uid: targetUid, status, eligible: false, sources: [], revision };+ const sources = [];+ for (const account of accounts) {+ const uid = String(account.uid);+ if (!validUid(uid) || uid === targetUid || uid === 'legacy') continue;+ const sourceFiles = snapshot(personaDir(dataRoot, uid));+ if (usableSource(sourceFiles)) sources.push({ uid, nickname: String(account.nickname || uid), files: IDENTITY_FILES.filter(name => nonempty(sourceFiles, name)) });+ }+ const legacyFiles = snapshot(path.resolve(dataRoot));+ if (usableSource(legacyFiles)) sources.push({ uid: 'legacy', nickname: '旧版全局档案', files: IDENTITY_FILES.filter(name => nonempty(legacyFiles, name)) });+ return { uid: targetUid, status, eligible: ['missing', 'empty', 'bootstrap'].includes(status) && sources.length > 0, sources, revision };+}+function copyPersona(options) {+ if (options.confirmed !== true) throw new Error('请先确认复制身份档案');+ const preview = inspectPersona(options);+ if (!preview.eligible) throw new Error('该账号无需修复或没有可用来源');+ if (!options.revision || preview.revision !== options.revision) throw new Error('目标身份档案已变化,请重新查看并确认');+ if (!preview.sources.some(source => source.uid === options.sourceUid)) throw new Error('身份档案来源无效');+ const target = personaDir(options.dataRoot, options.targetUid);+ const source = options.sourceUid === 'legacy' ? path.resolve(options.dataRoot) : personaDir(options.dataRoot, options.sourceUid);+ const original = snapshot(target);+ const sourceFiles = snapshot(source);+ const state = { ...stateOf(original), version: stateOf(original).version || 1, onboardingCompletedAt: new Date().toISOString() };+ // Preserve target workspace metadata. Only the completed marker is repaired.+ const writes = {};+ for (const name of IDENTITY_FILES) if (nonempty(sourceFiles, name)) writes[name] = sourceFiles[name].text;+ writes['workspace-state.json'] = JSON.stringify(state, null, 2) + '\n';+ const backupDir = path.join(path.resolve(options.backupRoot), 'persona', options.targetUid, `${Date.now()}-${crypto.randomBytes(6).toString('hex')}`);+ assertSafePath(backupDir);+ fs.mkdirSync(backupDir, { recursive: true, mode: 0o700 });+ for (const name of Object.keys(original)) fs.writeFileSync(path.join(backupDir, name), original[name].text, { mode: 0o600, flag: 'wx' });+ // WorkBuddy is another process: it may finish onboarding while we back up.+ if (fingerprint(snapshot(target)) !== preview.revision) throw new Error('目标身份档案已变化,请重新查看并确认');+ const existed = fs.existsSync(target);+ fs.mkdirSync(target, { recursive: true, mode: 0o700 });+ const replace = options.replaceFile || replaceFileWithRetry;+ try {+ for (const name of Object.keys(writes)) replace(path.join(target, name), writes[name], 0o600);+ fs.rmSync(path.join(target, 'BOOTSTRAP.md'), { force: true });+ } catch (error) {+ try {+ for (const name of PERSONA_FILES) {+ if (original[name]) replaceFileWithRetry(path.join(target, name), original[name].text, original[name].mode);+ else fs.rmSync(path.join(target, name), { force: true });+ }+ if (!existed) fs.rmdirSync(target);+ } catch (_) { throw new Error('复制失败且回滚未完成,请从 WorkDaddy 的 persona 备份目录恢复'); }+ throw error;+ }+ return { status: 'copied', files: Object.keys(writes).length - 1, backupDir };+}+module.exports = { PERSONA_FILES, personaDir, inspectPersona, copyPersona };diff --git a/test/codebuddy-ide-recovery.test.js b/test/codebuddy-ide-recovery.test.jsindex 7ed50be..25a3109 100644--- a/test/codebuddy-ide-recovery.test.js+++ b/test/codebuddy-ide-recovery.test.js@@ -33,7 +33,7 @@ function harness() {WebSocketCtor: Socket, createRendererApiBridge: () => async () => {}, API_TOKEN: 'fixture', ACTUAL_PORT: 1,BINDING: 'fixture', buildInjectScript: () => 'fixture-inject', redactDiagnosticText: s => s, log: () => {},PROFILE: { kind: 'codebuddy' }, cdp: { port: 1 }, fetch: async () => ({ json: async () => state.targets }),- AbortSignal, selectIdeTargets: list => list });+ AbortSignal, selectIdeTargets: list => list, IS_MAC: false, PROBE_CLIENT_RUNNING: false });vm.runInContext(manager, context);return { state, sockets, context, timers,scan: () => vm.runInContext('ideSyncScan()', context),diff --git a/test/daemon-status-nonblocking.test.js b/test/daemon-status-nonblocking.test.jsindex 49de665..e161f6c 100644--- a/test/daemon-status-nonblocking.test.js+++ b/test/daemon-status-nonblocking.test.js@@ -13,6 +13,7 @@const assert = require('node:assert/strict');const fs = require('node:fs');const http = require('node:http');+const os = require('node:os');const path = require('node:path');const test = require('node:test');const vm = require('node:vm');@@ -50,19 +51,63 @@ test('client running probe runs in a one-shot subprocess so the daemon event looassert.match(daemonSource, /execFile\(process\.execPath, \[__filename, '--probe-client-running'\]/, 'refresh must shell out to the one-shot probe');});+test('macOS probe uses bounded scan and parent timeouts', () => {+ assert.match(daemonSource, /CLIENT_RUNNING_MAC_SCAN_TIMEOUT_MS = 2000/);+ assert.match(daemonSource, /CLIENT_RUNNING_PROBE_TIMEOUT_MS = IS_MAC \? 4000 : 15000/);+ assert.match(daemonSource, /timeout: IS_MAC \? CLIENT_RUNNING_MAC_SCAN_TIMEOUT_MS : 5000/);+ assert.match(daemonSource, /timeout: CLIENT_RUNNING_PROBE_TIMEOUT_MS/);+});+test('one-shot probe subprocess answers without starting the daemon', () => {const { execFileSync } = require('node:child_process');- const startedAt = Date.now();- const stdout = execFileSync(- process.execPath,- [path.join(__dirname, '..', 'scripts', 'daemon.js'), '--probe-client-running'],- { encoding: 'utf8', timeout: 20000, windowsHide: true }- );- const parsed = JSON.parse(stdout);- assert.ok(parsed.running === true || parsed.running === false || parsed.running === null,- 'probe must answer a boolean or null');- // 子进程只做一次探测后退出:不得进入单实例锁/HTTP 服务等启动路径- assert.ok(Date.now() - startedAt < 15000, 'probe subprocess should exit quickly without booting the daemon');+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-probe-test-'));+ const preload = path.join(temp, 'audit-probe.cjs');+ const audit = path.join(temp, 'probe-spawns.json');+ // 执行真实入口,但拦截递归探测,避免有缺陷的版本在测试中制造进程风暴。+ fs.writeFileSync(preload, `+ const fs = require('node:fs');+ const cp = require('node:child_process');+ const originalExecFile = cp.execFile;+ const probes = [];+ cp.execFile = function(bin, args, options, callback) {+ if (args && args.includes('--probe-client-running')) {+ probes.push(args);+ callback(new Error('recursive probe blocked by regression test'));+ return;+ }+ return originalExecFile.apply(this, arguments);+ };+ process.on('exit', () => fs.writeFileSync(${JSON.stringify(audit)}, JSON.stringify(probes)));+ `);+ try {+ for (const profile of ['workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl']) {+ const dataDir = path.join(temp, profile);+ const startedAt = Date.now();+ const stdout = execFileSync(+ process.execPath,+ ['--require', preload, path.join(__dirname, '..', 'scripts', 'daemon.js'), '--probe-client-running'],+ { encoding: 'utf8', timeout: 20000, windowsHide: true, env: {+ ...process.env,+ WBSWITCH_PROFILE: profile,+ WBSWITCH_DATA_DIR: dataDir,+ WBSWITCH_AUTH_FILE: path.join(temp, 'absent-auth.json'),+ WORKDADDY_TELEMETRY: '0',+ } }+ );+ const parsed = JSON.parse(stdout);+ assert.ok(parsed.running === true || parsed.running === false || parsed.running === null,+ 'probe must answer a boolean or null');+ assert.ok(Date.now() - startedAt < 15000, 'probe should exit without booting the daemon');+ assert.deepEqual(JSON.parse(fs.readFileSync(audit, 'utf8')), [],+ `${profile}: one-shot probe must never spawn another probe`);+ assert.equal(fs.existsSync(path.join(dataDir, '.daemon.lock')), false,+ 'probe must not acquire the daemon lock');+ assert.equal(fs.existsSync(path.join(dataDir, 'ui-port.json')), false,+ 'probe must not start the HTTP service');+ }+ } finally {+ fs.rmSync(temp, { recursive: true, force: true });+ }});test('client running cache refreshes in the background and survives probe failures', async () => {@@ -75,6 +120,7 @@ test('client running cache refreshes in the background and survives probe failurlet probeCalls = 0;let probeShouldFail = false;let probeResult = true;+ let refreshTimer;const ctx = {// mock execFile:模拟一次性子进程探测,异步回调execFile: (bin, args, options, callback) => {@@ -87,11 +133,20 @@ test('client running cache refreshes in the background and survives probe failurprocess: { execPath: process.execPath },__filename: 'daemon.js',Date,- setInterval: () => ({ unref() {} }),+ setInterval: (callback, delay) => {+ assert.equal(delay, 5000);+ refreshTimer = callback;+ return { unref() {} };+ },console,+ IS_MAC: false,+ PROBE_CLIENT_RUNNING: false,};vm.runInNewContext(block, ctx);+ assert.equal(probeCalls, 0, 'defining the cache must not spawn a probe before the startup gate');+ assert.equal(refreshTimer, undefined, 'defining the cache must not start a timer');+ ctx.startClientRunningMonitor();// 启动时立即刷新一次(fire-and-forget),缓存随后就位await new Promise((resolve) => setTimeout(resolve, 10));assert.equal(probeCalls, 1, 'cache should refresh once at startup');@@ -107,14 +162,66 @@ test('client running cache refreshes in the background and survives probe failurprobeShouldFail = true;assert.equal(await ctx.refreshClientRunning(), false, 'failed probe must preserve the last known value');assert.equal(probeCalls, 4);++ // 定时刷新必须保留;避免修复递归时意外停掉正常 daemon 的后台状态更新。+ probeShouldFail = false;+ probeResult = true;+ refreshTimer();+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(probeCalls, 5);+ assert.equal(vm.runInNewContext('clientRunningState.value', ctx), true);+});++test('probe subprocess never starts another probe', async () => {+ const anchor = daemonSource.indexOf('const clientRunningState = {');+ assert.ok(anchor > 0, 'client running cache block not found');+ const end = daemonSource.indexOf('async function cdpLoop', anchor);+ assert.ok(end > anchor, 'cache block end anchor not found');+ const block = daemonSource.slice(anchor, end);+ let probeCalls = 0;+ const ctx = {+ execFile: () => { probeCalls += 1; },+ process: { execPath: process.execPath },+ __filename: 'daemon.js',+ Date,+ setInterval: () => ({ unref() {} }),+ console,+ IS_MAC: false,+ PROBE_CLIENT_RUNNING: true,+ };+ vm.runInNewContext(block, ctx);+ assert.equal(await ctx.refreshClientRunning(), null);+ assert.equal(probeCalls, 0);+});++test('only the daemon holding the instance lock starts the client monitor', () => {+ const start = daemonSource.indexOf('\nensureDirs(DATA_DIR, log);');+ const end = daemonSource.indexOf('\nconst sessionBackupCleanup =', start);+ assert.ok(start > 0 && end > start, 'daemon startup gate not found');+ const block = daemonSource.slice(start, end);+ const exit = new Error('process exited');+ let monitorStarts = 0;+ let ownsLock = false;+ const ctx = {+ DATA_DIR: 'fixture', log() {}, ensureDirs() {},+ acquireDaemonLock: () => ownsLock,+ startClientRunningMonitor: () => { monitorStarts += 1; },+ process: { exit: (code) => { assert.equal(code, 0); throw exit; } },+ };+ assert.throws(() => vm.runInNewContext(block, ctx), (error) => error === exit);+ assert.equal(monitorStarts, 0, 'rejected duplicate daemon must not leave a probe chain');+ ownsLock = true;+ vm.runInNewContext(block, ctx);+ assert.equal(monitorStarts, 1, 'the owning daemon must start the monitor once');});test('daemon behavior change ships a version and build bump so stale daemons are replaced', () => {const version = daemonSource.match(/const DAEMON_VERSION = '([^']+)'/);const buildId = daemonSource.match(/const DAEMON_BUILD_ID = '([^']+)'/);assert.ok(version && buildId, 'DAEMON_VERSION/DAEMON_BUILD_ID not found');- assert.notEqual(version[1], '1.2.28', 'DAEMON_VERSION must be incremented for a daemon behavior change');- assert.match(buildId[1], /^release-1\.2\.35-/, 'DAEMON_BUILD_ID must be rewritten for the new build');+ assert.notEqual(version[1], '1.2.35', 'DAEMON_VERSION must change so launchers replace the affected daemon');+ assert.ok(buildId[1].startsWith(`release-${version[1]}-`), 'DAEMON_BUILD_ID must match the daemon version');+ assert.notEqual(buildId[1], 'release-1.2.35-20261012-panel-token-daily-limit');});test('launcher httpGet uses a budget aligned with the daemon probe cost', () => {diff --git a/test/macos-dmg-layout.test.js b/test/macos-dmg-layout.test.jsindex b4bdb3c..213e8f8 100644--- a/test/macos-dmg-layout.test.js+++ b/test/macos-dmg-layout.test.js@@ -29,6 +29,7 @@ test('macOS DMG layout is written to a writable image before final compression',assert.match(buildSource, /osascript[\s\S]*tell application "Finder"/);assert.match(buildSource, /test -f "\$MOUNT_DIR\/\.DS_Store"/);assert.match(buildSource, /rm -rf -- "\$MOUNT_DIR\/\.fseventsd"/);+ assert.match(buildSource, /chflags hidden "\$MOUNT_DIR\/\.background" "\$MOUNT_DIR\/\.fseventsd"/);assert.match(buildSource, /hdiutil convert[\s\S]*-format UDZO/);});diff --git a/test/persona-api.test.js b/test/persona-api.test.jsnew file mode 100644index 0000000..4e50188--- /dev/null+++ b/test/persona-api.test.js@@ -0,0 +1,71 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const vm = require('node:vm');+const persona = require('../scripts/persona');+const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+const routes = daemon.slice(daemon.indexOf(" if (req.method === 'GET' && p === '/api/persona')"), daemon.indexOf(" if (req.method === 'GET' && p === '/api/accounts')"));+function harness(t, profile = 'workbuddy-cn') {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-persona-api-')));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const dataRoot = path.join(root, profile);+ fs.mkdirSync(path.join(dataRoot, 'user-b-personal'), { recursive: true });+ for (const file of ['IDENTITY.md', 'USER.md', 'SOUL.md', 'MEMORY.md']) fs.writeFileSync(path.join(dataRoot, file), 'fixture ' + file);+ fs.writeFileSync(path.join(dataRoot, 'user-b-personal/BOOTSTRAP.md'), 'fixture onboarding');+ let reloads = 0, locked = false;+ const context = vm.createContext({+ PROFILE: { kind: profile.startsWith('workbuddy') ? 'workbuddy' : 'codebuddy', dataRoot, capabilities: { accounts: true } },+ DATA_DIR: path.join(root, 'WorkDaddy'), URL, ...persona,+ currentAccount: () => ({ uid: 'b' }), listAccounts: () => [{ uid: 'a' }],+ assertAccountSwitchIdle: async () => { if (locked) throw new Error('busy'); locked = true; return () => { locked = false; }; },+ reloadWorkBuddyPage: async () => { reloads++; }, log: () => {}, readBody: req => Promise.resolve(req.body),+ json: (res, status, body) => ({ status, body }),+ });+ const run = vm.runInContext('(async function(req) { const res = {}; const url = new URL(req.url, "http://127.0.0.1"); const p = url.pathname; ' + routes + '})', context);+ return { dataRoot, context, run, reloads: () => reloads, locked: () => locked };+}+for (const profile of ['workbuddy-cn', 'workbuddy-ai']) test('persona API uses ' + profile + ' root, consent, backup and current-account CDP reload', async t => {+ const h = harness(t, profile);+ const get = await h.run({ method: 'GET', url: '/api/persona' });+ assert.equal(get.body.eligible, true);+ assert.equal(JSON.stringify(get).includes('fixture MEMORY'), false, 'private contents never leave the API');+ const body = { uid: 'b', sourceUid: 'legacy', revision: get.body.revision };+ assert.equal((await h.run({ method: 'POST', url: '/api/persona-copy', body })).status, 400);+ assert.equal(fs.existsSync(path.join(h.dataRoot, 'user-b-personal/MEMORY.md')), false);+ assert.equal(h.locked(), false);+ const copy = await h.run({ method: 'POST', url: '/api/persona-copy', body: { ...body, confirmed: true } });+ assert.equal(copy.status, 200);+ assert.equal(copy.body.reloaded, true);+ assert.equal(copy.body.backedUp, true);+ assert.equal(h.reloads(), 1);+ assert.equal(h.locked(), false);+ assert.equal((await h.run({ method: 'GET', url: '/api/persona' })).body.eligible, false);+});+test('repairing destination leaves current renderer alone until normal switch', async t => {+ const h = harness(t);+ h.context.currentAccount = () => ({ uid: 'a' });+ h.context.listAccounts = () => [{ uid: 'a' }, { uid: 'b' }];+ const preview = await h.run({ method: 'GET', url: '/api/persona?uid=b' });+ const result = await h.run({ method: 'POST', url: '/api/persona-copy', body: { uid: 'b', sourceUid: 'legacy', confirmed: true, revision: preview.body.revision } });+ assert.equal(result.body.reloaded, false);+ assert.equal(h.reloads(), 0);+});+test('reload failure reports saved repair without claiming successful refresh', async t => {+ const h = harness(t);+ h.context.reloadWorkBuddyPage = async () => { throw new Error('disconnected'); };+ const preview = await h.run({ method: 'GET', url: '/api/persona' });+ const result = await h.run({ method: 'POST', url: '/api/persona-copy', body: { uid: 'b', sourceUid: 'legacy', confirmed: true, revision: preview.body.revision } });+ assert.equal(result.status, 200);+ assert.equal(result.body.reloaded, false);+ assert.ok(result.body.hint.includes('下次刷新'));+});+test('unknown accounts and non-WorkBuddy profiles cannot copy', async t => {+ const h = harness(t);+ assert.equal((await h.run({ method: 'GET', url: '/api/persona?uid=unknown' })).status, 400);+ h.context.PROFILE.kind = 'codebuddy';+ assert.equal((await h.run({ method: 'GET', url: '/api/persona' })).body.status, 'unsupported');+ assert.equal((await h.run({ method: 'POST', url: '/api/persona-copy', body: { uid: 'b', confirmed: true } })).status, 400);+});diff --git a/test/persona-migration.test.js b/test/persona-migration.test.jsnew file mode 100644index 0000000..8b5a7fc--- /dev/null+++ b/test/persona-migration.test.js@@ -0,0 +1,135 @@+'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 { inspectPersona, copyPersona } = require('../scripts/persona');+function fixture(t, scoped = true) {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-persona-')));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const dataRoot = path.join(root, '.workbuddy');+ const backupRoot = path.join(root, 'WorkDaddy');+ function write(dir, name, text) { fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true }); fs.writeFileSync(path.join(dir, name), text); }+ const target = path.join(dataRoot, 'user-b-personal');+ const source = path.join(dataRoot, 'user-a-personal');+ for (const name of ['IDENTITY.md', 'USER.md', 'SOUL.md', 'MEMORY.md']) write(dataRoot, name, 'legacy ' + name);+ if (scoped) write(dataRoot, 'storage/device/global/user-data-migration.json', JSON.stringify({ migrationItems: { persona: true }, migrationStatus: 'done' }));+ const opts = { dataRoot, backupRoot, targetUid: 'b', accounts: [{ uid: 'a', nickname: 'A' }, { uid: 'b', nickname: 'B' }] };+ function preview() { return inspectPersona(opts); }+ function copy(extra = {}) { return copyPersona({ ...opts, sourceUid: 'legacy', confirmed: true, revision: preview().revision, ...extra }); }+ return { root, dataRoot, target, source, opts, write, preview, copy };+}+test('old global layout is untouched and never creates scoped directories', t => {+ const f = fixture(t, false);+ assert.equal(f.preview().status, 'legacy');+ assert.throws(() => f.copy(), /无需修复/);+ assert.equal(fs.existsSync(f.target), false);+});+test('new layout with missing target copies complete legacy identity after consent', t => {+ const f = fixture(t);+ assert.equal(f.preview().status, 'missing');+ assert.throws(() => f.copy({ confirmed: false }), /确认/);+ const r = f.copy();+ assert.equal(r.files, 4);+ assert.equal(fs.readFileSync(path.join(f.target, 'MEMORY.md'), 'utf8'), 'legacy MEMORY.md');+ assert.ok(JSON.parse(fs.readFileSync(path.join(f.target, 'workspace-state.json'))).onboardingCompletedAt);+ assert.equal(f.preview().status, 'initialized');+});+test('existing scoped directories signal new layout without migration marker', t => {+ const f = fixture(t, false);+ f.write(f.source, 'USER.md', 'independent');+ assert.equal(f.preview().status, 'missing');+});+test('bootstrap repair backs up exact target, preserves unrelated state/files and global source', t => {+ const f = fixture(t);+ f.write(f.target, 'BOOTSTRAP.md', 'onboarding');+ f.write(f.target, 'IDENTITY.md', 'template');+ f.write(f.target, 'workspace-state.json', JSON.stringify({ version: 1, bootstrapSeededAt: 'before', custom: 7 }));+ f.write(f.target, 'unrelated.txt', 'keep');+ const r = f.copy();+ assert.equal(fs.readFileSync(path.join(r.backupDir, 'IDENTITY.md'), 'utf8'), 'template');+ assert.equal(fs.readFileSync(path.join(r.backupDir, 'BOOTSTRAP.md'), 'utf8'), 'onboarding');+ assert.equal(fs.existsSync(path.join(f.target, 'BOOTSTRAP.md')), false);+ assert.equal(fs.readFileSync(path.join(f.target, 'unrelated.txt'), 'utf8'), 'keep');+ const state = JSON.parse(fs.readFileSync(path.join(f.target, 'workspace-state.json')));+ assert.equal(state.custom, 7);+ assert.equal(state.bootstrapSeededAt, 'before');+ assert.equal(fs.readFileSync(path.join(f.dataRoot, 'MEMORY.md'), 'utf8'), 'legacy MEMORY.md');+});+test('explicit scoped source wins over stale legacy files', t => {+ const f = fixture(t);+ for (const name of ['IDENTITY.md', 'USER.md', 'SOUL.md', 'MEMORY.md']) f.write(f.source, name, 'scoped ' + name);+ assert.deepEqual(f.preview().sources.map(s => s.uid), ['a', 'legacy']);+ f.copy({ sourceUid: 'a' });+ assert.equal(fs.readFileSync(path.join(f.target, 'MEMORY.md'), 'utf8'), 'scoped MEMORY.md');+});+for (const variant of ['memory', 'completed', 'partial']) test('protect independent target: ' + variant, t => {+ const f = fixture(t);+ if (variant === 'memory') { f.write(f.target, 'MEMORY.md', 'independent'); f.write(f.target, 'BOOTSTRAP.md', 'stale'); }+ if (variant === 'completed') f.write(f.target, 'workspace-state.json', '{"onboardingCompletedAt":"before"}');+ if (variant === 'partial') f.write(f.target, 'USER.md', 'custom persona');+ assert.equal(f.preview().eligible, false);+ assert.throws(() => f.copy(), /无需修复/);+});+test('changed target requires another preview and confirmation', t => {+ const f = fixture(t);+ const revision = f.preview().revision;+ f.write(f.target, 'BOOTSTRAP.md', 'new');+ assert.throws(() => f.copy({ revision }), /已变化/);+ assert.equal(fs.existsSync(path.join(f.target, 'MEMORY.md')), false);+});+test('reject traversal, unknown account, symlink directory/file and oversized source', t => {+ const f = fixture(t);+ assert.throws(() => inspectPersona({ ...f.opts, targetUid: '../outside' }), /账号/);+ assert.throws(() => f.copy({ sourceUid: 'unknown' }), /来源/);+ fs.symlinkSync(f.dataRoot, f.target, 'dir');+ assert.throws(() => f.copy(), /链接/);+ fs.unlinkSync(f.target);+ fs.mkdirSync(f.target);+ fs.symlinkSync(path.join(f.dataRoot, 'USER.md'), path.join(f.target, 'USER.md'));+ assert.throws(() => f.copy(), /链接/);+ fs.unlinkSync(path.join(f.target, 'USER.md'));+ fs.truncateSync(path.join(f.dataRoot, 'MEMORY.md'), 20 * 1024 * 1024 + 1);+ assert.throws(() => f.copy(), /过大/);+});+test('write failure rolls back all target files and retains backup', t => {+ const f = fixture(t);+ f.write(f.target, 'BOOTSTRAP.md', 'keep bootstrap');+ f.write(f.target, 'IDENTITY.md', 'keep identity');+ let calls = 0;+ const { replaceFileWithRetry } = require('../scripts/atomic-file-write');+ assert.throws(() => f.copy({ replaceFile(file, text, mode) { if (++calls === 2) throw new Error('simulated lock'); replaceFileWithRetry(file, text, mode); } }), /simulated lock/);+ assert.equal(fs.readFileSync(path.join(f.target, 'IDENTITY.md'), 'utf8'), 'keep identity');+ assert.equal(fs.readFileSync(path.join(f.target, 'BOOTSTRAP.md'), 'utf8'), 'keep bootstrap');+ assert.equal(fs.existsSync(path.join(f.target, 'MEMORY.md')), false);+});+test('empty or incomplete source never marks onboarding completed', t => {+ const f = fixture(t);+ fs.unlinkSync(path.join(f.dataRoot, 'USER.md'));+ assert.equal(f.preview().eligible, false);+ assert.throws(() => f.copy(), /无需修复/);+ assert.equal(fs.existsSync(f.target), false);+});++test('a null migration marker does not move an old client out of global layout', t => {+ const f = fixture(t, false);+ f.write(f.dataRoot, 'storage/device/global/user-data-migration.json', 'null');+ assert.equal(f.preview().status, 'legacy');+ assert.equal(fs.existsSync(f.target), false);+});+test('official onboarding completed during backup is protected before any replacement', t => {+ const f = fixture(t);+ f.write(f.target, 'BOOTSTRAP.md', 'before');+ const writeFile = fs.writeFileSync;+ fs.writeFileSync = function (file, ...args) {+ const result = writeFile.call(fs, file, ...args);+ if (String(file).includes(path.join('WorkDaddy', 'persona'))) writeFile(path.join(f.target, 'MEMORY.md'), 'new independent memory');+ return result;+ };+ try { assert.throws(() => f.copy(), /已变化/); }+ finally { fs.writeFileSync = writeFile; }+ assert.equal(fs.readFileSync(path.join(f.target, 'MEMORY.md'), 'utf8'), 'new independent memory');+ assert.equal(fs.readFileSync(path.join(f.target, 'BOOTSTRAP.md'), 'utf8'), 'before');+ assert.equal(fs.existsSync(path.join(f.target, 'IDENTITY.md')), false);+});diff --git a/test/persona-switch-preflight.test.js b/test/persona-switch-preflight.test.jsnew file mode 100644index 0000000..967eb2d--- /dev/null+++ b/test/persona-switch-preflight.test.js@@ -0,0 +1,47 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const vm = require('node:vm');+const path = require('node:path');+const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+const apiSource = inject.slice(inject.indexOf(' function api(path, opts) {'), inject.indexOf(' // 调试:递归收集所有元素'));++test('persona repair remains available in code but is disabled in the current account UI and switch flow', () => {+ assert.match(inject, /暂停身份资料提醒入口:保留修复代码/);+ assert.match(inject, /暂停身份资料修复入口:保留 beforePersonaSwitch\/openPersonaDialog/);+ assert.doesNotMatch(inject, /^\s*personaSwitchPreflight = beforePersonaSwitch;/m);+ assert.doesNotMatch(inject, /^\s*refreshPersonaNotice\(\);$/m);+ assert.doesNotMatch(inject, /^\s*'<div class="wbs-persona-notice"/m);+});++function harness(preflight) {+ const requests = [];+ const ctx = vm.createContext({ CAPS: {}, API: 'http://127.0.0.1', WBS_API_TOKEN: 'fixture-token', personaSwitchPreflight: preflight,+ fetch: async (url, request) => { requests.push({ url, request }); return { ok: true, json: async () => ({ ok: true }) }; },+ });+ vm.runInContext(apiSource, ctx);+ return { ctx, requests };+}+test('switch HTTP request waits for persona confirmation; internal bypass flag never reaches fetch', async () => {+ let confirm;+ const h = harness(uid => { assert.equal(uid, 'destination'); return new Promise(resolve => { confirm = resolve; }); });+ const pending = h.ctx.api('/api/switch', { method: 'POST', body: '{"uid":"destination","reload":true}' });+ assert.equal(h.requests.length, 0);+ confirm(); await pending;+ assert.equal(h.requests.length, 1);+ assert.equal(h.requests[0].request.body, '{"uid":"destination","reload":true}');+ assert.equal(h.requests[0].request._wbsPersonaChecked, undefined);+ assert.equal(h.requests[0].request.headers['X-WorkDaddy-Token'], 'fixture-token');+});+test('cancel or failed persona inspection never writes account authentication', async () => {+ const h = harness(() => Promise.reject(new Error('canceled')));+ await assert.rejects(h.ctx.api('/api/switch', { method: 'POST', body: '{"uid":"destination"}' }), /canceled/);+ assert.equal(h.requests.length, 0);+});+test('persona API and unrelated requests do not recurse through switch confirmation', async () => {+ const h = harness(() => { throw new Error('unexpected preflight'); });+ await h.ctx.api('/api/persona?uid=destination');+ await h.ctx.api('/api/persona-copy', { method: 'POST', body: '{}' });+ assert.equal(h.requests.length, 2);+});