WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
release: merge 1.2.15 changes
[email protected]a90bc404303e
diff --git a/scripts/build-linux-deb.sh b/scripts/build-linux-deb.shindex c8b893c..2109257 100644--- a/scripts/build-linux-deb.sh+++ b/scripts/build-linux-deb.sh@@ -186,6 +186,7 @@ def add_entry(archive, path, name):info = archive.gettarinfo(str(path), name)info.uid = info.gid = 0info.uname = info.gname = 'root'+ info.mtime = int(info.mtime)if info.isfile():with path.open('rb') as source:archive.addfile(info, source)@@ -199,9 +200,10 @@ def add_tree(archive, root, prefix='.'):with tempfile.TemporaryDirectory() as tmp:control = pathlib.Path(tmp, 'control.tar.xz')data = pathlib.Path(tmp, 'data.tar.xz')- with tarfile.open(control, 'w:xz') as archive:+ # Older dpkg rejects PAX extension headers, including fractional mtimes.+ with tarfile.open(control, 'w:xz', format=tarfile.USTAR_FORMAT) as archive:add_tree(archive, stage / 'DEBIAN')- with tarfile.open(data, 'w:xz') as archive:+ with tarfile.open(data, 'w:xz', format=tarfile.USTAR_FORMAT) as archive:for root in ('opt', 'usr'):add_entry(archive, stage / root, './' + root)add_tree(archive, stage / root, './' + root)diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 180a048..b6f50c5 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -28,7 +28,7 @@ const path = require('path');const os = require('os');const crypto = require('crypto');const net = require('net');-const { inspectPersona, copyPersona } = require('./persona.js');+const { inspectPersona, copyPersona, readPersonaSettings, listPersonaSources, configurePersona, dismissPersonaNotice, syncSharedPersonaForSwitch } = require('./persona.js');let sessionSync = require('./session-sync.js');const {createCodeBuddyFiles} = require('./codebuddy-files.js');const { createAccountCreditCache } = require('./account-credit-cache.js');@@ -489,12 +489,18 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// launcher 的 httpGet 预算同步对齐到 HTTP_GET_TIMEOUT_MS;Windows app.asar// 页面归属与 CDP 目标等待窗口也同步修复。// 1.2.35:账号页合并加密备份 token 刷新后的有效期快照,并按自然日限制成功刷新一次。-// 1.2.37:新版账号个人身份档案支持确认复制、备份及 CDP 刷新,兼容旧版全局目录。+// 1.2.37:新版账号个性化设置支持确认复制、备份及 CDP 刷新,兼容旧版全局目录。// 1.2.38:防止 --probe-client-running 探测进程再次派生探测进程;监控仅由持有单实例锁的 daemon 启动。// 1.2.39:限制 macOS pgrep 探针和父进程等待时间,避免系统过载时探针长期堆积。// 1.2.40:周期性客户端运行探测改用 tasklist 轻量存在性检查(不经 WMI),CIM 进程查询加 -Filter 服务端过滤,刷新间隔 5s→15s(可用 WORKDADDY_CLIENT_REFRESH_MS 覆盖);完整 CIM 验证仅保留给 /api/client/relaunch 等用户主动操作。-const DAEMON_VERSION = '1.2.40';-const DAEMON_BUILD_ID = 'release-1.2.40-20261014-client-probe-wmi';+// 1.2.41:会话工作目录巡检跳过已失效的卷,同一卷根只提示一次,卷恢复后自动继续修复。+// 1.2.42:账号设置支持共享身份与记忆,切换时同步最新档案并保留覆盖前备份。+// 1.2.44:精简来源选择文字,明确共享范围仅限身份与本地记忆。+// 1.2.45:同步功能统一使用 WorkBuddy 的「个性化」名称。+// 1.2.43:共享身份提示使用全局说明浮层,来源列出未设置账号并简化文案。+// 1.2.46:合入失效卷上的会话目录修复保护,避免后台反复尝试创建目录。+const DAEMON_VERSION = '1.2.46';+const DAEMON_BUILD_ID = 'release-1.2.46-session-cwd-volume-guard';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -1892,7 +1898,12 @@ function syncCodeBuddyAuth() {return work;}async function switchAccountForProfile(uid) {- if (!codeBuddyNative) return switchTo(DATA_DIR, uid, log);+ if (!codeBuddyNative) {+ const sharing = PROFILE.kind === 'workbuddy' ? syncSharedPersonaForSwitch({ dataRoot: PROFILE.dataRoot,+ backupRoot: DATA_DIR, accounts: listAccounts(DATA_DIR), sourceUid: String((currentAccount() || {}).uid || ''), targetUid: String(uid) }) : null;+ try { return await switchTo(DATA_DIR, uid, log); }+ catch (error) { if (sharing && sharing.rollback) sharing.rollback(); throw error; }+ }await syncCodeBuddyAuth();if (fs.existsSync(AUTH_FILE)) backupCurrent(DATA_DIR, log);const file = accountBackupFile(uid);@@ -4793,6 +4804,8 @@ function createDirectoryNoFollow(directory) {}let sessionCwdRepairInFlight = null;+// 只去重提示;每轮仍检查卷状态,盘符或共享恢复后无需重启 daemon。+const reportedMissingCwdRoots = new Set();function repairMissingSessionWorkspaces() {if (sessionCwdRepairInFlight) return sessionCwdRepairInFlight;sessionCwdRepairInFlight = (async () => {@@ -4800,10 +4813,17 @@ function repairMissingSessionWorkspaces() {const wbHome = path.dirname(SESSIONS_DB);const rows = await sqliteQuery("SELECT id, cwd FROM sessions WHERE deleted_at IS NULL AND cwd IS NOT NULL AND cwd != '';" );const repaired = [];+ const missingCwdRoots = new Set();let skipped = 0;for (const row of rows.slice(0, 2000)) {const cwd = String(row.cwd || '').trim();if (!cwd || fs.existsSync(cwd) || !sessionPayloadExists(wbHome, row.id)) { skipped++; continue; }+ const root = path.parse(cwd).root;+ if (root && !fs.existsSync(root)) {+ skipped++;+ missingCwdRoots.add(root);+ continue;+ }try {createDirectoryNoFollow(cwd);if (fs.statSync(cwd).isDirectory()) repaired.push(cwd);@@ -4812,6 +4832,12 @@ function repairMissingSessionWorkspaces() {log(`[sessions-cwd-repair] 跳过 ${cwd}: ${error.message}`);}}+ // 缺失卷的提示只记录卷根,避免写入完整会话路径。+ for (const root of missingCwdRoots) {+ if (reportedMissingCwdRoots.has(root)) continue;+ reportedMissingCwdRoots.add(root);+ log(`[sessions-cwd-repair] 跳过所在卷不存在的会话:${root}`);+ }if (repaired.length) log(`[sessions-cwd-repair] 已恢复 ${repaired.length} 个会话工作目录(消息文件未改动)`);return { repaired, skipped };})();@@ -10529,15 +10555,51 @@ function handleApi(req, res) {} catch (error) { return json(res, 400, { ok: false, error: error.message }); }}+ if (req.method === 'GET' && p === '/api/persona/settings') {+ try {+ if (PROFILE.kind !== 'workbuddy' || !PROFILE.capabilities.accounts) return json(res, 200, { ok: true, supported: false });+ const current = currentAccount();+ 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, supported: true, ...readPersonaSettings(DATA_DIR),+ currentUid: String(current && current.uid || ''), sources: listPersonaSources({ dataRoot: PROFILE.dataRoot, accounts }) });+ } catch (error) { return json(res, 400, { ok: false, error: error.message }); }+ }++ if (req.method === 'POST' && p === '/api/persona/settings') {+ return readBody(req).then(async body => {+ let release = null;+ try {+ if (PROFILE.kind !== 'workbuddy' || !PROFILE.capabilities.accounts) throw new Error('当前客户端不支持同步个性化');+ release = await assertAccountSwitchIdle();+ if (body.dismissNotice === true) return json(res, 200, { ok: true, ...dismissPersonaNotice(DATA_DIR) });+ const current = currentAccount();+ if (!current) throw new Error('请先登录账号');+ if (body.currentUid !== String(current.uid)) throw new Error('当前账号已变化,请重新打开设置');+ const accounts = listAccounts(DATA_DIR);+ if (!accounts.some(a => String(a.uid) === String(current.uid))) accounts.push(current);+ const result = configurePersona({ dataRoot: PROFILE.dataRoot, backupRoot: DATA_DIR, accounts,+ currentUid: String(current.uid), mode: body.mode, sourceUid: body.sourceUid, revision: body.revision });+ let reloaded = false;+ if (result.changed) {+ try { await reloadWorkBuddyPage({ waitForInjection: false, account: current }); reloaded = true; } catch (_) {}+ }+ return json(res, 200, { ok: true, ...result.settings, reloaded, reloadRequired: result.changed && !reloaded });+ } catch (error) { return json(res, 400, { ok: false, error: error.message }); }+ finally { if (release) release(); }+ });+ }+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('当前客户端不支持个人身份档案修复');+ 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);+ if (readPersonaSettings(DATA_DIR).mode === 'shared') throw new Error('共享模式下请在账号设置中选择来源');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;@@ -10545,9 +10607,9 @@ function handleApi(req, res) {try { await reloadWorkBuddyPage({ waitForInjection: false, account: current }); reloaded = true; }catch (_) { /* The disk repair is complete; report reload separately. */ }}- log('[persona] 个人身份档案复制完成,已保留修复前备份');+ log('[persona] 个性化设置复制完成,已保留修复前备份');return json(res, 200, { ok: true, files: result.files, backedUp: true, reloaded,- hint: reloaded ? '身份档案已复制并刷新窗口' : '身份档案已复制,下次刷新窗口后生效' });+ hint: reloaded ? '个性化设置已复制并刷新窗口' : '个性化设置已复制,下次刷新窗口后生效' });} catch (error) { return json(res, 400, { ok: false, error: error.message }); }finally { if (release) release(); }});diff --git a/scripts/inject.js b/scripts/inject.jsindex d828b85..4691da3 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -1424,32 +1424,38 @@ 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",+ "同步个性化": "Sync personalization",+ "不再提醒": "Don't remind me again",+ "了解同步个性化": "About personalization sync",+ "同步个性化设置": "Sync personalization settings",+ "让所有账号使用同一份个性化设置,修改后随账号切换一起更新。原有设置会自动备份。不包含「管理记忆」中的云端记忆。": "Use the same personalization settings across accounts. Changes sync when switching accounts. Existing settings are backed up. Cloud memory in Manage Memory is not included.",+ "各账号独立": "Separate per account",+ "所有账号共享": "Share across accounts",+ "所有账号使用同一份个性化设置。": "Use the same personalization settings across accounts.",+ "每个账号使用各自的个性化设置,已同步的内容会保留。": "Use separate personalization settings per account. Previously synced copies are kept.",+ "共享设置来源": "Shared settings source",+ "升级前共用的设置": "Settings shared before the upgrade",+ "未设置": "Not set up",+ "这是升级前所有账号共用的设置。": "These settings were shared by all accounts before the upgrade.",+ "请先在任一账号设置个性化。": "Set up personalization in any account first.",+ "个性化设置加载失败,请重新打开": "Could not load personalization settings. Reopen to retry.",+ "设置已保存,刷新 WorkBuddy 后生效": "Saved. Reload WorkBuddy to apply.",+ "请选择已完成设置的账号": "Choose an account that has been set up",+ "当前账号已变化,请重新打开设置": "The account changed. Reopen settings.",+ "来源个性化设置已变化,请重新选择": "The source changed. Select it again.",++ "个性化设置复制完成,已保留修复前备份": "Personalization settings copied; original settings backed up",+ "当前客户端不支持个性化设置修复": "Personalization repair is unavailable for this client",+ "个性化设置已复制并刷新窗口": "Personalization settings copied and window refreshed",+ "个性化设置已复制,下次刷新窗口后生效": "Personalization settings copied; refresh the window to apply",+ "请先确认复制个性化设置": "Confirm copying personalization settings 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",+ "目标个性化设置已变化,请重新查看并确认": "Target personalization settings changed; review and confirm again",+ "个性化设置来源无效": "Invalid personalization source",+ "个性化设置路径不能包含符号链接": "Personalization paths must not contain symbolic links",+ "个性化设置文件过大,未执行复制": "Personalization file too large; copy canceled",+ "个性化设置状态文件无效,请先手动检查": "Invalid personalization state; inspect it manually first",+ "个性化设置必须为普通文件": "Personalization 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",@@ -2491,17 +2497,8 @@ 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 = {};@@ -2511,7 +2508,6 @@ 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) {@@ -6622,8 +6618,7 @@ 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-persona-notice" hidden><span class="wbs-persona-notice-label"><span>同步个性化</span><button type="button" class="wbs-acct-eye wbs-persona-help" aria-label="了解同步个性化" aria-expanded="false">' + MODEL_TIP_SVG + '</button></span><span class="wbs-persona-notice-actions"><button type="button" class="wbs-modal-btn" data-act="persona-settings">设置</button><button type="button" class="wbs-persona-dismiss" data-act="persona-dismiss">不再提醒</button></span></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">';@@ -6643,106 +6638,111 @@ 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 (accountsPane && CAPS.accounts) {+ var personaHelp = accountsPane.querySelector('.wbs-persona-help');+ var personaHelpPinned = false;+ function hidePersonaHelp() {+ personaHelpPinned = false;+ personaHelp.setAttribute('aria-expanded', 'false');+ personaHelp.removeAttribute('aria-describedby');+ hideStatusPopover(personaHelp);+ }+ function showPersonaHelp() {+ showStatusPopover(personaHelp, '<div class="wbs-daily-popover-head"><strong>同步个性化设置</strong></div><div class="wbs-persona-help-copy">让所有账号使用同一份个性化设置,修改后随账号切换一起更新。原有设置会自动备份。不包含「管理记忆」中的云端记忆。</div>', 'persona', 'below');+ personaHelp.setAttribute('aria-describedby', 'wbs-status-popover');+ personaHelp.setAttribute('aria-expanded', 'true');+ }+ listen(personaHelp, 'mouseenter', showPersonaHelp);+ listen(personaHelp, 'mouseleave', function () { if (!personaHelpPinned && document.activeElement !== personaHelp) hidePersonaHelp(); });+ listen(personaHelp, 'focus', showPersonaHelp);+ listen(personaHelp, 'blur', hidePersonaHelp);+ listen(personaHelp, 'click', function () { personaHelpPinned = !personaHelpPinned; if (personaHelpPinned) showPersonaHelp(); else hidePersonaHelp(); });+ listen(document, 'pointerdown', function (event) { if (!personaHelp.contains(event.target)) hidePersonaHelp(); }, true);+ listen(document, 'keydown', function (event) {+ if (event.key === 'Escape' && statusPopoverOwner === personaHelp) { event.stopPropagation(); event.preventDefault(); hidePersonaHelp(); }+ }, true);+ listen(accountsPane, 'scroll', hidePersonaHelp, true);+ listen(window, 'resize', hidePersonaHelp);+ listen(accountsPane.querySelector('[data-act="persona-settings"]'), 'click', function () { hidePersonaHelp(); openAccountOrderModal(); });+ listen(accountsPane.querySelector('[data-act="persona-dismiss"]'), 'click', function () {+ hidePersonaHelp();+ var button = accountsPane.querySelector('[data-act="persona-dismiss"]');+ button.disabled = true;+ api('/api/persona/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ dismissNotice: true }) })+ .then(function () { if (alive) { state.personaRefreshId = (state.personaRefreshId || 0) + 1; accountsPane.querySelector('.wbs-persona-notice').hidden = true; } })+ .catch(function (error) { if (alive) toast(error.message, true, root); })+ .finally(function () { if (alive) button.disabled = false; });});}- 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');+ var notice = accountsPane && 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 () {});+ api('/api/persona/settings').then(function (info) {+ if (alive && requestId === state.personaRefreshId) notice.hidden = !info.supported || info.noticeDismissed || info.mode !== 'unset' || !info.currentUid;+ }).catch(function () { if (alive && requestId === state.personaRefreshId) notice.hidden = true; });+ }+ function setupPersonaSettings(mask) {+ var section = mask.querySelector('[data-persona-settings]');+ var info = null, mode = 'independent', needsSource = false;+ var select = section.querySelector('select');+ var save = mask.querySelector('[data-order-save]');+ save.disabled = true;+ function sync() {+ needsSource = !!info && mode === 'shared' && (info.mode !== 'shared' || info.activeUid !== info.currentUid);+ section.querySelector('[data-persona-source]').hidden = !needsSource;+ section.querySelector('[data-persona-description]').textContent = mode === 'shared'+ ? '所有账号使用同一份个性化设置。'+ : '每个账号使用各自的个性化设置,已同步的内容会保留。';+ var sourceHint = section.querySelector('[data-persona-source-hint]');+ sourceHint.textContent = info && !info.sources.some(function (source) { return source.available; })+ ? '请先在任一账号设置个性化。'+ : select.value === 'legacy' ? '这是升级前所有账号共用的设置。' : '';+ sourceHint.hidden = !sourceHint.textContent;+ applyI18n(section);+ }+ section.addEventListener('change', function (event) { if (event.target.name === 'wbs-persona-mode') { mode = event.target.value; sync(); } });+ var loaded = api('/api/persona/settings').then(function (result) {+ if (!alive || !mask.isConnected) return;+ info = result;+ save.disabled = false;+ if (!info.supported) { section.hidden = true; return; }+ mode = info.mode === 'shared' ? 'shared' : 'independent';+ section.querySelectorAll('[name="wbs-persona-mode"]').forEach(function (radio) { radio.disabled = false; radio.checked = radio.value === mode; });+ info.sources.forEach(function (source) {+ var option = document.createElement('option'); option.value = source.uid;+ var name = source.uid === 'legacy' ? wbsTranslateString('升级前共用的设置', WBS_LANGUAGE) : state.mask ? maskAccountName(source.nickname) : source.nickname;+ option.textContent = name + (source.available ? '' : ' · ' + wbsTranslateString('未设置', WBS_LANGUAGE));+ option.disabled = !source.available;+ option.setAttribute('data-wbs-i18n-skip', '');+ select.appendChild(option);+ });+ var initialSource = info.sources.find(function (source) { return source.available && source.uid === info.currentUid; }) || info.sources.find(function (source) { return source.available; });+ select.value = initialSource ? initialSource.uid : '';+ select.addEventListener('change', sync);+ section.querySelector('[data-persona-loading]').hidden = true;+ sync();+ }).catch(function (error) {+ if (mask.isConnected) section.querySelector('[data-persona-loading]').textContent = '个性化设置加载失败,请重新打开';+ throw error;+ });+ // Keep the rejection handled even if the user cancels instead of saving.+ loaded.catch(function () {});+ return function () {+ return loaded.then(function () {+ if (!info || !info.supported) return;+ var source = needsSource && info.sources.find(function (item) { return item.uid === select.value && item.available; });+ if (needsSource && !source) throw new Error('请选择已完成设置的账号');+ if (info.mode === mode && !needsSource) return;+ return api('/api/persona/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ mode: mode, currentUid: info.currentUid, sourceUid: source ? source.uid : undefined, revision: source ? source.revision : undefined })+ }).then(function (result) {+ info.mode = result.mode; info.activeUid = result.activeUid;+ refreshPersonaNotice();+ if (result.reloadRequired) toast('设置已保存,刷新 WorkBuddy 后生效', false, root);+ });+ });+ };}function initialAutoCopyAllSeen() {@@ -6831,6 +6831,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});mask.innerHTML = '<div class="wbs-modal wbs-account-order-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-account-order-title">' +'<div class="wbs-modal-title" id="wbs-account-order-title">账号设置</div>' ++ '<section data-persona-settings><div class="wbs-account-settings-section">同步个性化</div>' ++ '<div class="wbs-account-order-modes"><label><input type="radio" name="wbs-persona-mode" value="independent" disabled>各账号独立</label><label><input type="radio" name="wbs-persona-mode" value="shared" disabled>所有账号共享</label></div>' ++ '<div class="wbs-persona-description" data-persona-loading role="status">加载中…</div><div class="wbs-persona-description" data-persona-description></div>' ++ '<div data-persona-source hidden><label class="wbs-persona-source-label"><select aria-label="共享设置来源"></select></label>' ++ '<div class="wbs-persona-description" data-persona-source-hint hidden></div></div></section>' +'<div class="wbs-account-settings-section">排序方式</div>' +'<div class="wbs-account-order-modes"><label><input type="radio" name="wbs-account-order" value="expiry">按积分临近时间</label>' +'<label><input type="radio" name="wbs-account-order" value="fixed">固定顺序</label></div>' +@@ -6844,6 +6849,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<button class="wbs-modal-btn" type="button" data-order-cancel>取消</button>' +'<button class="wbs-modal-btn wbs-modal-ok" type="button" data-order-save>保存</button></div></div>';panel.appendChild(mask);+ var savePersonaSettings = setupPersonaSettings(mask);var list = mask.querySelector('.wbs-account-order-list');mask.querySelector('[data-rotation-reminder]').checked = rotationReminderEnabled();mask.querySelector('[data-account-note-hover]').checked = accountNoteHoverEnabled();@@ -6911,7 +6917,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {move(from, from + (event.key === 'ArrowUp' ? -1 : 1));}if (event.key === 'Tab') {- var focusable = Array.from(mask.querySelectorAll('button,input')).filter(function (node) { return !node.disabled && node.getClientRects().length; });+ var focusable = Array.from(mask.querySelectorAll('button,input,select')).filter(function (node) { return !node.disabled && node.getClientRects().length; });var first = focusable[0], last = focusable[focusable.length - 1];if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }@@ -6928,10 +6934,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var noteHover = mask.querySelector('[data-account-note-hover]').checked;var growthHover = mask.querySelector('[data-growth-plan-hover]').checked;busy = true;- mask.querySelectorAll('button,input').forEach(function (node) { node.disabled = true; });+ mask.querySelectorAll('button,input,select').forEach(function (node) { node.disabled = true; });mask.querySelector('[data-order-save]').textContent = '保存中…';api('/api/accounts/order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mode: mode, uids: ordered.map(function (a) { return a.uid; }) }) }).then(function (result) {+ return savePersonaSettings().then(function () { return result; });+ }).then(function (result) {state.accountOrder = result.accountOrder;var ranks = new Map(); ordered.forEach(function (a, index) { ranks.set(a.uid, index + 1); });state.accounts.forEach(function (a) { a.sort = ranks.get(a.uid) || 0; });@@ -6946,7 +6954,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {busy = false; close();}).catch(function (error) {busy = false;- mask.querySelectorAll('button,input').forEach(function (node) { node.disabled = false; });+ mask.querySelectorAll('button,input,select').forEach(function (node) { node.disabled = false; });mask.querySelector('[data-order-save]').textContent = '保存';mask.querySelector('[role="alert"]').textContent = error.message || '保存排序失败';});@@ -16564,8 +16572,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {.then(function (data) {if (!alive || requestId !== state.accountRefreshId) return;render(data);- // 暂停身份资料提醒:后续版本重新设计文案和交互后再启用。- // refreshPersonaNotice();+ 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@@ -17956,8 +17963,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-persona-notice-label{display:flex;align-items:center;gap:4px;flex:1;min-width:0;overflow-wrap:anywhere}.wbs-persona-notice .wbs-persona-help{flex:0 0 24px;width:24px;height:24px;color:var(--wb-color-text-secondary)}.wbs-persona-notice .wbs-persona-help:hover{color:var(--wb-color-text-primary);background:var(--wb-bg-hover)}.wbs-persona-notice-actions{display:flex;align-items:center;gap:8px;flex:none;margin-left:auto}.wbs-persona-dismiss{padding:4px 0;border:0;background:transparent;color:var(--wb-color-text-secondary);font:inherit;font-size:11px;white-space:nowrap;cursor:pointer}.wbs-persona-dismiss:hover{color:var(--wb-color-text-primary)}.wbs-persona-dismiss:disabled{opacity:.5;cursor:default}.wbs-persona-notice button:focus-visible{outline:2px solid var(--wb-accent-primary,var(--wb-color-text-primary));outline-offset:2px}.wbs-acct-toolbar:has(+.wbs-persona-notice:not([hidden])){border-bottom-color:transparent}.wbs-status-popover.is-persona{max-width:calc(100vw - 16px)}.wbs-persona-help-copy{font-size:12px;line-height:1.6;overflow-wrap:anywhere;color:var(--wb-color-text-secondary)}.wbs-persona-description{font-size:11px;line-height:1.5;color:var(--wb-color-text-secondary);margin:7px 0;overflow-wrap:anywhere}.wbs-persona-source-label{display:flex;flex-direction:column;gap:6px;margin-top:10px;font-size:12px}.wbs-persona-source-label select{box-sizing:border-box;width:100%;min-width:0;padding:7px 9px;border:1px solid var(--wb-border-subtle);border-radius:8px;background:var(--wb-bg-secondary);color:var(--wb-color-text-primary);font:inherit}.wbs-account-order-modal section{flex-shrink:0}.wbs-account-order-modal :is(input,select):disabled{opacity:.5}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i],body[data-vscode-theme-name*="night" i]) .wbs-account-order-modal{color-scheme:dark}',+ '.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-default,#ddd);border-radius:9px;background:var(--wb-bg-secondary,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);font-size:12px}','.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}',@@ -17970,8 +17977,6 @@ 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}',@@ -18134,7 +18139,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-account-order-list{margin-top:9px;padding:1px;max-height:min(280px,40vh);overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:5px}','.wbs-account-order-row{display:flex;align-items:center;gap:8px;min-height:34px;padding:3px 8px;border:1px solid var(--wb-border-subtle);border-radius:8px;background:var(--wb-bg-secondary);font-size:12px}.wbs-account-order-row>span{flex:1;min-width:0;overflow-wrap:anywhere}.wbs-account-order-row button{cursor:grab}.wbs-account-order-row.dragging{opacity:.45}.wbs-account-order-row.drop-target{border-color:var(--wb-accent-blue);background:var(--wb-bg-hover)}',- '.wbs-account-order-modal>.wbs-modal-actions{margin-top:14px;padding-top:10px;border-top:1px solid var(--wb-border-subtle,#eee)}.wbs-account-order-modal :is(button,input):focus-visible{outline:2px solid var(--wb-accent-blue);outline-offset:2px}.wbs-account-order-modal button:disabled{opacity:.5;cursor:default}',+ '.wbs-account-order-modal>.wbs-modal-actions{margin-top:14px;padding-top:10px;border-top:1px solid var(--wb-border-subtle,#eee)}.wbs-account-order-modal :is(button,input,select):focus-visible{outline:2px solid var(--wb-accent-blue);outline-offset:2px}.wbs-account-order-modal button:disabled{opacity:.5;cursor:default}',+ ':is(.wbs-account-order-modal,.wbs-persona-notice) .wbs-modal-btn:not(.wbs-modal-ok){color:var(--wb-color-text-secondary,#666)}:is(.wbs-account-order-modal,.wbs-persona-notice) .wbs-modal-btn:not(.wbs-modal-ok):hover{color:var(--wb-color-text-primary,#1f1f1f)}','@media(max-width:420px){.wbs-account-order-modal{width:100%;max-width:calc(100% - 20px)}.wbs-account-order-modes{grid-template-columns:1fr}}','html[data-wbs-theme-id="nebula"] .wbs-account-note-footer .primary{background:rgba(255,255,255,.9) !important;border-color:rgba(255,255,255,.9) !important;color:#11121a !important}.wbs-account-note-footer .primary:focus-visible{outline-color:var(--wb-color-text-primary,#1f1f1f)}html[data-wbs-theme-id="nebula"] .wbs-account-note-footer .primary:disabled{background:rgba(255,255,255,.78) !important;border-color:rgba(255,255,255,.78) !important;color:#34343c !important;opacity:1 !important}','.wbs-initial-sync-modal{box-sizing:border-box;width:380px;max-width:calc(100% - 28px)}.wbs-initial-sync-copy{margin:-2px 0 12px;color:var(--wb-color-text-secondary,#666);font-size:11.5px;line-height:1.6;overflow-wrap:anywhere}.wbs-initial-sync-toggle{margin:0 0 10px}.wbs-initial-sync-error{min-height:17px;margin:0 0 2px}.wbs-initial-sync-modal .wbs-modal-actions{justify-content:flex-end}.wbs-initial-sync-modal .wbs-modal-ok{min-width:66px}',diff --git a/scripts/persona.js b/scripts/persona.jsindex 5d20c83..499d708 100644--- a/scripts/persona.js+++ b/scripts/persona.js@@ -1,6 +1,6 @@'use strict';-// Only explicit, confirmed repairs cross the global -> personal layout boundary.+// Only an explicit repair or shared-mode source selection imports a legacy profile.// Metadata returned to the renderer never includes identity or memory contents.const fs = require('node:fs');const path = require('node:path');@@ -9,6 +9,7 @@ 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;+const PERSONA_MODES = ['unset', 'shared', 'independent'];function validUid(uid) { return typeof uid === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(uid); }function personaDir(root, uid) {@@ -18,7 +19,7 @@ function personaDir(root, uid) {function assertSafePath(file) {let cursor = path.resolve(file);for (;;) {- try { if (fs.lstatSync(cursor).isSymbolicLink()) throw new Error('身份档案路径不能包含符号链接'); }+ 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;@@ -33,8 +34,8 @@ function snapshot(dir) {assertSafePath(file);try {const stat = fs.lstatSync(file);- if (!stat.isFile()) throw new Error('身份档案必须为普通文件');- if (stat.size > MAX_FILE_SIZE) throw new Error('身份档案文件过大,未执行复制');+ 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; }}@@ -46,7 +47,7 @@ function stateOf(files) {const value = JSON.parse(files['workspace-state.json'].text);if (value && typeof value === 'object' && !Array.isArray(value)) return value;} catch (_) {}- throw new Error('身份档案状态文件无效,请先手动检查');+ 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()); }@@ -91,15 +92,159 @@ function inspectPersona(options) {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)) });+ 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 personaSettingsFile(backupRoot) {+ const file = path.join(path.resolve(backupRoot), 'persona', 'settings.json');+ assertSafePath(file);+ return file;+}+function normalizePersonaSettings(value) {+ if (!value || !PERSONA_MODES.includes(value.mode) || typeof value.noticeDismissed !== 'boolean' ||+ (value.mode === 'shared' && !validUid(value.activeUid))) throw new Error('个性化设置无效');+ return { mode: value.mode, noticeDismissed: value.noticeDismissed, activeUid: value.mode === 'shared' ? value.activeUid : null };+}+function readPersonaSettings(backupRoot) {+ try {+ const file = personaSettingsFile(backupRoot), stat = fs.lstatSync(file);+ if (!stat.isFile() || stat.size > MAX_FILE_SIZE) throw new Error('invalid');+ return normalizePersonaSettings(JSON.parse(fs.readFileSync(file, 'utf8')));+ } catch (error) {+ if (error.code === 'ENOENT') return { mode: 'unset', noticeDismissed: false, activeUid: null };+ throw new Error('个性化设置无法读取,请检查 WorkDaddy 的 persona 目录');+ }+}+function writePersonaSettings(backupRoot, value) {+ const settings = normalizePersonaSettings(value);+ const file = personaSettingsFile(backupRoot);+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });+ replaceFileWithRetry(file, JSON.stringify(settings, null, 2) + '\n', 0o600);+ return settings;+}+function dismissPersonaNotice(backupRoot) {+ return writePersonaSettings(backupRoot, { ...readPersonaSettings(backupRoot), noticeDismissed: true });+}+function sharedPersonaDir(backupRoot) {+ const dir = path.join(path.resolve(backupRoot), 'persona', 'shared');+ assertSafePath(dir);+ return dir;+}+function listPersonaSources({ dataRoot, accounts = [] }) {+ const sources = [];+ for (const account of [...accounts.filter(a => a.uid !== 'legacy'), { uid: 'legacy', nickname: '升级前共用的设置' }]) {+ const uid = String(account.uid || '');+ if (!validUid(uid)) continue;+ const files = snapshot(uid === 'legacy' ? path.resolve(dataRoot) : personaDir(dataRoot, uid));+ const available = usableSource(files);+ if (uid === 'legacy' && !available) continue;+ sources.push({ uid, nickname: String(account.nickname || uid), available,+ ...(available ? { files: IDENTITY_FILES.filter(name => nonempty(files, name)), revision: fingerprint(files) }+ : { unavailableReason: '未设置' }) });+ }+ return sources;+}+function backupPersonaDirectory(backupRoot, label, original) {+ const dir = path.join(path.resolve(backupRoot), 'persona', 'backups', label,+ `${Date.now()}-${crypto.randomBytes(6).toString('hex')}`);+ assertSafePath(dir);+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });+ for (const name of Object.keys(original)) fs.writeFileSync(path.join(dir, name), original[name].text, { mode: 0o600, flag: 'wx' });+}+// A single canonical copy is projected into WorkBuddy's required per-account files.+// WorkBuddy can edit the active projection; the switch seam captures it before auth changes.+function applySharedPersona(options, sourceFiles, settings) {+ const { dataRoot, backupRoot, targetUid } = options;+ if (!usableSource(sourceFiles)) throw new Error('来源个性化设置尚未完成,请先完成个性化设置');+ const targetDir = personaDir(dataRoot, targetUid);+ const sharedDir = sharedPersonaDir(backupRoot);+ const originalTarget = snapshot(targetDir), originalShared = snapshot(sharedDir);+ const targetState = stateOf(originalTarget);+ const completedState = { ...targetState, version: targetState.version || 1,+ onboardingCompletedAt: targetState.onboardingCompletedAt || new Date().toISOString() };+ const identity = Object.fromEntries(IDENTITY_FILES.filter(name => sourceFiles[name]).map(name => [name, sourceFiles[name]]));+ const nextTarget = { ...identity, 'workspace-state.json': { text: JSON.stringify(completedState, null, 2) + '\n', mode: 0o600 } };+ const settingsFile = personaSettingsFile(backupRoot);+ const oldSettings = fs.existsSync(settingsFile) ? fs.readFileSync(settingsFile, 'utf8') : null;+ const plans = [+ { dir: sharedDir, before: originalShared, after: identity, label: 'shared' },+ { dir: targetDir, before: originalTarget, after: nextTarget, label: targetUid },+ ].map(plan => ({ ...plan, existed: fs.existsSync(plan.dir), names: PERSONA_FILES.filter(name =>+ (plan.before[name] && plan.before[name].text) !== (plan.after[name] && plan.after[name].text)) }));+ for (const plan of plans) if (plan.names.length) backupPersonaDirectory(backupRoot, plan.label, plan.before);+ // Do not overwrite files WorkBuddy changed during backup creation.+ if (fingerprint(snapshot(options.sourceDir)) !== fingerprint(sourceFiles)) throw new Error('来源个性化设置已变化,请重试');+ for (const plan of plans) if (fingerprint(snapshot(plan.dir)) !== fingerprint(plan.before)) throw new Error('个性化设置已变化,请重试');+ const touched = [];+ let settingsTouched = false;+ function rollback() {+ try {+ for (const plan of touched.slice().reverse()) {+ for (const name of plan.names) {+ const file = path.join(plan.dir, name);+ if (plan.before[name]) replaceFileWithRetry(file, plan.before[name].text, plan.before[name].mode);+ else fs.rmSync(file, { force: true });+ }+ if (!plan.existed && !fs.readdirSync(plan.dir).length) fs.rmdirSync(plan.dir);+ }+ if (settingsTouched) {+ if (oldSettings === null) fs.rmSync(settingsFile, { force: true });+ else replaceFileWithRetry(settingsFile, oldSettings, 0o600);+ }+ } catch (_) { throw new Error('共享失败且回滚未完成,请从 WorkDaddy 的 persona/backups 目录恢复'); }+ }+ try {+ for (const plan of plans) {+ if (!plan.names.length) continue;+ fs.mkdirSync(plan.dir, { recursive: true, mode: 0o700 });+ touched.push(plan);+ for (const name of plan.names) {+ const file = path.join(plan.dir, name);+ assertSafePath(file);+ if (plan.after[name]) (options.replaceFile || replaceFileWithRetry)(file, plan.after[name].text, 0o600);+ else fs.rmSync(file, { force: true });+ }+ }+ settingsTouched = true;+ writePersonaSettings(backupRoot, settings);+ } catch (error) { rollback(); throw error; }+ return { changed: plans.some(plan => plan.names.length), rollback };+}+function configurePersona(options) {+ const settings = readPersonaSettings(options.backupRoot);+ if (!['shared', 'independent'].includes(options.mode)) throw new Error('个性化模式无效');+ if (options.mode === 'independent' || (settings.mode === 'shared' && options.mode === 'shared' && !options.sourceUid)) {+ return { settings: writePersonaSettings(options.backupRoot, { ...settings, mode: options.mode, noticeDismissed: true,+ activeUid: options.mode === 'shared' ? settings.activeUid : null }), changed: false };+ }+ if (!options.accounts.some(a => String(a.uid) === options.currentUid)) throw new Error('当前账号不存在');+ if (!scopedLayout(options.dataRoot)) throw new Error('当前版本尚未启用独立个性化目录,无需开启共享');+ const source = listPersonaSources(options).find(a => a.uid === options.sourceUid && a.available);+ if (!source) throw new Error('请选择可用的个性化设置来源');+ if (!options.revision || source.revision !== options.revision) throw new Error('来源个性化设置已变化,请重新选择');+ const sourceDir = source.uid === 'legacy' ? path.resolve(options.dataRoot) : personaDir(options.dataRoot, source.uid);+ const files = snapshot(sourceDir);+ if (fingerprint(files) !== options.revision) throw new Error('来源个性化设置已变化,请重新选择');+ const next = { mode: 'shared', noticeDismissed: true, activeUid: options.currentUid };+ const result = applySharedPersona({ ...options, sourceDir, targetUid: options.currentUid }, files, next);+ return { settings: next, changed: result.changed };+}+function syncSharedPersonaForSwitch(options) {+ const settings = readPersonaSettings(options.backupRoot);+ if (settings.mode !== 'shared' || options.sourceUid === options.targetUid) return { skipped: true };+ if (settings.activeUid !== options.sourceUid) throw new Error('当前账号已变化,请在账号设置中重新选择共享来源');+ if (!options.accounts.some(a => String(a.uid) === options.targetUid)) throw new Error('目标账号不存在');+ const sourceDir = personaDir(options.dataRoot, options.sourceUid);+ const files = snapshot(sourceDir);+ return applySharedPersona({ ...options, sourceDir }, files, { ...settings, activeUid: options.targetUid });+}function copyPersona(options) {- if (options.confirmed !== true) throw new Error('请先确认复制身份档案');+ 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('身份档案来源无效');+ 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);@@ -114,7 +259,7 @@ function copyPersona(options) {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('目标身份档案已变化,请重新查看并确认');+ 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;@@ -133,4 +278,8 @@ function copyPersona(options) {}return { status: 'copied', files: Object.keys(writes).length - 1, backupDir };}-module.exports = { PERSONA_FILES, personaDir, inspectPersona, copyPersona };+module.exports = {+ PERSONA_FILES, PERSONA_MODES, personaDir, inspectPersona, copyPersona,+ personaSettingsFile, readPersonaSettings, writePersonaSettings,+ sharedPersonaDir, listPersonaSources, configurePersona, dismissPersonaNotice, syncSharedPersonaForSwitch,+};diff --git a/test/linux-release-script.test.js b/test/linux-release-script.test.jsindex 1a4f097..501b953 100644--- a/test/linux-release-script.test.js+++ b/test/linux-release-script.test.js@@ -2,6 +2,7 @@const assert = require('node:assert/strict');const fs = require('node:fs');+const os = require('node:os');const path = require('node:path');const { spawnSync } = require('node:child_process');const test = require('node:test');@@ -9,12 +10,72 @@ const test = require('node:test');const root = path.join(__dirname, '..');const script = path.join(root, 'scripts', 'build-linux-deb.sh');+test('cross-packager writes tar headers supported by older dpkg with fractional file timestamps', (t) => {+ const python = (process.platform === 'win32' ? ['python', 'python3'] : ['python3', 'python'])+ .find(command => spawnSync(command, ['-c', 'import sys, tarfile, lzma; assert sys.version_info >= (3, 8)']).status === 0);+ if (!python) {+ t.skip('Requires Python 3.8+ with lzma for the cross-packager');+ return;+ }+ const source = fs.readFileSync(script, 'utf8');+ const packager = source.match(/<<'PY'\n([\s\S]*?)\nPY/)[1];+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-deb-compat-'));+ try {+ const stage = path.join(temp, 'stage');+ const scripts = path.join(stage, 'opt/workdaddy/scripts');+ fs.mkdirSync(path.join(stage, 'DEBIAN'), { recursive: true });+ fs.mkdirSync(path.join(stage, 'usr/share/applications'), { recursive: true });+ fs.mkdirSync(path.join(scripts, 'runtime/node'), { recursive: true });+ fs.writeFileSync(path.join(stage, 'DEBIAN/control'), 'Package: workdaddy\nVersion: 1.2.14\nArchitecture: amd64\n');+ const daemon = path.join(scripts, 'daemon.js');+ fs.writeFileSync(daemon, "const DAEMON_VERSION = '1.2.14';\n");+ fs.utimesSync(daemon, 1700000000.125, 1700000000.125);+ const elf = Buffer.alloc(20);+ elf.set([0x7f, 0x45, 0x4c, 0x46, 0x02]);+ elf.writeUInt16LE(62, 18);+ fs.writeFileSync(path.join(scripts, 'runtime/node/node'), elf, { mode: 0o755 });+ const longPath = path.join(scripts, 'builtin', 'a'.repeat(70), 'theme.json');+ fs.mkdirSync(path.dirname(longPath), { recursive: true });+ fs.writeFileSync(longPath, '{}');+ const checkHeaders = `+import io+import lzma+with output.open('rb') as deb:+ deb.seek(8)+ for expected in ('debian-binary', 'control.tar.xz', 'data.tar.xz'):+ header = deb.read(60)+ size = int(header[48:58])+ contents = deb.read(size)+ deb.read(size % 2)+ if not expected.endswith('.tar.xz'):+ continue+ raw = lzma.decompress(contents)+ offset = 0+ while any(raw[offset:offset + 512]):+ block = raw[offset:offset + 512]+ assert block[156:157] in (b'0', b'5'), (expected, block[156:157], 'unsupported tar header')+ size = int(block[124:136].strip(b'\\x00 ') or b'0', 8)+ offset += 512 + ((size + 511) // 512) * 512+with tarfile.open(fileobj=io.BytesIO(contents), mode='r:xz') as archive:+ assert archive.extractfile('./opt/workdaddy/scripts/daemon.js').read() == b"const DAEMON_VERSION = '1.2.14';\\n"+ assert any(len(member.name) > 100 for member in archive.getmembers())+ assert archive.getmember('./opt/workdaddy/scripts/runtime/node/node').mode == 0o755+`;+ const result = spawnSync(python, ['-', stage, path.join(temp, 'fixture.deb'), '1.2.14', '/opt/workdaddy', 'workdaddy', 'amd64'], {+ input: packager + '\n' + checkHeaders, encoding: 'utf8',+ });+ assert.equal(result.status, 0, result.stderr || result.error?.message);+ } finally {+ fs.rmSync(temp, { recursive: true, force: true });+ }+});+test('Linux release builds a versioned, self-contained Debian package without root install hooks', () => {const source = fs.readFileSync(script, 'utf8');assert.match(source, /dpkg-deb --build --root-owner-group/);assert.match(source, /CROSS_PACKAGE=1/);- assert.match(source, /tarfile\.open\(control, 'w:xz'\)/);- assert.match(source, /tarfile\.open\(data, 'w:xz'\)/);+ assert.match(source, /tarfile\.open\(control, 'w:xz', format=tarfile\.USTAR_FORMAT\)/);+ assert.match(source, /tarfile\.open\(data, 'w:xz', format=tarfile\.USTAR_FORMAT\)/);assert.match(source, /expected_machine = \{'amd64': 62, 'arm64': 183\}/);assert.match(source, /actual_machine = int\.from_bytes\(node\[18:20\], 'little'\)/);assert.match(source, /WORKDADDY_BUILD_ARCH/);diff --git a/test/persona-api.test.js b/test/persona-api.test.jsindex 4e50188..e91e0fc 100644--- a/test/persona-api.test.js+++ b/test/persona-api.test.js@@ -69,3 +69,38 @@ test('unknown accounts and non-WorkBuddy profiles cannot copy', async t => {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);});+for (const profile of ['workbuddy-cn','workbuddy-ai']) test('shared settings persist dismissal, validate consent source and lock, and remain profile scoped: '+profile, async t => {+ const h=harness(t,profile);+ const before=await h.run({method:'GET',url:'/api/persona/settings'});+ assert.equal(before.body.mode,'unset');+ assert.deepEqual(Array.from(before.body.sources,s=>s.uid),['a','b','legacy']);+ assert.equal(before.body.sources.find(s=>s.uid==='a').available,false);+ assert.equal(JSON.stringify(before).includes('fixture MEMORY'),false);+ assert.equal((await h.run({method:'POST',url:'/api/persona/settings',body:{dismissNotice:true}})).body.noticeDismissed,true);+ assert.equal((await h.run({method:'GET',url:'/api/persona/settings'})).body.mode,'unset');+ assert.equal((await h.run({method:'POST',url:'/api/persona/settings',body:{mode:'shared',currentUid:'a'}})).status,400);+ const source=before.body.sources.find(s=>s.available);+ const saved=await h.run({method:'POST',url:'/api/persona/settings',body:{mode:'shared',currentUid:'b',sourceUid:source.uid,revision:source.revision}});+ assert.equal(saved.status,200); assert.equal(saved.body.mode,'shared'); assert.equal(saved.body.reloaded,true);+ assert.equal(h.locked(),false);+ assert.equal((await h.run({method:'POST',url:'/api/persona-copy',body:{uid:'a',confirmed:true}})).status,400);+ assert.equal((await h.run({method:'POST',url:'/api/persona/settings',body:{mode:'independent',currentUid:'b'}})).body.mode,'independent');+ h.context.PROFILE.kind='codebuddy';+ assert.equal((await h.run({method:'GET',url:'/api/persona/settings'})).body.supported,false);+ assert.equal((await h.run({method:'POST',url:'/api/persona/settings',body:{dismissNotice:true}})).status,400);+});+test('shared switching protects authentication until projection succeeds and undoes projection if authentication fails',async t=>{+ const h=harness(t);+ const options={dataRoot:h.dataRoot,backupRoot:h.context.DATA_DIR,accounts:[{uid:'a'},{uid:'b'}],currentUid:'b'};+ persona.configurePersona({...options,mode:'shared',sourceUid:'legacy',revision:persona.listPersonaSources(options).find(s=>s.uid==='legacy').revision});+ const context=vm.createContext({...h.context,codeBuddyNative:null,switchTo:async()=>{throw new Error('auth failed');}});+ const seam=daemon.slice(daemon.indexOf('async function switchAccountForProfile(uid)'),daemon.indexOf('\nfunction scheduleBackup('));+ vm.runInContext(seam,context);+ await assert.rejects(context.switchAccountForProfile('a'),/auth failed/);+ assert.equal(fs.existsSync(path.join(h.dataRoot,'user-a-personal')),false);+ assert.equal(persona.readPersonaSettings(options.backupRoot).activeUid,'b');+ let switched=false; context.switchTo=()=>{switched=true;};+ fs.unlinkSync(path.join(h.dataRoot,'user-b-personal/USER.md'));+ await assert.rejects(context.switchAccountForProfile('a'),/尚未完成/);+ assert.equal(switched,false);+});diff --git a/test/persona-sharing.test.js b/test/persona-sharing.test.jsnew file mode 100644index 0000000..b65656d--- /dev/null+++ b/test/persona-sharing.test.js@@ -0,0 +1,110 @@+'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 p = require('../scripts/persona');+function fixture(t) {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sharing-')));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const options = { dataRoot: path.join(root, 'client'), backupRoot: path.join(root, 'plugin'), currentUid: 'a', accounts: [{uid:'a'}, {uid:'b'}] };+ const file = (uid, name) => path.join(p.personaDir(options.dataRoot, uid), name);+ const write = (uid, name, text) => { fs.mkdirSync(path.dirname(file(uid,name)), {recursive:true}); fs.writeFileSync(file(uid,name),text); };+ for (const uid of ['a','b']) for (const name of ['IDENTITY.md','USER.md','SOUL.md']) write(uid,name,uid + name);+ write('b','workspace-state.json',JSON.stringify({custom:42}));+ const enable = () => p.configurePersona({...options,mode:'shared',sourceUid:'a',revision:p.listPersonaSources(options)[0].revision});+ return {options,file,write,enable};+}+test('dismissal persists without selecting a mode and can later enable sharing', t => {+ const f=fixture(t);+ p.dismissPersonaNotice(f.options.backupRoot);+ assert.deepEqual(p.readPersonaSettings(f.options.backupRoot),{mode:'unset',noticeDismissed:true,activeUid:null});+ f.enable();+ assert.equal(p.readPersonaSettings(f.options.backupRoot).mode,'shared');+});+test('shared A edits reach B; B edits and optional memory deletion reach A, preserving state', t => {+ const f=fixture(t); f.enable();+ f.write('a','MEMORY.md','new A memory');+ p.syncSharedPersonaForSwitch({...f.options,sourceUid:'a',targetUid:'b'});+ assert.equal(fs.readFileSync(f.file('b','MEMORY.md'),'utf8'),'new A memory');+ assert.equal(JSON.parse(fs.readFileSync(f.file('b','workspace-state.json'))).custom,42);+ f.write('b','USER.md','edited B'); fs.unlinkSync(f.file('b','MEMORY.md'));+ p.syncSharedPersonaForSwitch({...f.options,sourceUid:'b',targetUid:'a'});+ assert.equal(fs.readFileSync(f.file('a','USER.md'),'utf8'),'edited B');+ assert.equal(fs.existsSync(f.file('a','MEMORY.md')),false);+ assert.equal(fs.readFileSync(path.join(p.sharedPersonaDir(f.options.backupRoot),'USER.md'),'utf8'),'edited B');+});+test('independent mode leaves other account untouched; re-enabling asks for a fresh source', t => {+ const f=fixture(t); f.enable(); p.configurePersona({...f.options,mode:'independent'});+ f.write('a','USER.md','private');+ assert.equal(p.syncSharedPersonaForSwitch({...f.options,sourceUid:'a',targetUid:'b'}).skipped,true);+ assert.equal(fs.readFileSync(f.file('b','USER.md'),'utf8'),'bUSER.md');+ assert.throws(()=>p.configurePersona({...f.options,mode:'shared'}),/来源/);+});+test('stale selection, unknown account, external login and symlinks fail before replacement', t => {+ const f=fixture(t); const revision=p.listPersonaSources(f.options)[0].revision;+ f.write('a','USER.md','changed');+ assert.throws(()=>p.configurePersona({...f.options,mode:'shared',sourceUid:'a',revision}),/变化/);+ assert.throws(()=>p.configurePersona({...f.options,mode:'shared',sourceUid:'unknown'}),/来源/);+ f.enable();+ assert.throws(()=>p.syncSharedPersonaForSwitch({...f.options,sourceUid:'b',targetUid:'a'}),/账号已变化/);+ const before=fs.readFileSync(f.file('b','USER.md'),'utf8');+ fs.symlinkSync(f.file('a','USER.md'),f.file('b','MEMORY.md'));+ assert.throws(()=>p.syncSharedPersonaForSwitch({...f.options,sourceUid:'a',targetUid:'b'}),/符号链接/);+ assert.equal(fs.readFileSync(f.file('b','USER.md'),'utf8'),before);+});+test('failed transaction restores canonical, target and settings; switch failure can undo prepared sharing', t => {+ const f=fixture(t); f.enable(); f.write('a','USER.md','new');+ const before=fs.readFileSync(f.file('b','USER.md'),'utf8'); let writes=0;+ const replace = require('../scripts/atomic-file-write').replaceFileWithRetry;+ assert.throws(()=>p.syncSharedPersonaForSwitch({...f.options,sourceUid:'a',targetUid:'b',replaceFile:(...args)=>{+ if(++writes===2) throw new Error('disk failed');+ return replace(...args);+ }}),/disk failed/);+ assert.equal(fs.readFileSync(f.file('b','USER.md'),'utf8'),before);+ assert.equal(fs.readFileSync(path.join(p.sharedPersonaDir(f.options.backupRoot),'USER.md'),'utf8'),'aUSER.md');+ assert.equal(p.readPersonaSettings(f.options.backupRoot).activeUid,'a');+ const prepared=p.syncSharedPersonaForSwitch({...f.options,sourceUid:'a',targetUid:'b'}); prepared.rollback();+ assert.equal(fs.readFileSync(f.file('b','USER.md'),'utf8'),before);+ assert.equal(p.readPersonaSettings(f.options.backupRoot).activeUid,'a');+});+test('edits arriving during backup abort sharing before canonical or destination changes', t => {+ const f=fixture(t); f.enable(); f.write('a','USER.md','before backup');+ const write=fs.writeFileSync;+ let changed=false;+ t.mock.method(fs,'writeFileSync',function(file,...args) {+ const result=write.call(fs,file,...args);+ if (!changed && String(file).includes(path.join('persona','backups'))) {+ changed=true;+ write.call(fs,f.file('a','USER.md'),'edited during backup');+ }+ return result;+ });+ assert.throws(()=>p.syncSharedPersonaForSwitch({...f.options,sourceUid:'a',targetUid:'b'}),/来源个性化设置已变化/);+ assert.equal(changed,true);+ assert.equal(fs.readFileSync(f.file('a','USER.md'),'utf8'),'edited during backup');+ assert.equal(fs.readFileSync(f.file('b','USER.md'),'utf8'),'bUSER.md');+ assert.equal(fs.readFileSync(path.join(p.sharedPersonaDir(f.options.backupRoot),'USER.md'),'utf8'),'aUSER.md');+ assert.equal(p.readPersonaSettings(f.options.backupRoot).activeUid,'a');+});+test('invalid settings never replace a previously saved preference', t => {+ const f=fixture(t); p.dismissPersonaNotice(f.options.backupRoot);+ assert.throws(()=>p.writePersonaSettings(f.options.backupRoot,{mode:'shared',noticeDismissed:true,activeUid:'../a'}),/设置无效/);+ assert.deepEqual(p.readPersonaSettings(f.options.backupRoot),{mode:'unset',noticeDismissed:true,activeUid:null});+});+test('source picker lists every account, explains unavailable accounts, and names the pre-upgrade settings', t => {+ const f=fixture(t);+ fs.rmSync(path.dirname(f.file('b','USER.md')),{recursive:true});+ for(const name of ['IDENTITY.md','USER.md','SOUL.md']) fs.writeFileSync(path.join(f.options.dataRoot,name),'before upgrade '+name);+ const sources=p.listPersonaSources(f.options);+ assert.deepEqual(sources.map(s=>s.uid),['a','b','legacy']);+ assert.equal(sources[0].available,true);+ assert.equal(sources[1].available,false);+ assert.equal(sources[1].unavailableReason,'未设置');+ assert.equal(sources[1].revision,undefined);+ assert.equal(sources[2].nickname,'升级前共用的设置');+ assert.equal(sources[2].available,true);+ assert.throws(()=>p.configurePersona({...f.options,mode:'shared',sourceUid:'b',revision:sources[0].revision}),/来源/);+ assert.equal(JSON.stringify(sources).includes('before upgrade'),false);+});diff --git a/test/persona-switch-preflight.test.js b/test/persona-switch-preflight.test.jsindex 967eb2d..823e238 100644--- a/test/persona-switch-preflight.test.js+++ b/test/persona-switch-preflight.test.js@@ -7,41 +7,19 @@ 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);+test('sharing is configured inside account settings without a per-switch prompt', () => {+ assert.doesNotMatch(inject, /openPersonaDialog|personaSwitchPreflight|wbs-persona-modal/);+ assert.match(inject, /data-persona-settings/);+ assert.match(inject, /data-act="persona-dismiss"/);+ assert.match(inject, /refreshPersonaNotice\(\);/);});--function harness(preflight) {+test('switch goes straight to the authenticated API; persona sync belongs to the daemon', async () => {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 }) }; },+ const ctx = vm.createContext({ CAPS: {}, API: 'http://127.0.0.1', WBS_API_TOKEN: 'fixture-token',+ 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);+ vm.runInContext(apiSource,ctx);+ await ctx.api('/api/switch',{method:'POST',body:'{"uid":"b"}'});+ assert.equal(requests.length,1);+ assert.equal(requests[0].request.headers['X-WorkDaddy-Token'],'fixture-token');});diff --git a/test/sentry.test.js b/test/sentry.test.jsindex d1e11bc..751959f 100644--- a/test/sentry.test.js+++ b/test/sentry.test.js@@ -208,12 +208,7 @@ test('privacy documentation distinguishes local data from required remote servicassert.match(readme, /对应 API Key/);});-test('source repair instructions require a verified Sentry send', () => {- const instructions = fs.readFileSync(path.join(repoRoot, '安装失败自主解决提示词.txt'), 'utf8');- assert.match(instructions, /启动后必须先完整读取本文件/);- assert.match(instructions, /--force-send --require-sent/);- assert.match(instructions, /只有看到 `sent=true` 才算上报成功/);- assert.doesNotMatch(instructions, /可选诊断上报/);+test('repair reporter requires a verified Sentry send when requested', () => {assert.match(reporterSource, /if \(key === 'force-send'\)/);assert.match(reporterSource, /if \(args\.requireSent && result\.sent !== true\) process\.exitCode = 1/);assert.match(reporterSource, /process\.exitCode = 1/);diff --git a/test/session-cwd-repair.test.js b/test/session-cwd-repair.test.jsnew file mode 100644index 0000000..e148dc7--- /dev/null+++ b/test/session-cwd-repair.test.js@@ -0,0 +1,138 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');+const vm = require('node:vm');++const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+const start = source.indexOf('function createDirectoryNoFollow(directory)');+const end = source.indexOf('function sessionRangeMs(', start);+assert.ok(start >= 0 && end > start, 'session cwd repair helpers must be present');++// Execute the real repair helpers with Windows paths and an in-memory filesystem+// so missing drives and remounts can be exercised on every test host.+function harness({ isWin = true, kind = 'workbuddy' } = {}) {+ const state = {+ rows: [+ { id: 'fixture-a', cwd: 'G:\\fixture\\project-a' },+ { id: 'fixture-b', cwd: 'G:\\fixture\\project-b' },+ ],+ roots: new Set(), directories: new Set(), symlinks: new Set(),+ missingPayloads: new Set(), mkdir: [], logs: [], denied: false, queries: 0,+ };+ const missing = () => Object.assign(new Error('fixture path missing'), { code: 'ENOENT' });+ const context = vm.createContext({+ path: path.win32,+ fs: {+ existsSync(target) {+ return state.roots.has(target) || state.directories.has(target) || state.symlinks.has(target);+ },+ lstatSync(target) {+ if (state.symlinks.has(target)) return { isSymbolicLink: () => true, isDirectory: () => true };+ if (state.directories.has(target)) return { isSymbolicLink: () => false, isDirectory: () => true };+ throw missing();+ },+ mkdirSync(target) {+ state.mkdir.push(target);+ if (!state.roots.has(path.win32.parse(target).root)) throw missing();+ if (state.denied) throw Object.assign(new Error('fixture access denied'), { code: 'EACCES' });+ state.directories.add(target);+ },+ statSync: target => ({ isDirectory: () => state.directories.has(target) }),+ },+ IS_WIN: isWin, PROFILE: { kind }, SESSIONS_DB: 'C:\\fixture\\sessions.db',+ sqliteQuery: async () => { state.queries++; return state.rows; },+ sessionPayloadExists: (_, id) => !state.missingPayloads.has(id),+ log: message => state.logs.push(message),+ });+ vm.runInContext(source.slice(start, end), context);+ return { state, tick: () => context.repairMissingSessionWorkspaces() };+}++test('missing volumes never trigger mkdir and log only once per root across repair ticks', async () => {+ const h = harness();+ h.state.rows.push({ id: 'fixture-c', cwd: 'H:\\fixture\\project-c' });+ for (let tick = 0; tick < 3; tick++) {+ const result = await h.tick();+ assert.equal(result.repaired.length, 0);+ assert.equal(result.skipped, 3);+ }+ assert.deepEqual(h.state.mkdir, []);+ assert.equal(h.state.logs.length, 2);+ for (const root of ['G:\\', 'H:\\']) {+ assert.equal(h.state.logs.filter(message => message.endsWith(root)).length, 1);+ }+ assert.ok(h.state.logs.every(message => !message.includes('fixture') && !message.includes('project')));+});++test('repair resumes when a missing drive returns without restarting the daemon', async () => {+ const h = harness();+ await h.tick();+ h.state.roots.add('G:\\');+ const result = await h.tick();+ assert.deepEqual(Array.from(result.repaired), h.state.rows.map(row => row.cwd));+ assert.equal(result.skipped, 0);+ assert.ok(h.state.rows.every(row => h.state.directories.has(row.cwd)));+ h.state.directories.clear();+ h.state.roots.clear();+ await h.tick();+ assert.equal(h.state.logs.filter(message => message.includes('所在卷不存在')).length, 1);+});++test('missing UNC shares are skipped and can recover on a later repair tick', async () => {+ const h = harness();+ const cwd = '\\\\fixture-host\\fixture-share\\workspace\\project';+ h.state.rows = [{ id: 'fixture-unc', cwd }];+ await h.tick();+ await h.tick();+ assert.deepEqual(h.state.mkdir, []);+ assert.equal(h.state.logs.length, 1);+ assert.ok(!h.state.logs[0].includes('workspace'));+ h.state.roots.add(path.win32.parse(cwd).root);+ assert.deepEqual(Array.from((await h.tick()).repaired), [cwd]);+});++test('mounted-drive permission failures retain the existing retry behavior', async () => {+ const h = harness();+ h.state.roots.add('G:\\');+ h.state.denied = true;+ for (let tick = 0; tick < 2; tick++) assert.equal((await h.tick()).skipped, 2);+ assert.equal(h.state.mkdir.length, 4);+ assert.equal(h.state.logs.length, 4);+ assert.ok(h.state.logs.every(message => message.includes('fixture access denied')));+ assert.ok(h.state.logs.every(message => !message.includes('所在卷不存在')));+});++test('existing directories and sessions without stored payloads are never recreated', async () => {+ const h = harness();+ h.state.roots.add('G:\\');+ h.state.directories.add(h.state.rows[0].cwd);+ h.state.missingPayloads.add(h.state.rows[1].id);+ assert.equal((await h.tick()).skipped, 2);+ assert.deepEqual(h.state.mkdir, []);+ assert.deepEqual(h.state.logs, []);+});++test('cwd repair still rejects symbolic-link ancestors on a mounted drive', async () => {+ const h = harness();+ h.state.roots.add('G:\\');+ h.state.symlinks.add('G:\\fixture');+ assert.equal((await h.tick()).skipped, 2);+ assert.deepEqual(h.state.mkdir, []);+ assert.equal(h.state.logs.length, 2);+ assert.ok(h.state.logs.every(message => message.includes('符号链接')));+});++test('non-Windows and CodeBuddy profiles never query or repair session cwd', async () => {+ for (const options of [{ isWin: false }, { kind: 'codebuddy' }]) {+ const h = harness(options);+ const result = await h.tick();+ assert.equal(result.skipped, 0);+ assert.equal(result.repaired.length, 0);+ assert.equal(h.state.queries, 0);+ assert.deepEqual(h.state.mkdir, []);+ assert.deepEqual(h.state.logs, []);+ }+});diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 2cc1c09..d017bd9 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -932,13 +932,6 @@ test('macOS package launcher returns focus to the target WorkBuddy and separatesassert.match(build, /manual inject result:[\s\S]*activate_target_app/);});-test('troubleshooting prompts keep Sentry reports short and omit raw logs', () => {- const prompt = fs.readFileSync(path.join(repoRoot, '安装失败自主解决提示词.txt'), 'utf8');- assert.ok(prompt.length < 3500, 'source prompt should stay compact');- assert.match(prompt, /报告硬上限 3500 字符/);- assert.match(prompt, /不要粘贴完整日志/);-});-test('daemon lock falls back when the data-directory lock is not writable on Windows', () => {const daemon = read('daemon.js');assert.match(daemon, /DAEMON_LOCK_FALLBACK_FILE/);diff --git "a/\345\256\211\350\243\205\345\244\261\350\264\245\350\207\252\344\270\273\350\247\243\345\206\263\346\217\220\347\244\272\350\257\215.txt" "b/\345\256\211\350\243\205\345\244\261\350\264\245\350\207\252\344\270\273\350\247\243\345\206\263\346\217\220\347\244\272\350\257\215.txt"deleted file mode 100644index bbe78a1..0000000--- "a/\345\256\211\350\243\205\345\244\261\350\264\245\350\207\252\344\270\273\350\247\243\345\206\263\346\217\220\347\244\272\350\257\215.txt"+++ /dev/null@@ -1,38 +0,0 @@-WorkDaddy Windows 安装失败自助修复-==================================--你是 WorkDaddy 的故障修复 agent。用户已经无法正常安装或启动 WorkDaddy。启动后必须先完整读取本文件,再在用户授权的源码目录内完成排查、修复和验证。修复通过后,诊断报告是本次修复流程的必需步骤;不得跳过、伪造或把排队当成成功。--一、准备与排查--1. 在临时目录执行:- git clone https://github.com/babygoton/WorkDaddy.git- cd WorkDaddy-2. 阅读 README.md、scripts/install-win.ps1、scripts/launcher.cmd、scripts/win-launcher.js、scripts/daemon.js,结合用户提供的错误复现问题。-3. 只在源码目录操作;不要读取、复制、上传或修改 %APPDATA%\\WorkDaddy\\accounts\\、登录文件、Cookie、数据库、环境变量、私钥或完整日志。-4. 记录一条关键错误、系统/Node/WorkBuddy 版本和可复现命令;不要粘贴完整日志。-5. 可复现时运行 `powershell -NoProfile -ExecutionPolicy Bypass -File .\\scripts\\install-win.ps1`,再运行 `.\\scripts\\launcher.cmd`。--二、修复与验证--1. 只修改源码,保持用户数据和脱敏逻辑不变。-2. 先确认根因,再做最小修复;无法确认时明确写“未确认”,不要猜测。-3. 运行:- node --check scripts/sentry-report.js- node --check scripts/daemon.js- node --check scripts/win-launcher.js- node --test test/*.test.js--三、生成短报告--在源码根目录写 WORKDADDY_FIX_REPORT.md。报告硬上限 3500 字符,最多包含:问题/根因、修改文件及目的、测试汇总、用户下一步。每项用短句;只引用一条脱敏错误,不附完整日志、命令输出、账号数据或凭据。--四、诊断上报(修复通过后必须完成)--「发送错误诊断」开关同时控制远程 Sentry 和本地脱敏诊断。用户启动本修复 agent 即表示允许发送本次脱敏修复报告;不要修改用户的持久化设置,也不要读取账号、Cookie、Token、数据库或完整日志。修复通过测试后必须执行以下命令:-- node scripts\\sentry-report.js --stage agent-fix --level info --message-file WORKDADDY_FIX_REPORT.md --tags-json '{"source":"workbuddy-agent","status":"fixed","platform":"windows"}' --force-send --require-sent--命令输出必须是 JSON,命令会自动重试。只有看到 `sent=true` 才算上报成功;看到 `queued=true` 或命令退出码非 0 时,必须继续检查网络、DNS、代理和系统时间后重试,不能向用户报告“已上报”。即使关于页开关关闭,`--force-send --require-sent` 也只用于本次用户主动发起的修复报告,并且仍受同样的脱敏规则约束。不要把 token、账号备份、数据库、输入框内容或完整日志放进 WORKDADDY_FIX_REPORT.md。--如果测试仍未通过,不得伪造 fixed 状态;可以改用 status=unresolved,但仍必须使用同样的 `--force-send --require-sent`,并在报告中写清楚阻塞原因。