WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
release: merge 1.2.18 changes
[email protected]2fd29e480298
diff --git a/scripts/automation-model.js b/scripts/automation-model.jsindex 01d71ba..5a0e852 100644--- a/scripts/automation-model.js+++ b/scripts/automation-model.js@@ -64,10 +64,14 @@ async function selectAutomationModel({ model, conversationId, accountUid }) {await openMenu();const available = options();previousModel = available.find((item) => item.props.isSelected)?.option.id || null;- const target = available.find((item) => item.option.id === model);+ // Prefer the exact ID: official and custom models may share a name. Older+ // callers may omit the custom-local prefix; resolve that only as a fallback.+ const target = available.find((item) => item.option.id === model) ||+ (!model.startsWith('custom-local:') && available.find((item) => item.option.id === 'custom-local:' + model));if (!target) throw new Error('未知模型 ID;请从 WorkBuddy 模型列表选择有效 ID');if (target.option.disabled) throw new Error('指定模型当前不可用');if (!previousModel) throw new Error('无法确认当前模型');+ model = target.option.id;changed = previousModel !== model;if (changed) target.props.onSelect();for (let attempt = 0; attempt < 50; attempt++) {diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 9e7c43f..8b64bcd 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -91,6 +91,7 @@ const {wdCompatText, // [wd-compat]wdCompatContainsEncryptedFields, // [wd-compat]wdCompatDecryptAuthJson, // [wd-compat] WorkBuddy 5.6+ 字段信封解密+ wdCompatEncryptAuthJson, // [wd-compat] 刷新凭据按原信封加密落盘wdCompatAuthToken, // [wd-compat] 仅返回可直接发送的明文 tokennormalizeAccountImportJson, // [wd-compat] 明文/信封账号导入归一化backupPath,@@ -526,8 +527,11 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.2.62:手动复制会话到当前账号后刷新官方列表,无需再次切号。// 1.2.63:跟随系统将浅色恢复视为成功,持续轮询并更新外观基线。// 1.2.64:CodeBuddy 原生主题支持跟随系统,重连恢复并与手动选择互斥。-const DAEMON_VERSION = '1.2.64';-const DAEMON_BUILD_ID = 'release-1.2.64-codebuddy-system-theme';+// 1.2.65:兼容空会话同步、自定义模型和重定向备份目录,工作目录恢复退避重试。+// 1.2.66:刷新凭据按原信封加密保存,同账号刷新去重,过期账号保留手动切换。+// 1.2.67:Windows 重启 GUI 客户端时不再请求隐藏主窗口,与冷启动保持一致。+const DAEMON_VERSION = '1.2.68';+const DAEMON_BUILD_ID = 'release-1.2.68-login-page-persona-switch';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -3401,7 +3405,10 @@ function relaunchWorkBuddy() {const child = spawn(command, args, {detached: true,stdio: 'ignore',- windowsHide: true,+ // WorkBuddy 是 GUI 程序:windowsHide:true 会把 STARTUPINFO.wShowWindow 置为 SW_HIDE,+ // Electron 主窗口走 ShowWindow(SW_SHOWDEFAULT) 会继承该值,导致重启后主窗口隐藏启动、+ // 只剩托盘图标。与 win-launcher.js 的冷启动路径保持一致(那里的注释早已说明此坑)。+ windowsHide: false,env: childEnv,});await new Promise((resolve, reject) => {@@ -3828,7 +3835,7 @@ const accountSyncFailures = new Map();function isIgnorableAutomationSyncFailure(job) {if (!job || job.status === 'done' || !Array.isArray(job.details) || !job.details.length) return false;const failed = job.details.filter(item => item && item.status === 'failed');- return failed.length > 0 && failed.every(item => item.error === '会话消息文件没有消息,未同步');+ return failed.length > 0 && failed.every(item => ['会话消息文件没有消息,未同步', '会话消息文件为空,未同步'].includes(item.error));}async function assertSessionSyncIdle(sessionIds = []) {if (PROFILE.kind === 'codebuddy') {@@ -4065,7 +4072,7 @@ function startAutomationRun(task, event = null) {}const accountUid = (currentAccount() || {}).uid;if (!accountUid) throw new Error('没有可用账号');- const modelId = detail.model === undefined ? null : normalizeAutomationModelId(detail.model);+ let modelId = detail.model === undefined ? null : normalizeAutomationModelId(detail.model);if (op === 'session.create') await withInput(() => ensureAutomationNewTask({ guard: () => {if (isCancelled() || (currentAccount() || {}).uid !== accountUid) throw new Error('发送前账号或运行状态已变化');}, cwd: detail.cwd, workspace: detail.workspace }));@@ -4094,6 +4101,7 @@ function startAutomationRun(task, event = null) {if (modelId) {modelSelection = await withInput(() => selectAutomationModelById(modelId,op === 'session.send' ? { conversationId: detail.conversationId } : { accountUid }));+ modelId = modelSelection.model;appendRunLog('session:model:confirmed');// Selecting a model on New Task may mount its provisional conversation// before any text is entered. Treat that renderer-owned transition as@@ -4265,8 +4273,9 @@ function saveCheckinCache(cache) {}}-// 加密备份的刷新结果只缓存公开时间字段,绝不把解密后的 token 写回磁盘。+// 刷新结果必须加密落盘;写入失败时暂存内存,下次先重试保存,避免再次轮换丢失凭据。const backupAuthRuntimeCache = new Map();+const accountTokenRefreshes = new Map();let accountTokenRefreshInFlight = null;const TOKEN_REFRESH_STATE_FILE = path.join(DATA_DIR, 'token-refresh-state.json');let tokenRefreshState = null;@@ -4308,7 +4317,8 @@ function saveTokenRefreshState() {function persistedTokenRefreshState(uid, signature) {const record = loadTokenRefreshState().accounts[String(uid || '')];- if (!record || record.signature !== signature) return null;+ // 旧版只有公开时间、没有对应的新凭据,不能据此跳过刷新或显示更晚的有效期。+ if (!record || record.signature !== signature || record.credentialsPersisted !== true) return null;return record;}@@ -4318,6 +4328,7 @@ function rememberTokenRefreshSuccess(uid, file, auth) {const lastRefreshTime = normalizeTokenTimestamp(auth && auth.lastRefreshTime) || Date.now();loadTokenRefreshState().accounts[String(uid)] = {signature,+ credentialsPersisted: true,lastRefreshTime,expiresAt: normalizeTokenTimestamp(auth && auth.expiresAt),refreshExpiresAt: normalizeTokenTimestamp(auth && auth.refreshExpiresAt),@@ -4326,8 +4337,7 @@ function rememberTokenRefreshSuccess(uid, file, auth) {}/**- * 将加密备份 token 刷新后仅存在内存中的公开时间字段合并到账号列表。- * 加密备份不能把解密后的 token 写回磁盘,但账号页仍应显示新有效期。+ * 有效期必须来自实际持有的凭据,不能使用旧版仅保存的公开时间。*/function listAccountsWithRuntimeTokenCache() {return listAccounts(DATA_DIR).map((account) => {@@ -4353,21 +4363,59 @@ function listAccountsWithRuntimeTokenCache() {/** 刷新备份账号凭证:临期惰性刷新,或当天尚未成功刷新时执行保活。 */async function refreshAccountBackupToken(uid, options = {}) {- const file = path.join(DATA_DIR, 'accounts', uid + '.info');+ if (accountTokenRefreshes.has(uid)) return accountTokenRefreshes.get(uid);+ const task = performAccountTokenRefresh(uid, options).finally(() => {+ if (accountTokenRefreshes.get(uid) === task) accountTokenRefreshes.delete(uid);+ });+ accountTokenRefreshes.set(uid, task);+ return task;+}++function persistRefreshedAccount(uid, file, root, stored, sourceSignature, sourceText) {+ const tmp = `${file}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;+ try {+ if (accountBackupSignature(file) !== sourceSignature || fs.readFileSync(file, 'utf8') !== sourceText) {+ backupAuthRuntimeCache.delete(uid);+ return { root: null, refreshed: false, persisted: false, error: 'account-changed-during-refresh' };+ }+ const output = wdCompatContainsEncryptedFields(stored) ? wdCompatEncryptAuthJson(root, stored) : root;+ fs.writeFileSync(tmp, JSON.stringify(output, null, 2), { mode: 0o600, flag: 'wx' });+ fs.renameSync(tmp, file);+ } catch (_) {+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch (_) {}+ // 不记录原始加密/文件异常,避免错误文本带出凭据或账号备份内容。+ log(`[token-refresh] 账号 ${uid} 刷新结果落盘失败,将重试保存`);+ return { root, refreshed: true, persisted: false, error: 'write-account-failed' };+ }+ backupAuthRuntimeCache.delete(uid);+ rememberTokenRefreshSuccess(uid, file, root.auth);+ return { root, refreshed: true, persisted: true };+}++async function performAccountTokenRefresh(uid, options) {+ let file;let root;+ let stored;+ let sourceText;let encryptedAtRest = false;let sourceSignature = '';try {+ file = accountBackupFile(uid);const stat = fs.statSync(file);sourceSignature = `${stat.mtimeMs}:${stat.size}`;- const stored = JSON.parse(fs.readFileSync(file, 'utf8'));+ sourceText = fs.readFileSync(file, 'utf8');+ stored = JSON.parse(sourceText);encryptedAtRest = wdCompatContainsEncryptedFields(stored);const cached = backupAuthRuntimeCache.get(uid);root = cached && cached.signature === sourceSignature? cached.root- : wdCompatDecryptAuthJson(stored); // [wd-compat]- } catch (e) {- return { root: null, error: 'read-account-failed: ' + e.message };+ : wdCompatDecryptAuthJson(JSON.parse(sourceText)); // 保留原信封作为写入模板。+ if (cached && cached.signature !== sourceSignature) backupAuthRuntimeCache.delete(uid);+ if (cached && cached.signature === sourceSignature && cached.pendingPersistence) {+ return persistRefreshedAccount(uid, file, root, stored, sourceSignature, sourceText);+ }+ } catch (_) {+ return { root: null, error: 'read-account-failed' };}const auth = root && root.auth && typeof root.auth === 'object' ? root.auth : null;if (!auth) return { root, skipped: true, reason: 'no-auth' };@@ -4382,31 +4430,24 @@ async function refreshAccountBackupToken(uid, options = {}) {if (options.dailyKeepalive === true && !dailyDue) return { root, skipped: true };if (options.force !== true && !dailyDue && !shouldRefreshAccessToken(auth, now)) return { root, skipped: true };+ if (encryptedAtRest) {+ try {+ // 在可能轮换 refresh token 的请求之前确认可以重新加密,不能刷新成功后才发现无法保存。+ wdCompatEncryptAuthJson(root, stored);+ if (typeof (auth.accessToken ?? auth.access_token) !== 'string' ||+ typeof (auth.refreshToken ?? auth.refresh_token) !== 'string') throw new Error('encrypted-credentials-unavailable');+ } catch (_) {+ return { root, refreshed: false, error: 'encrypt-account-unavailable' };+ }+ }const result = await refreshAuthToken(auth, { apiHost: PROFILE.apiHost, fetchImpl: globalThis.fetch, now });if (!result.ok) {log(`[token-refresh] 账号 ${uid} 刷新失败: ${redactDiagnosticText(result.error, 300)}`);return { root, refreshed: false, error: result.error };}const nextRoot = Object.assign({}, root, { auth: result.auth });- if (encryptedAtRest) {- backupAuthRuntimeCache.set(uid, { signature: sourceSignature, root: nextRoot });- rememberTokenRefreshSuccess(uid, file, result.auth);- log(`[token-refresh] 账号 ${uid} 已刷新(加密备份仅保存在内存)`);- return { root: nextRoot, refreshed: true, persisted: false };- }- const tmp = file + '.tmp';- try {- fs.writeFileSync(tmp, JSON.stringify(nextRoot, null, 2), { mode: 0o600 });- fs.renameSync(tmp, file);- fs.chmodSync(file, 0o600);- } catch (e) {- try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch (_) {}- log(`[token-refresh] 账号 ${uid} 刷新结果落盘失败: ${e.message}`);- return { root, refreshed: false, error: 'write-account-failed: ' + e.message };- }- backupAuthRuntimeCache.delete(uid);- rememberTokenRefreshSuccess(uid, file, result.auth);- return { root: nextRoot, refreshed: true, persisted: true };+ backupAuthRuntimeCache.set(uid, { signature: sourceSignature, root: nextRoot, pendingPersistence: true });+ return persistRefreshedAccount(uid, file, nextRoot, stored, sourceSignature, sourceText);}/**@@ -4881,6 +4922,7 @@ function createDirectoryNoFollow(directory) {let sessionCwdRepairInFlight = null;// 只去重提示;每轮仍检查卷状态,盘符或共享恢复后无需重启 daemon。const reportedMissingCwdRoots = new Set();+const sessionCwdRepairFailures = new Map();function repairMissingSessionWorkspaces() {if (sessionCwdRepairInFlight) return sessionCwdRepairInFlight;sessionCwdRepairInFlight = (async () => {@@ -4889,24 +4931,51 @@ function repairMissingSessionWorkspaces() {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();+ const activeCwds = 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; }+ if (!cwd) { skipped++; continue; }+ const key = path.resolve(cwd).toLowerCase();+ if (fs.existsSync(cwd)) {+ sessionCwdRepairFailures.delete(key);+ skipped++;+ continue;+ }+ if (!sessionPayloadExists(wbHome, row.id)) { skipped++; continue; }+ activeCwds.add(key);const root = path.parse(cwd).root;if (root && !fs.existsSync(root)) {skipped++;missingCwdRoots.add(root);continue;}+ const previous = sessionCwdRepairFailures.get(key);+ if (previous && Date.now() < previous.nextRetryAt) { skipped++; continue; }try {createDirectoryNoFollow(cwd);- if (fs.statSync(cwd).isDirectory()) repaired.push(cwd);+ if (fs.statSync(cwd).isDirectory()) {+ repaired.push(cwd);+ sessionCwdRepairFailures.delete(key);+ }} catch (error) {skipped++;- log(`[sessions-cwd-repair] 跳过 ${cwd}: ${error.message}`);+ // Retry transient failures with bounded backoff. Do not persist/log the+ // filesystem error message: it may contain a private workspace path.+ const code = ['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR', 'EEXIST'].includes(error.code) ? error.code : 'UNSAFE_PATH';+ const attempts = previous ? Math.min(previous.attempts + 1, 5) : 1;+ sessionCwdRepairFailures.set(key, { attempts, code,+ nextRetryAt: Date.now() + Math.min(30000 * Math.pow(2, attempts - 1), 300000) });+ if (!previous || previous.code !== code) {+ log(code === 'UNSAFE_PATH'+ ? '[sessions-cwd-repair] 跳过不安全的会话工作目录(符号链接或非目录路径),稍后重试'+ : `[sessions-cwd-repair] 会话工作目录恢复失败(${code}),稍后重试`);+ }}}+ for (const key of sessionCwdRepairFailures.keys()) {+ if (!activeCwds.has(key)) sessionCwdRepairFailures.delete(key);+ }// 缺失卷的提示只记录卷根,避免写入完整会话路径。for (const root of missingCwdRoots) {if (reportedMissingCwdRoots.has(root)) continue;@@ -6416,7 +6485,7 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {} catch (e) {recoverOpenSessionTarget(src);const errorText = String(e.message || e).slice(0, 240);- if (errorText === '会话消息文件没有消息,未同步') {+ if (['会话消息文件没有消息,未同步', '会话消息文件为空,未同步'].includes(errorText)) {// Empty metadata-only sessions are normal transient WorkBuddy// rows (for example a newly opened draft), not sync failures.if (typeof getSessionDirtyIndex === 'function' && typeof clearSessionDirty === 'function') {diff --git a/scripts/inject.js b/scripts/inject.jsindex f9ecf59..7387910 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -1991,6 +1991,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// —— 第十二批:切换/删除断句模板 + ' 天' 时间变体 ——' 天': ' days','已切换到「': 'Switched to “', '再次点击确认切换': 'Click again to confirm switch', '再次点击确认切换为「': 'Click again to confirm switching to “',+ '切换(可能需要重新登录)': 'Switch (sign-in may be required)',+ ',可能需要重新登录': '; sign-in may be required','切换中…': 'Switching…', '已切换为「': 'Switched to “', '将永久删除「': 'Permanently delete “', '已永久删除「': 'Permanently deleted “',// —— 第十三批:弹窗/登录方式/更新流/会话归档等二级页文案(扫描网修复后暴露)——'确定删除这 {n} 条快捷短语吗?删除后不可恢复。': 'Delete these {n} quick phrases? This cannot be undone.',@@ -8601,7 +8603,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (themePane && !themePane.dataset.built) buildThemePane();syncWallpaperCardVisibility(currentThemeId);}- if (name === 'sessions' && sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();+ if (name === 'sessions' && sessionsPane) {+ if (!sessionsPane.dataset.built) buildSessionsPane();+ else refreshSessionsSilently();+ }if (name === 'models' && modelsPane && !modelsPane.dataset.built) buildModelsPane();if (name === 'enhance' && enhancePane && !enhancePane.dataset.built) buildEnhancePane();if (name === 'automations' && automationPane && !automationPane.dataset.built) buildAutomationPane();@@ -9393,6 +9398,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {wireSessionsPane();loadSessionAccounts();loadSessions();+ setBuildInterval(refreshSessionsSilently, 5000);loadAutomationSyncSetting();pollActiveSessionCopyJob();pollSessionExport();@@ -9502,31 +9508,68 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}).catch(function () {});}- function loadSessions() {+ function canRefreshSessions() {+ return alive && state.open && !document.hidden && sessionsPane && sessionsPane.classList.contains('active') &&+ !sessionsState.batchMode && !Object.keys(sessionsState.selected || {}).some(function (id) { return sessionsState.selected[id]; }) &&+ !sessionsState.autoCopyAllBusy && !sessionsState.autoSyncAutomationsBusy &&+ !(sessionsState.exportJob && sessionsState.exportJob.running) &&+ !(sessionsState.autoCopyJob && /^(queued|running)$/.test(sessionsState.autoCopyJob.status)) &&+ !Array.from(root.querySelectorAll('.wbs-modal-mask, .wbs-panel-modal-mask')).some(function (mask) {+ return !mask.hidden && mask.getClientRects().length > 0;+ });+ }+ function refreshSessionsSilently() {+ if (!canRefreshSessions() || sessionsState.loading) return;+ return loadSessions({ silent: true });+ }+ function loadSessions(options) {if (!sessionsPane) return;var listEl = sessionsPane.querySelector('#wbs-sess-list');if (!listEl) return;- listEl.innerHTML = '<div class="wbs-empty">加载中…</div>';+ var silent = !!(options && options.silent);+ if (silent && (!canRefreshSessions() || sessionsState.loading)) return;+ var snapshot = silent ? JSON.stringify([sessionsState.list, sessionsState.totalBytes, sessionsState.autoCopy, sessionsState.autoCopyAll]) : null;+ var serial = sessionsState.readSerial = (sessionsState.readSerial || 0) + 1;+ sessionsState.loading = true;+ if (!silent) listEl.innerHTML = '<div class="wbs-empty">加载中…</div>';// uid: undefined=当前账号(不传),''=全部账号,具体值=指定账号var url = '/api/sessions?range=' + (sessionsState.range || '7d');if (sessionsState.uid !== undefined) url += '&uid=' + encodeURIComponent(sessionsState.uid);- api(url).then(function (d) {+ return api(url).then(function (d) {+ if (!alive || serial !== sessionsState.readSerial || (silent && !canRefreshSessions())) return;+ // A local rule toggle may finish before this older read returns.+ if (silent && snapshot !== JSON.stringify([sessionsState.list, sessionsState.totalBytes, sessionsState.autoCopy, sessionsState.autoCopyAll])) return;+ var nextList = (d && d.sessions) || [];+ var nextAutoCopy = (d && d.autoCopy) || null;+ if (silent && snapshot === JSON.stringify([nextList, d && d.totalBytes, nextAutoCopy, !!(d && d.autoCopyAll)])) return;+ // Capture at response time so scrolling during the request is retained.+ var listScroll = listEl.scrollTop, bodyScroll = body.scrollTop;// 任务会话(is_playground=1)保留在列表中,由渲染层归入「任务」分组展示与操作。- sessionsState.list = ((d && d.sessions) || []);+ sessionsState.list = nextList;sessionsState.totalBytes = d && d.totalBytes;- sessionsState.autoCopy = (d && d.autoCopy) || null;+ sessionsState.autoCopy = nextAutoCopy;sessionsState.autoCopyAll = !!(d && d.autoCopyAll);- sessionsState.selected = {};- sessionsState.wsExpanded = {};+ if (!silent) {+ sessionsState.selected = {};+ sessionsState.wsExpanded = {};+ }renderSessions();+ if (silent) {+ listEl.scrollTop = listScroll;+ body.scrollTop = bodyScroll;+ }// 筛选变化后退出批量模式(勾选框隐藏 + 恢复工具栏右侧按钮)- if (sessionsState.batchMode) {+ if (!silent && sessionsState.batchMode) {sessionsState.batchMode = false;setSessBatchBar(false);}updateSessCount();}).catch(function (e) {- listEl.innerHTML = '<div class="wbs-empty">会话加载失败: ' + esc(e.message || e) + '</div>';+ if (!silent && alive && serial === sessionsState.readSerial) {+ listEl.innerHTML = '<div class="wbs-empty">会话加载失败: ' + esc(e.message || e) + '</div>';+ }+ }).finally(function () {+ if (serial === sessionsState.readSerial) sessionsState.loading = false;});}@@ -12079,6 +12122,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}fabQuietMode.wake();if (open) {+ if (newlyOpened) refreshSessionsSilently();if (newlyOpened && typeof automationPane !== 'undefined' && automationPane && automationPane.__wbsRefreshDiscovery) automationPane.__wbsRefreshDiscovery();else if (newlyOpened && typeof preloadAutomationDiscovery === 'function') preloadAutomationDiscovery().catch(function () {});if (newlyOpened && !(options && options.automation)) api('/api/automations/events', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ type: 'panelOpened' }) }).catch(function () {});@@ -16778,11 +16822,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var checkinBadge = checkinBadgeHtml(a);var modelRateLimitBadge = typeof modelRateLimitBadgeHtml === 'function' ? modelRateLimitBadgeHtml(a) : '';var invalidAuthBadge = a.authValid === false ? '<span class="wbs-badge wbs-auth-invalid">认证数据无效</span>' : '';- // 当前登录账号隐藏操作;认证已过期的账号保留删除,但隐藏切换,避免进入登录页。- var expired = isIdentityExpired(a);+ // 过期账号仍可手动切换检查登录状态;仅损坏的认证备份禁止切换。+ var expired = isIdentityExpired(a) || a.creditExpired;var ops = (isCur? ''- : (expired || a.authValid === false ? '' : '<button class="wbs-icon-btn wbs-acc-switch" type="button" title="切换" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(accountDisplayName(a, state.mask)) + '">' + SWITCH_SVG + '</button>') ++ : (a.authValid === false ? '' : '<button class="wbs-icon-btn wbs-acc-switch" type="button" title="' + (expired ? '切换(可能需要重新登录)' : '切换') + '" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(accountDisplayName(a, state.mask)) + '">' + SWITCH_SVG + '</button>') +'<button class="wbs-icon-btn wbs-del" type="button" title="删除" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(accountDisplayName(a, state.mask)) + '">' + TRASH_SVG + '</button>');ops = '<div class="wbs-ops"' + (isCur ? ' hidden' : '') + '>' + ops + '</div>';// 国际版没有手机号:用 UIN(账号唯一数字标识)替代展示;国内版仍显示手机。@@ -16809,18 +16853,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {list.querySelectorAll('.wbs-acc-switch').forEach(function (btn) {var armed = false;var armedTimer = null;+ var switchTitle = btn.getAttribute('title');btn.addEventListener('click', function () {if (btn.disabled) return;if (!armed) {armed = true;btn.classList.add('armed');btn.setAttribute('title', '再次点击确认切换');- toast('再次点击确认切换为「' + btn.dataset.name + '」', false, root);+ var needsLogin = state.accounts.some(function (a) {+ return a.uid === btn.dataset.uid && (isIdentityExpired(a) || a.creditExpired);+ });+ toast('再次点击确认切换为「' + btn.dataset.name + '」' + (needsLogin ? ',可能需要重新登录' : ''), false, root);clearTimeout(armedTimer);armedTimer = setBuildTimeout(function () {armed = false;btn.classList.remove('armed');- btn.setAttribute('title', '切换');+ btn.setAttribute('title', switchTitle);}, 3000);return;}@@ -16828,7 +16876,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {armed = false;btn.classList.remove('armed');btn.disabled = true;- var prevTitle = btn.getAttribute('title');+ var prevTitle = switchTitle;btn.setAttribute('title', '切换中…');api('/api/switch', {method: 'POST',@@ -17237,12 +17285,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {nameGroup.insertAdjacentHTML('beforeend', modelLimitBadge);}if (cell) {- var hidden = isIdentityExpired(account);// 不再整格隐藏/清空:过期时由 creditBlockHtml 展示「登录身份过期」诊断文案cell.classList.remove('wbs-credit-hidden');cell.innerHTML = creditBlockHtml(account.credits, account.creditSegments, account);var switchBtn = cards[i].querySelector('.wbs-acc-switch');- if (switchBtn) switchBtn.style.display = hidden || account.creditExpired || account.authValid === false ? 'none' : '';+ if (switchBtn) switchBtn.style.display = account.authValid === false ? 'none' : '';}}updateDailyProgressCells();@@ -17475,11 +17522,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {for (var j = 0; j < state.accounts.length; j++) {if (state.accounts[j].uid === uid) { account = state.accounts[j]; break; }}- var hidden = isIdentityExpired(account);elCredit.classList.remove('wbs-credit-hidden');elCredit.innerHTML = creditBlockHtml(credits, segments || [], account);var cellSwitch = card.querySelector('.wbs-acc-switch');- if (cellSwitch) cellSwitch.style.display = hidden || (account && (account.creditExpired || account.authValid === false)) ? 'none' : '';+ if (cellSwitch) cellSwitch.style.display = account && account.authValid === false ? 'none' : '';}// ===== 调试:暴露内部状态到 window.__wbsDiag(控制台可调) =====diff --git a/scripts/lib.js b/scripts/lib.jsindex e480a56..8435cca 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -198,16 +198,19 @@ function wdCompatStaticKey() {throw new Error(lastErr);}-function wdCompatOpenEnvelope(env, key) {+function wdCompatEnvelopeAAD(env) {const FRAMING_FIELD = 2, FMT_FIELD = 'WBEV1', AAD_DOMAIN = Buffer.from('WB-AAD\0', 'ascii');const lp = (s) => { const b = Buffer.from(s, 'utf8'); const l = Buffer.alloc(4); l.writeUInt32BE(b.length); return Buffer.concat([l, b]); };const u32 = (n) => { const b = Buffer.alloc(4); b.writeUInt32BE(n); return b; };- const aad = Buffer.concat([+ return Buffer.concat([AAD_DOMAIN, Buffer.from([1]), lp(FMT_FIELD), lp('sym-v1'), u32(env.suite || 1),lp(env.keyId || ''), Buffer.from([FRAMING_FIELD]), Buffer.from([0]), Buffer.from([0]),]);+}++function wdCompatOpenEnvelope(env, key) {const d = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(env.nonce, 'base64'), { authTagLength: 16 });- d.setAAD(aad);+ d.setAAD(wdCompatEnvelopeAAD(env));d.setAuthTag(Buffer.from(env.authTag, 'base64'));return Buffer.concat([d.update(Buffer.from(env.ciphertext, 'base64')), d.final()]).toString('utf8');}@@ -235,6 +238,51 @@ function wdCompatDecryptAuthJson(json) {walk(json);return json;}++/** 按原备份的字段信封加密刷新结果;密钥或模板不可用时拒绝写入,绝不降级明文。 */+function wdCompatEncryptAuthJson(json, template) {+ if (!wdCompatContainsEncryptedFields(template)) throw new Error('missing-encryption-template');+ const key = wdCompatStaticKey();+ let fallbackEnvelope = null;+ const envelopes = new Map();+ const inspect = (node) => {+ if (isWbEncryptedEnvelope(node)) {+ const env = JSON.parse(Buffer.from(node.envelope, 'base64').toString('utf8'));+ if (env.suite !== 1) throw new Error('unsupported-encryption-suite');+ wdCompatOpenEnvelope(env, key); // 先验证原信封及密钥,再允许刷新/写入。+ envelopes.set(node, env);+ if (!fallbackEnvelope) fallbackEnvelope = env;+ } else if (node && typeof node === 'object') Object.values(node).forEach(inspect);+ };+ inspect(template);+ const seal = (value, env) => {+ const nonce = crypto.randomBytes(12);+ const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 });+ cipher.setAAD(wdCompatEnvelopeAAD(env));+ const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);+ return { $wbEncrypted: 1, envelope: Buffer.from(JSON.stringify({+ suite: env.suite, keyId: env.keyId || '', nonce: nonce.toString('base64'),+ authTag: cipher.getAuthTag().toString('base64'), ciphertext: ciphertext.toString('base64'),+ })).toString('base64') };+ };+ const credentialKeys = new Set(['accessToken', 'access_token', 'refreshToken', 'refresh_token', 'idToken', 'id_token', 'token']);+ const walk = (value, original, inAuth = false, field = '') => {+ if (isWbEncryptedEnvelope(original)) {+ if (isWbEncryptedEnvelope(value) && value.envelope === original.envelope) return { ...original };+ if (typeof value !== 'string') throw new Error('invalid-encrypted-field-type');+ return seal(value, envelopes.get(original));+ }+ if (inAuth && credentialKeys.has(field) && typeof value === 'string') return seal(value, fallbackEnvelope);+ if (Array.isArray(value)) return value.map((item, index) => walk(item, original && original[index], inAuth));+ if (value && typeof value === 'object') {+ const result = {};+ for (const name of Object.keys(value)) result[name] = walk(value[name], original && original[name], inAuth || name === 'auth', name);+ return result;+ }+ return value;+ };+ return walk(json, template);+}// ===================== [wd-compat] 适配层结束 =====================function samePath(a, b) {@@ -1913,6 +1961,7 @@ module.exports = {wdCompatHasAuthCredential, // [wd-compat]normalizeAccountImportJson, // [wd-compat]wdCompatDecryptAuthJson, // [wd-compat]+ wdCompatEncryptAuthJson, // [wd-compat]getAccountOrder,setAccountOrder,setAccountNote,diff --git a/scripts/persona.js b/scripts/persona.jsindex 499d708..6baa197 100644--- a/scripts/persona.js+++ b/scripts/persona.js@@ -96,8 +96,24 @@ function inspectPersona(options) {return { uid: targetUid, status, eligible: ['missing', 'empty', 'bootstrap'].includes(status) && sources.length > 0, sources, revision };}+// The configured backup root may be redirected (for example an AppData+// Junction). Canonicalize that trusted root, including a not-yet-created suffix;+// paths inside persona still pass through assertSafePath without following links.+function resolveBackupRoot(backupRoot) {+ let cursor = path.resolve(backupRoot);+ const missing = [];+ for (;;) {+ try { return path.join(fs.realpathSync(cursor), ...missing); }+ catch (error) {+ const parent = path.dirname(cursor);+ if (error.code !== 'ENOENT' || parent === cursor) throw error;+ missing.unshift(path.basename(cursor));+ cursor = parent;+ }+ }+}function personaSettingsFile(backupRoot) {- const file = path.join(path.resolve(backupRoot), 'persona', 'settings.json');+ const file = path.join(resolveBackupRoot(backupRoot), 'persona', 'settings.json');assertSafePath(file);return file;}@@ -127,7 +143,7 @@ function dismissPersonaNotice(backupRoot) {return writePersonaSettings(backupRoot, { ...readPersonaSettings(backupRoot), noticeDismissed: true });}function sharedPersonaDir(backupRoot) {- const dir = path.join(path.resolve(backupRoot), 'persona', 'shared');+ const dir = path.join(resolveBackupRoot(backupRoot), 'persona', 'shared');assertSafePath(dir);return dir;}@@ -146,7 +162,7 @@ function listPersonaSources({ dataRoot, accounts = [] }) {return sources;}function backupPersonaDirectory(backupRoot, label, original) {- const dir = path.join(path.resolve(backupRoot), 'persona', 'backups', label,+ const dir = path.join(resolveBackupRoot(backupRoot), 'persona', 'backups', label,`${Date.now()}-${crypto.randomBytes(6).toString('hex')}`);assertSafePath(dir);fs.mkdirSync(dir, { recursive: true, mode: 0o700 });@@ -232,10 +248,14 @@ function configurePersona(options) {}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 (settings.mode !== 'shared') return { skipped: true };+ // The login page has no auth uid. Resume from the last shared projection so+ // edits made before logout survive, without adopting another logged-in user.+ const sourceUid = options.sourceUid || settings.activeUid;+ if (sourceUid === options.targetUid) return { skipped: true };+ if (settings.activeUid !== 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 sourceDir = personaDir(options.dataRoot, sourceUid);const files = snapshot(sourceDir);return applySharedPersona({ ...options, sourceDir }, files, { ...settings, activeUid: options.targetUid });}@@ -254,7 +274,7 @@ function copyPersona(options) {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')}`);+ const backupDir = path.join(resolveBackupRoot(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' });diff --git a/test/account-list-stability.test.js b/test/account-list-stability.test.jsindex b318d0b..72ce07c 100644--- a/test/account-list-stability.test.js+++ b/test/account-list-stability.test.js@@ -32,7 +32,7 @@ function harness() {updateCheckinCells() {}, updateCreditCell() {}, fetchActivityForAccounts() {}, toast() {}, root: {},MODEL_EDIT_SVG: '', PRIMARY_ACCOUNT_SVG: '', SWITCH_SVG: '', TRASH_SVG: '',setBuildTimeout: fn => fn(), setTimeout: () => 1, clearTimeout() {},- checkForUpdate() {}, acCheckPromptOnOpen() {}, syncSessionModule() {}, fetchDailyProgressForAccounts() {}, pollActiveSessionCopyNotice() {},+ checkForUpdate() {}, acCheckPromptOnOpen() {}, syncSessionModule() {}, refreshSessionsSilently() {}, fetchDailyProgressForAccounts() {}, pollActiveSessionCopyNotice() {},});vm.runInContext([section(' function isKnownActivityStreak(', ' function el(tag'),@@ -180,6 +180,37 @@ test('fresh current-account and identity changes update card controls', () => {assert.equal(h.cards()[1].className, 'wbs-card cur');});+test('expired identities retain a manual switch while malformed backups remain blocked', () => {+ const h = harness();+ h.ctx.render({ accounts: [+ { ...account('expired', 100), identityExpired: true },+ { ...account('invalid', 200), authValid: false },+ ] });+ assert.match(h.cards()[0].innerHTML, /wbs-acc-switch/);+ assert.match(h.cards()[0].innerHTML, /可能需要重新登录/);+ assert.doesNotMatch(h.cards()[1].innerHTML, /wbs-acc-switch/);+});++test('a background credit expiry response does not hide the manual switch', () => {+ const button = { style: {} };+ const credit = { classList: { remove() {} } };+ const card = {+ getAttribute: () => 'expired',+ querySelector: selector => selector === '.wbs-credit-cell' ? credit : button,+ };+ const ctx = {+ state: { accounts: [{ uid: 'expired', creditExpired: true }] },+ accountsPane: { querySelectorAll: () => [card] },+ isIdentityExpired: () => true, creditBlockHtml: () => '登录身份过期',+ };+ vm.runInNewContext(section(' function updateCreditCell(', ' // ===== 调试'), ctx);+ ctx.updateCreditCell('expired', null, []);+ assert.equal(button.style.display, '');+ ctx.state.accounts[0].authValid = false;+ ctx.updateCreditCell('expired', null, []);+ assert.equal(button.style.display, 'none');+});+test('account metadata refresh retains valid activity days while the server cache is missing or failed', () => {const h = harness();h.ctx.render({ accounts: [{ ...account('a', 100), activityStreak: { days: 5, status: 'ready' } }] });diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.jsindex c8a4fae..2f7e714 100644--- a/test/automation-checkin.test.js+++ b/test/automation-checkin.test.js@@ -150,7 +150,7 @@ test('panel-open emits once per user opening and excludes automation restorationconst calls=[];const noop=()=>{};const ctx={window:{},state:{open:false,creditRunId:0},panel:{classList:{toggle:noop}},fab:{classList:{toggle:noop}},api:(route,options)=>{if(route==='/api/automations/discovery')return Promise.resolve({tasks:[]});calls.push([route,JSON.parse(options.body).type]);return Promise.resolve();},- preloadAutomationDiscovery:()=>Promise.resolve({tasks:[]}),CAPS:{accounts:false},refresh:noop,checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,closeSessionCopyNotice:noop,fabQuietMode:{wake:noop}};+ preloadAutomationDiscovery:()=>Promise.resolve({tasks:[]}),CAPS:{accounts:false},refresh:noop,refreshSessionsSilently:noop,checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,closeSessionCopyNotice:noop,fabQuietMode:{wake:noop}};vm.createContext(ctx);vm.runInContext(ui.slice(start,end),ctx);ctx.setOpen(true);ctx.setOpen(true);assert.equal(calls.length,1);ctx.setOpen(false);ctx.setOpen(true,{automation:true});assert.equal(calls.length,1);diff --git a/test/automation-model.test.js b/test/automation-model.test.jsindex a2844ae..9eac42d 100644--- a/test/automation-model.test.js+++ b/test/automation-model.test.js@@ -74,7 +74,7 @@ function rendererHarness(session, options = {}) {let menuOpen = false;let selectedCalls = 0;const storage = new Map([['cb-newtask:model:account', JSON.stringify({ id: selected, reasoningEffort: 'high' })]]);- const names = { 'original-model': 'Original', 'deepseek-v4.1-flash': 'Deepseek-V4.1-Flash' };+ const names = { 'original-model': 'Original', ...(options.models || { 'deepseek-v4.1-flash': 'Deepseek-V4.1-Flash' }) };const trigger = {innerText: names[selected],getBoundingClientRect: () => ({ width: 90, height: 25 }),@@ -152,6 +152,65 @@ test('an unconfirmed core switch restores the previously selected model', asyncassert.equal(session.state().menuOpen, false);});+test('bare custom model IDs resolve to the real ID for verification and preference restoration', async () => {+ for (const session of [false, true]) {+ const h = rendererHarness(session, { models: { 'custom-local:fixture': 'Fixture' } });+ const selection = await h.run({ model: 'fixture', ...(session ? { conversationId: 'conversation' } : { accountUid: 'account' }) });+ assert.equal(selection.model, 'custom-local:fixture');+ assert.equal(h.verify({ model: selection.model, ...(session ? { conversationId: 'conversation' } : { accountUid: 'account' }) }), true);+ if (!session) assert.equal(h.restore(selection).restored, true);+ }+});++test('exact model IDs take precedence and explicit custom IDs never select an official namesake', async () => {+ const h = rendererHarness(true, { models: { 'custom-local:fixture': 'Custom', fixture: 'Official' } });+ assert.equal((await h.run({ model: 'fixture', conversationId: 'conversation' })).model, 'fixture');+ assert.equal(h.state().selected, 'fixture');+ assert.equal((await h.run({ model: 'custom-local:fixture', conversationId: 'conversation' })).model, 'custom-local:fixture');+ assert.equal(h.verify({ model: 'fixture', conversationId: 'conversation' }), false, 'send guard must use the resolved full ID');+ const officialOnly = rendererHarness(true, { models: { fixture: 'Official' } });+ await assert.rejects(officialOnly.run({ model: 'custom-local:fixture', conversationId: 'conversation' }), /未知模型/);+ assert.equal(officialOnly.state().selectedCalls, 0);+});++test('daemon send guards and receipts use the resolved custom ID for new and existing sessions', async () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ const start = source.indexOf(' const sessionAction = async (op, detail) => {');+ const end = source.indexOf(' // Compatibility aliases', start);+ assert.ok(start > 0 && end > start);+ for (const op of ['session.create', 'session.send']) {+ let submitted = false;+ const confirmed = [];+ const ctx = {+ isCancelled: () => false, currentAccount: () => ({ uid: 'account' }),+ normalizeAutomationModelId, withInput: async fn => fn(),+ ensureAutomationNewTask: async () => {}, appendRunLog() {}, lastReceipt: null,+ readSession: async () => submitted ? { conversationId: 'conversation', userMessageId: 'sent' }+ : op === 'session.send' ? { conversationId: 'conversation', userMessageId: 'previous', busy: false } : null,+ selectAutomationModelById: async model => {+ assert.equal(model, 'fixture');+ return { model: 'custom-local:fixture', changed: true, displayName: 'Fixture' };+ },+ confirmAutomationModel: async model => {+ assert.equal(model, 'custom-local:fixture'); confirmed.push(model);+ },+ acSendPhrase: async (_message, options) => {+ await options.guard(); options.beforeSubmit(); submitted = true;+ },+ readAutomationAgentSurface: async () => ({ newTaskReady: false }),+ restoreAutomationNewTaskPreference: async selection => {+ assert.equal(selection.model, 'custom-local:fixture'); return { restored: true };+ },+ Date,+ };+ vm.runInNewContext(source.slice(start, end) + '\nglobalThis.sessionAction = sessionAction;', ctx);+ const receipt = await ctx.sessionAction(op, { model: 'fixture', message: 'fixture', conversationId: 'conversation' });+ assert.equal(receipt.model, 'custom-local:fixture');+ assert.equal(receipt.userMessageId, 'sent');+ assert.equal(confirmed.length, op === 'session.create' ? 2 : 1);+ }+});+test('daemon selects and checks the model before sending, and ships the renderer helper', () => {const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const selectAt = daemon.indexOf('modelSelection = await withInput(() => selectAutomationModelById(');diff --git a/test/automation-panel-input.test.js b/test/automation-panel-input.test.jsindex 98fc28e..4283b58 100644--- a/test/automation-panel-input.test.js+++ b/test/automation-panel-input.test.js@@ -5,7 +5,7 @@ const ui=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');test('panel opening is blocked only during input; waiting for a reply still allows access',()=>{const calls=[];const noop=()=>{};- const ctx={window:{__wbsAutomationInputActive:true},state:{open:false},root:{},panel:{classList:{toggle:noop}},fab:{classList:{toggle:noop}},CAPS:{accounts:false},fabQuietMode:{wake:noop},toast:()=>calls.push('blocked'),refresh:()=>calls.push('refresh'),checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,closeSessionCopyNotice:noop,api:()=>Promise.resolve()};+ const ctx={window:{__wbsAutomationInputActive:true},state:{open:false},root:{},panel:{classList:{toggle:noop}},fab:{classList:{toggle:noop}},CAPS:{accounts:false},fabQuietMode:{wake:noop},toast:()=>calls.push('blocked'),refresh:()=>calls.push('refresh'),refreshSessionsSilently:noop,checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,closeSessionCopyNotice:noop,api:()=>Promise.resolve()};const start=ui.indexOf(' function setOpen(open, options)');vm.runInNewContext(ui.slice(start,ui.indexOf(' function setupFabDrag()',start)),ctx);ctx.setOpen(true);assert.equal(ctx.state.open,false);assert.deepEqual(calls,['blocked']);diff --git a/test/automation-switch-sync.test.js b/test/automation-switch-sync.test.jsindex 0053d66..07fc255 100644--- a/test/automation-switch-sync.test.js+++ b/test/automation-switch-sync.test.js@@ -110,11 +110,11 @@ test('pruning public job history cannot erase failed synchronization; successfulassert.deepEqual(h.switches, ['b']);});-test('an empty message-file session does not block automation account switching', async () => {+for (const error of ['会话消息文件没有消息,未同步', '会话消息文件为空,未同步']) test('empty sessions do not block automation account switching: ' + error, async () => {const h = harness();const run = h.ctx.automationSwitchAccount({ uid: 'b' }, h.options);await tick(); await tick();- h.jobs[0].finish('partial', [{ status: 'failed', error: '会话消息文件没有消息,未同步' }]);+ h.jobs[0].finish('partial', [{ status: 'failed', error }]);await run;assert.deepEqual(h.switches, ['b']);});diff --git a/test/persona-api.test.js b/test/persona-api.test.jsindex e91e0fc..023264d 100644--- a/test/persona-api.test.js+++ b/test/persona-api.test.js@@ -104,3 +104,44 @@ test('shared switching protects authentication until projection succeeds and undawait assert.rejects(context.switchAccountForProfile('a'),/尚未完成/);assert.equal(switched,false);});++for (const profile of ['workbuddy-cn', 'workbuddy-ai']) {+ for (const targetUid of ['a', 'b']) test(profile + ': login-page switching resumes shared persona for ' + targetUid, async t => {+ const h = harness(t, profile);+ 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 });+ fs.writeFileSync(path.join(h.dataRoot, 'user-b-personal/USER.md'), 'latest shared edit');+ let current = null;+ const switches = [];+ const context = vm.createContext({ ...h.context, codeBuddyNative: null, currentAccount: () => current,+ listAccounts: () => options.accounts,+ switchTo: async (_, uid) => { switches.push(uid); current = { uid }; return current; },+ });+ const seam = daemon.slice(daemon.indexOf('async function switchAccountForProfile(uid)'), daemon.indexOf('\nfunction scheduleBackup('));+ vm.runInContext(seam, context);+ assert.equal((await context.switchAccountForProfile(targetUid)).uid, targetUid);+ assert.deepEqual(switches, [targetUid]);+ assert.equal(persona.readPersonaSettings(options.backupRoot).activeUid, targetUid);+ assert.equal(fs.readFileSync(path.join(h.dataRoot, `user-${targetUid}-personal/USER.md`), 'utf8'), 'latest shared edit');+ const nextUid = targetUid === 'a' ? 'b' : 'a';+ await context.switchAccountForProfile(nextUid);+ assert.equal(persona.readPersonaSettings(options.backupRoot).activeUid, nextUid);+ assert.equal(fs.readFileSync(path.join(h.dataRoot, `user-${nextUid}-personal/USER.md`), 'utf8'), 'latest shared edit');+ });+}++test('login-page auth failure rolls shared persona back; a different logged-in account remains guarded', 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, currentAccount: () => null,+ listAccounts: () => options.accounts, 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');+ context.currentAccount = () => ({ uid: 'a' });+ await assert.rejects(context.switchAccountForProfile('b'), /当前账号已变化/);+});diff --git a/test/persona-migration.test.js b/test/persona-migration.test.jsindex 8b5a7fc..8d85cac 100644--- a/test/persona-migration.test.js+++ b/test/persona-migration.test.js@@ -64,6 +64,18 @@ test('explicit scoped source wins over stale legacy files', t => {f.copy({ sourceUid: 'a' });assert.equal(fs.readFileSync(path.join(f.target, 'MEMORY.md'), 'utf8'), 'scoped MEMORY.md');});+test('explicit repair backs up through a redirected backup root', t => {+ const f = fixture(t);+ fs.mkdirSync(f.opts.backupRoot);+ const alias = f.opts.backupRoot + '-alias';+ fs.symlinkSync(f.opts.backupRoot, alias, process.platform === 'win32' ? 'junction' : 'dir');+ f.opts.backupRoot = alias;+ f.write(f.target, 'BOOTSTRAP.md', 'original');+ const result = f.copy();+ assert.equal(fs.readFileSync(path.join(result.backupDir, 'BOOTSTRAP.md'), 'utf8'), 'original');+ assert.equal(fs.existsSync(path.join(f.target, 'BOOTSTRAP.md')), false);+ assert.equal(f.preview().status, 'initialized');+});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'); }diff --git a/test/persona-sharing.test.js b/test/persona-sharing.test.jsindex b65656d..28efb69 100644--- a/test/persona-sharing.test.js+++ b/test/persona-sharing.test.js@@ -23,6 +23,39 @@ test('dismissal persists without selecting a mode and can later enable sharing',f.enable();assert.equal(p.readPersonaSettings(f.options.backupRoot).mode,'shared');});+test('a redirected backup root supports unset settings, sharing and rollback without following inner links', t => {+ const f = fixture(t);+ const actualRoot = f.options.backupRoot;+ fs.mkdirSync(actualRoot);+ const alias = actualRoot + '-alias';+ fs.symlinkSync(actualRoot, alias, process.platform === 'win32' ? 'junction' : 'dir');+ f.options.backupRoot = alias;+ assert.equal(p.readPersonaSettings(alias).mode, 'unset');+ assert.equal(p.syncSharedPersonaForSwitch({ ...f.options, sourceUid: 'a', targetUid: 'b' }).skipped, true);+ f.enable();+ f.write('a', 'USER.md', 'updated');+ const prepared = p.syncSharedPersonaForSwitch({ ...f.options, sourceUid: 'a', targetUid: 'b' });+ assert.equal(fs.readFileSync(f.file('b', 'USER.md'), 'utf8'), 'updated');+ prepared.rollback();+ assert.equal(fs.readFileSync(f.file('b', 'USER.md'), 'utf8'), 'bUSER.md');+ const outside = path.join(path.dirname(actualRoot), 'outside');+ fs.mkdirSync(outside);+ fs.rmSync(path.join(actualRoot, 'persona', 'shared'), { recursive: true });+ fs.symlinkSync(outside, path.join(actualRoot, 'persona', 'shared'), process.platform === 'win32' ? 'junction' : 'dir');+ assert.throws(() => p.syncSharedPersonaForSwitch({ ...f.options, sourceUid: 'a', targetUid: 'b' }), /符号链接/);+ assert.deepEqual(fs.readdirSync(outside), []);+});+test('a not-yet-created backup root beneath a redirected parent can initialize settings', t => {+ const f = fixture(t);+ const actualRoot = f.options.backupRoot;+ fs.mkdirSync(actualRoot);+ const alias = actualRoot + '-alias';+ fs.symlinkSync(actualRoot, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const nested = path.join(alias, 'new', 'profile');+ assert.equal(p.readPersonaSettings(nested).mode, 'unset');+ p.dismissPersonaNotice(nested);+ assert.equal(p.readPersonaSettings(path.join(actualRoot, 'new', 'profile')).noticeDismissed, true);+});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');diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.jsindex 59a1277..e42b00f 100644--- a/test/renderer-escaping.test.js+++ b/test/renderer-escaping.test.js@@ -44,7 +44,7 @@ test('toast content is always written as text', () => {});test('session and account selectors escape every text and attribute sink', () => {- const accountSelect = sourceBetween('function loadSessionAccounts()', 'function loadSessions()');+ const accountSelect = sourceBetween('function loadSessionAccounts()', 'function canRefreshSessions()');assert.match(accountSelect, /'<option value="' \+ escAttr\(a\.uid\) \+ '">' \+ esc\(a\.nickname/);assert.doesNotMatch(accountSelect, /'<option value="' \+ a\.uid/);assert.doesNotMatch(accountSelect, /\+ \(a\.nickname \|\|/);diff --git a/test/session-cwd-repair.test.js b/test/session-cwd-repair.test.jsindex e148dc7..34b1031 100644--- a/test/session-cwd-repair.test.js+++ b/test/session-cwd-repair.test.js@@ -20,10 +20,11 @@ function harness({ isWin = true, kind = 'workbuddy' } = {}) {{ 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,+ missingPayloads: new Set(), mkdir: [], logs: [], denied: false, queries: 0, now: 1000000,};const missing = () => Object.assign(new Error('fixture path missing'), { code: 'ENOENT' });const context = vm.createContext({+ Date: { now: () => state.now },path: path.win32,fs: {existsSync(target) {@@ -94,15 +95,26 @@ test('missing UNC shares are skipped and can recover on a later repair tick', asassert.deepEqual(Array.from((await h.tick()).repaired), [cwd]);});-test('mounted-drive permission failures retain the existing retry behavior', async () => {+test('mounted-drive permission failures back off and recover without flooding logs or exposing paths', 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.equal(h.state.mkdir.length, 2);+ assert.equal(h.state.logs.length, 2);+ assert.ok(h.state.logs.every(message => !message.includes('fixture') && !message.includes('project')));assert.ok(h.state.logs.every(message => !message.includes('所在卷不存在')));+ h.state.now += 30000;+ await h.tick();+ assert.equal(h.state.mkdir.length, 4);+ assert.equal(h.state.logs.length, 2);+ h.state.denied = false;+ h.state.now += 60000;+ assert.equal((await h.tick()).repaired.length, 2);+ h.state.directories.clear();+ h.state.denied = true;+ await h.tick();+ assert.equal(h.state.logs.filter(message => message.includes('EACCES')).length, 4, 'a recovered path starts a fresh failure episode');});test('existing directories and sessions without stored payloads are never recreated', async () => {@@ -115,11 +127,46 @@ test('existing directories and sessions without stored payloads are never recreaassert.deepEqual(h.state.logs, []);});+test('repair backoff is capped and deleting a session clears its failure episode', async () => {+ const h = harness();+ h.state.rows = [h.state.rows[0]];+ const rows = h.state.rows;+ h.state.roots.add('G:\\'); h.state.denied = true;+ await h.tick();+ let attempts = 1;+ for (const delay of [30000, 60000, 120000, 240000, 300000, 300000]) {+ h.state.now += delay - 1; await h.tick();+ assert.equal(h.state.mkdir.length, attempts);+ h.state.now++; await h.tick();+ assert.equal(h.state.mkdir.length, ++attempts);+ }+ assert.equal(h.state.logs.length, 1);+ h.state.rows = []; await h.tick();+ h.state.rows = rows; await h.tick();+ assert.equal(h.state.mkdir.length, attempts + 1);+ assert.equal(h.state.logs.length, 2);+});++test('a payload-less session sharing a failed workspace cannot reset its backoff', async () => {+ const h = harness();+ h.state.rows[1].cwd = h.state.rows[0].cwd;+ h.state.missingPayloads.add(h.state.rows[1].id);+ h.state.roots.add('G:\\'); h.state.denied = true;+ await h.tick(); await h.tick();+ assert.equal(h.state.mkdir.length, 1);+ assert.equal(h.state.logs.length, 1);+ h.state.missingPayloads.add(h.state.rows[0].id);+ await h.tick();+ h.state.missingPayloads.clear(); await h.tick();+ assert.equal(h.state.mkdir.length, 2);+ assert.equal(h.state.logs.length, 2);+});+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);+ for (let tick = 0; tick < 3; tick++) 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('符号链接')));diff --git a/test/session-refresh-ui.test.js b/test/session-refresh-ui.test.jsnew file mode 100644index 0000000..d1670ec--- /dev/null+++ b/test/session-refresh-ui.test.js@@ -0,0 +1,124 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');+const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+const flush = () => new Promise(resolve => setImmediate(resolve));++function harness() {+ const requests = [], masks = [];+ const list = { innerHTML: 'existing rows', scrollTop: 12 };+ let active = true, renders = 0, counts = 0;+ const ctx = vm.createContext({+ alive: true, state: { open: true }, document: { hidden: false },+ body: { scrollTop: 30 },+ root: { querySelectorAll: () => masks },+ sessionsPane: { classList: { contains: () => active }, querySelector: () => list },+ sessionsState: { range: 'all', list: [{ id: 'old' }], selected: {}, wsExpanded: { workspace: 8 }, batchMode: false },+ api(url) { return new Promise((resolve, reject) => requests.push({ url, resolve, reject })); },+ renderSessions() { renders++; list.innerHTML = 'rendered'; list.scrollTop = 0; ctx.body.scrollTop = 0; },+ updateSessCount() { counts++; }, setSessBatchBar() {}, esc: text => text,+ });+ const start = source.indexOf(' function canRefreshSessions(');+ const end = source.indexOf(' function loadAutomationSyncSetting()', start);+ assert.ok(start > 0 && end > start, 'refresh guards and loader must be available');+ vm.runInContext(source.slice(start, end), ctx);+ return { ctx, requests, list, masks, setActive(value) { active = value; }, renders: () => renders, counts: () => counts };+}++test('returning to a built session tab requests a silent refresh and the poll uses disposed build timers', () => {+ const h = harness();+ const start = source.indexOf(' function switchTab(name)');+ Object.assign(h.ctx, {+ root: { querySelectorAll: () => [] }, sessionsPane: { dataset: { built: '1' } },+ themePane: null, modelsPane: null, enhancePane: null, automationPane: null, pcPane: null, aboutPane: null, settingsPane: null,+ refreshSessionsSilently() { h.ctx.refreshed = true; },+ });+ vm.runInContext(source.slice(start, source.indexOf(' var tabBtns =', start)), h.ctx);+ h.ctx.switchTab('sessions');+ assert.equal(h.ctx.refreshed, true);+ assert.match(source, /setBuildInterval\(refreshSessionsSilently, 5000\)/);+ assert.match(source, /if \(newlyOpened\) refreshSessionsSilently\(\)/);+});++test('silent reconciliation preserves expanded groups and the scroll position at response time without a loading flash', async () => {+ const h = harness(), expanded = h.ctx.sessionsState.wsExpanded;+ const run = h.ctx.refreshSessionsSilently();+ h.ctx.refreshSessionsSilently();+ assert.equal(h.requests.length, 1, 'coalesce concurrent background reads');+ assert.equal(h.list.innerHTML, 'existing rows');+ h.list.scrollTop = 47; h.ctx.body.scrollTop = 81;+ h.requests[0].resolve({ sessions: [{ id: 'remaining' }], totalBytes: 3 });+ await run;+ assert.equal(h.ctx.sessionsState.list[0].id, 'remaining');+ assert.equal(h.ctx.sessionsState.wsExpanded, expanded);+ assert.equal(h.list.scrollTop, 47);+ assert.equal(h.ctx.body.scrollTop, 81);+ assert.equal(h.renders(), 1);+});++test('hidden panels, inactive tabs, selections, batch operations and visible dialogs suspend silent refresh', () => {+ for (const mutate of [+ h => { h.ctx.state.open = false; }, h => { h.ctx.document.hidden = true; },+ h => h.setActive(false), h => { h.ctx.sessionsState.batchMode = true; },+ h => { h.ctx.sessionsState.selected = { old: true }; },+ h => h.masks.push({ hidden: false, getClientRects: () => [1] }),+ h => { h.ctx.sessionsState.exportJob = { running: true }; },+ h => { h.ctx.sessionsState.autoCopyJob = { status: 'running' }; },+ h => { h.ctx.sessionsState.autoCopyAllBusy = true; },+ h => { h.ctx.sessionsState.autoSyncAutomationsBusy = true; },+ ]) {+ const h = harness(); mutate(h); h.ctx.refreshSessionsSilently();+ assert.equal(h.requests.length, 0);+ }+});++test('a dialog or selection opened during a background request prevents replacement', async () => {+ for (const mutate of [+ h => { h.ctx.sessionsState.selected = { old: true }; },+ h => h.masks.push({ hidden: false, getClientRects: () => [1] }),+ h => { h.ctx.alive = false; },+ h => { h.ctx.sessionsState.list[0].autoCopySession = true; },+ h => { h.ctx.sessionsState.autoCopyAll = true; },+ ]) {+ const h = harness(); const run = h.ctx.refreshSessionsSilently(); mutate(h);+ h.requests[0].resolve({ sessions: [] }); await run;+ assert.equal(h.ctx.sessionsState.list[0].id, 'old');+ assert.equal(h.renders(), 0);+ }+});++test('stale background results cannot replace a newer filter response', async () => {+ const h = harness(); const old = h.ctx.refreshSessionsSilently();+ h.ctx.sessionsState.range = '7d';+ const current = h.ctx.loadSessions();+ assert.match(h.requests[1].url, /range=7d/);+ h.requests[1].resolve({ sessions: [{ id: 'new-filter' }] }); await current;+ h.requests[0].resolve({ sessions: [{ id: 'stale-filter' }] }); await old;+ assert.equal(h.ctx.sessionsState.list[0].id, 'new-filter');+ assert.equal(h.renders(), 1);+});++test('background errors leave existing rows intact and allow a later retry', async () => {+ const h = harness(); const run = h.ctx.refreshSessionsSilently();+ h.requests[0].reject(Error('offline')); await run;+ assert.equal(h.list.innerHTML, 'existing rows');+ h.ctx.refreshSessionsSilently();+ assert.equal(h.requests.length, 2);+ h.requests[1].resolve({ sessions: [] }); await flush();+ assert.equal(h.ctx.sessionsState.list.length, 0);+});++test('unchanged background snapshots do not replace the session DOM', async () => {+ const h = harness();+ const data = { sessions: [{ id: 'old' }], totalBytes: 3, autoCopy: null, autoCopyAll: false };+ h.ctx.sessionsState.totalBytes = 3;+ h.ctx.sessionsState.autoCopy = null;+ h.ctx.sessionsState.autoCopyAll = false;+ const run = h.ctx.refreshSessionsSilently();+ h.requests[0].resolve(data); await run;+ assert.equal(h.renders(), 0);+ assert.equal(h.list.innerHTML, 'existing rows');+});diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.jsindex f2652b3..574fec4 100644--- a/test/session-sync-daemon.test.js+++ b/test/session-sync-daemon.test.js@@ -664,7 +664,7 @@ test('unchanged requested session resolves its target without entering the copyassert.equal(ctx.publicAutoCopyJob(job).openSessionId, 'existing-target');});-test('empty message sessions are skipped instead of shown as sync failures', async () => {+for (const error of ['会话消息文件没有消息,未同步', '会话消息文件为空,未同步']) test('empty message sessions are skipped instead of shown as sync failures: ' + error, async () => {let cleared = 0;const ctx = { codeBuddyFiles: null,crypto,@@ -672,7 +672,7 @@ test('empty message sessions are skipped instead of shown as sync failures', asyautoCopyJobs: new Map(), autoCopyQueue: [], Date,yieldAutoCopyToRenderer: async () => {},buildAutoCopyPlan: async () => [{ id: 'empty-session' }],- copySessionRecord: async () => { throw Error('会话消息文件没有消息,未同步'); },+ copySessionRecord: async () => { throw Error(error); },getSessionDirtyIndex: () => ({ get: () => ({ at: 7 }) }),clearSessionDirty: (_uid, _id, at) => { if (at === 7) cleared++; return true; },log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout,diff --git a/test/token-refresh-persistence.test.js b/test/token-refresh-persistence.test.jsnew file mode 100644index 0000000..9189e28--- /dev/null+++ b/test/token-refresh-persistence.test.js@@ -0,0 +1,253 @@+'use strict';++const assert = require('node:assert/strict');+const crypto = require('node:crypto');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const vm = require('node:vm');+const test = require('node:test');+const { normalizeTimestamp, shouldRefreshAccessToken, refreshAuthToken } = require('../scripts/token-refresh');+const { PROFILES } = require('../scripts/profiles');+const { replaceNativeSession } = require('../scripts/codebuddy-native');++// Exercise the real crypto helpers without obtaining a user's WorkBuddy key.+const fixtureKey = Buffer.alloc(32, 7);+function cryptoHarness() {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/lib.js'), 'utf8');+ const start = source.indexOf('function isWbEncryptedEnvelope(');+ const end = source.indexOf('// ===================== [wd-compat] 适配层结束', start);+ return vm.runInNewContext(source.slice(start, end) + '\n({wdCompatEncryptAuthJson, wdCompatDecryptAuthJson, wdCompatContainsEncryptedFields, wdCompatAuthToken, wdCompatHasAuthCredential, wdCompatText, isWbEncryptedEnvelope});', {+ crypto, Buffer, WD_COMPAT: { key: fixtureKey, decOk: 0, decFail: 0 },+ wdCompatLog() {},+ });+}++// Independent fixture matching the official field-envelope wire format.+function envelope(value) {+ const lp = (value) => {+ const bytes = Buffer.from(value);+ const length = Buffer.alloc(4);+ length.writeUInt32BE(bytes.length);+ return Buffer.concat([length, bytes]);+ };+ const nonce = crypto.randomBytes(12);+ const cipher = crypto.createCipheriv('aes-256-gcm', fixtureKey, nonce);+ cipher.setAAD(Buffer.concat([+ Buffer.from('WB-AAD\0'), Buffer.from([1]), lp('WBEV1'), lp('sym-v1'),+ Buffer.from([0, 0, 0, 1]), lp('fixture-key'), Buffer.from([2, 0, 0]),+ ]));+ const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);+ return { $wbEncrypted: 1, envelope: Buffer.from(JSON.stringify({+ suite: 1, keyId: 'fixture-key', nonce: nonce.toString('base64'),+ authTag: cipher.getAuthTag().toString('base64'), ciphertext: ciphertext.toString('base64'),+ })).toString('base64') };+}++function fixture() {+ return {+ account: { uid: 'fixture', nickname: envelope('private-nickname') },+ auth: { accessToken: envelope('old-access'), refreshToken: envelope('old-refresh'),+ expiresAt: Date.now() + 7 * 86400000, lastRefreshTime: Date.now() - 86400000 },+ };+}++test('refreshed credentials retain official encrypted envelopes for every protected field', () => {+ const compat = cryptoHarness();+ const stored = fixture();+ const root = compat.wdCompatDecryptAuthJson(structuredClone(stored));+ Object.assign(root.auth, { accessToken: 'new-access', refreshToken: 'new-refresh', idToken: 'new-id' });+ const encrypted = compat.wdCompatEncryptAuthJson(root, stored);+ for (const value of ['new-access', 'new-refresh', 'new-id', 'private-nickname']) {+ assert.equal(JSON.stringify(encrypted).includes(value), false);+ }+ assert.equal(encrypted.auth.idToken.$wbEncrypted, 1);+ const roundtrip = compat.wdCompatDecryptAuthJson(structuredClone(encrypted));+ assert.equal(roundtrip.auth.accessToken, 'new-access');+ assert.equal(roundtrip.auth.refreshToken, 'new-refresh');+ assert.equal(roundtrip.auth.idToken, 'new-id');+ assert.equal(roundtrip.account.nickname, 'private-nickname');+ assert.notEqual(encrypted.auth.accessToken.envelope, stored.auth.accessToken.envelope);+ const tampered = structuredClone(encrypted);+ const inner = JSON.parse(Buffer.from(tampered.auth.accessToken.envelope, 'base64'));+ inner.keyId = 'wrong-key';+ tampered.auth.accessToken.envelope = Buffer.from(JSON.stringify(inner)).toString('base64');+ assert.equal(compat.wdCompatDecryptAuthJson(tampered).auth.accessToken.$wbEncrypted, 1);+});++function daemonHarness(t, options = {}) {+ const compat = cryptoHarness();+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-token-persistence-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(dir, 'accounts'));+ const file = path.join(dir, 'accounts/fixture.info');+ const stored = fixture();+ if (options.profile) stored.auth.domain = options.profile.apiHost;+ fs.writeFileSync(file, JSON.stringify(options.plaintext+ ? compat.wdCompatDecryptAuthJson(stored) : stored), { mode: 0o600 });+ let requests = 0;+ let failWrite = false;+ const context = {+ ...compat, fs: { ...fs, writeFileSync(...args) {+ if (failWrite && String(args[0]).startsWith(file)) throw new Error('fixture write failure');+ return fs.writeFileSync(...args);+ } }, path, process, DATA_DIR: dir, PROFILE: options.profile || { apiHost: 'https://fixture.invalid' },+ normalizeTokenTimestamp: normalizeTimestamp, shouldRefreshAccessToken,+ todayStr: (d = new Date()) => d.toISOString().slice(0, 10),+ accountBackupFile: () => file,+ listAccounts: () => {+ const auth = JSON.parse(fs.readFileSync(file)).auth;+ return [{ uid: 'fixture', tokenExpiresAt: auth.expiresAt, lastRefreshTime: auth.lastRefreshTime }];+ },+ redactDiagnosticText: () => 'redacted', log() {},+ refreshAuthToken: async (auth, refreshOptions) => {+ requests++;+ await Promise.resolve();+ if (options.onRefresh) options.onRefresh(file);+ if (options.profile) return refreshAuthToken(auth, { ...refreshOptions, fetchImpl: async (url, init) => {+ assert.equal(url, options.profile.apiHost + '/v2/plugin/auth/token/refresh');+ assert.equal(init.headers['X-Refresh-Token'], 'old-refresh');+ return { ok: true, status: 200, json: async () => ({ code: 0, data: {+ accessToken: 'new-access', refreshToken: 'new-refresh', expiresIn: 3600,+ } }) };+ } });+ return { ok: true, auth: { ...auth, accessToken: 'new-access', refreshToken: 'new-refresh',+ lastRefreshTime: Date.now(), expiresAt: Date.now() + 28 * 86400000 } };+ },+ };+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ const start = source.indexOf('const backupAuthRuntimeCache = new Map()');+ const end = source.indexOf('/**\n * 打开账号面板时按日保活', start);+ vm.createContext(context);+ vm.runInContext(source.slice(start, end), context);+ let nativeStored;+ if (options.profile) {+ // Run the real native switch and persistence transaction against isolated+ // official-service storage. No inspector connection or user account I/O.+ const service = {+ currentSession: { account: { uid: 'other' }, auth: { accessToken: 'other-access', domain: options.profile.apiHost } },+ async storeSession(session) { nativeStored = structuredClone(session); },+ _onDidChangeSession: { fire() {} }, scheduleRefresh() {},+ };+ Object.assign(context, {+ URL, Buffer, ACTIVE_PROFILE: options.profile, DYNAMIC_AUTH_DISCOVERY: false,+ AUTH_FILE: path.join(dir, 'native-current.info'),+ codeBuddyNative: {+ read: async () => structuredClone(service.currentSession),+ replace: session => replaceNativeSession.call(service, session),+ },+ backupCurrent() {+ const current = JSON.parse(fs.readFileSync(context.AUTH_FILE, 'utf8'));+ fs.copyFileSync(context.AUTH_FILE, path.join(dir, 'accounts', current.account.uid + '.info'));+ },+ });+ const lib = fs.readFileSync(path.join(__dirname, '../scripts/lib.js'), 'utf8');+ vm.runInContext(lib.slice(lib.indexOf('function normalizeAuthDomain('), lib.indexOf('/**\n * Normalize a user-supplied account JSON')), context);+ vm.runInContext(source.slice(source.indexOf('let nativeAuthSyncTail = Promise.resolve();'), source.indexOf('\nfunction scheduleBackup(')), context);+ }+ return {+ dir, file, refresh: context.refreshAccountBackupToken,+ list: context.listAccountsWithRuntimeTokenCache,+ read: () => compat.wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(file))),+ restart() { vm.runInContext('backupAuthRuntimeCache.clear(); tokenRefreshState = null;', context); },+ counts: () => requests,+ failWrite(value) { failWrite = value; },+ signature: context.accountBackupSignature,+ nativeSwitch: uid => context.switchAccountForProfile(uid),+ nativeStored: () => nativeStored,+ };+}++test('encrypted refresh survives cache loss and same-day daily keepalive reads the saved credentials', async t => {+ const h = daemonHarness(t);+ const result = await h.refresh('fixture', { dailyKeepalive: true, force: true });+ assert.equal(result.persisted, true);+ assert.equal(h.read().auth.accessToken, 'new-access');+ assert.equal(fs.readFileSync(h.file, 'utf8').includes('new-access'), false);+ if (process.platform !== 'win32') assert.equal(fs.statSync(h.file).mode & 0o777, 0o600);+ h.restart();+ const next = await h.refresh('fixture', { dailyKeepalive: true, force: true });+ assert.equal(next.skipped, true);+ assert.equal(next.root.auth.refreshToken, 'new-refresh');+ assert.equal(h.counts(), 1);+});++for (const profileId of ['codebuddy-cn', 'codebuddy-intl']) {+ for (const plaintext of [true, false]) {+ test(`${profileId} ${plaintext ? 'plaintext' : 'encrypted'} refresh survives cache loss and reaches native switch storage`, async t => {+ const h = daemonHarness(t, { profile: PROFILES[profileId], plaintext });+ assert.equal((await h.refresh('fixture', { force: true })).persisted, true);+ h.restart();+ const result = await h.nativeSwitch('fixture');+ assert.equal(result.nativeSwitched, true);+ assert.equal(h.nativeStored().auth.accessToken, 'new-access');+ assert.equal(h.nativeStored().auth.refreshToken, 'new-refresh');+ assert.equal(h.nativeStored().auth.domain, PROFILES[profileId].apiHost);+ assert.equal(h.read().auth.refreshToken, 'new-refresh');+ assert.equal(h.counts(), 1);+ });+ }+}++test('legacy public refresh dates never suppress refresh or replace durable token expiry', async t => {+ const h = daemonHarness(t);+ const storedExpiry = h.read().auth.expiresAt;+ fs.writeFileSync(path.join(h.dir, 'token-refresh-state.json'), JSON.stringify({ accounts: { fixture: {+ signature: h.signature(h.file), lastRefreshTime: Date.now(), expiresAt: Date.now() + 28 * 86400000,+ } } }));+ assert.equal(h.list()[0].tokenExpiresAt, storedExpiry);+ assert.equal((await h.refresh('fixture', { dailyKeepalive: true, force: true })).persisted, true);+ assert.equal(h.counts(), 1);+});++test('overlapping panel and other refresh callers exchange a refresh token only once', async t => {+ const h = daemonHarness(t);+ await Promise.all([h.refresh('fixture', { force: true }), h.refresh('fixture', { dailyKeepalive: true })]);+ assert.equal(h.counts(), 1);+ assert.equal(h.read().auth.refreshToken, 'new-refresh');+});++test('failed persistence retains refreshed credentials and retries saving before another exchange', async t => {+ const h = daemonHarness(t);+ const original = fs.readFileSync(h.file, 'utf8');+ h.failWrite(true);+ const failed = await h.refresh('fixture', { force: true });+ assert.equal(failed.persisted, false);+ assert.ok(failed.error);+ assert.equal(fs.readFileSync(h.file, 'utf8'), original);+ h.failWrite(false);+ const retried = await h.refresh('fixture', { dailyKeepalive: true });+ assert.equal(retried.persisted, true);+ assert.equal(h.read().auth.refreshToken, 'new-refresh');+ assert.equal(h.counts(), 1);+});++test('a concurrent official login backup is preserved when refresh completes', async t => {+ let replacement;+ const h = daemonHarness(t, { onRefresh(file) {+ replacement = JSON.stringify({ account: { uid: 'fixture' }, auth: { accessToken: 'official-login', refreshToken: 'official-refresh' } });+ fs.writeFileSync(file, replacement);+ } });+ const result = await h.refresh('fixture', { force: true });+ assert.ok(result.error);+ assert.equal(fs.readFileSync(h.file, 'utf8'), replacement);+});++test('legacy plaintext backups still persist refreshed credentials', async t => {+ const h = daemonHarness(t, { plaintext: true });+ assert.equal((await h.refresh('fixture', { force: true })).persisted, true);+ assert.equal(h.read().auth.refreshToken, 'new-refresh');+});++test('unusable encryption templates stop before requesting a rotating refresh', async t => {+ const h = daemonHarness(t);+ const stored = JSON.parse(fs.readFileSync(h.file));+ const env = JSON.parse(Buffer.from(stored.auth.refreshToken.envelope, 'base64'));+ env.keyId = 'tampered-key';+ stored.auth.refreshToken.envelope = Buffer.from(JSON.stringify(env)).toString('base64');+ const source = JSON.stringify(stored);+ fs.writeFileSync(h.file, source);+ assert.ok((await h.refresh('fixture', { force: true })).error);+ assert.equal(h.counts(), 0);+ assert.equal(fs.readFileSync(h.file, 'utf8'), source);+});diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 1293fa9..bcaf585 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -963,7 +963,8 @@ test('session ranges use last-modified time and preserve standard WorkBuddy workconst inject = read('inject.js');assert.match(daemon, /Number\(row\.last_activity_at \?\? row\.updated_at \?\? row\.created_at\) >= rangeMs/);assert.match(daemon, /ORDER BY COALESCE\(last_activity_at, updated_at, created_at\) DESC/);- assert.match(inject, /sessionsState\.list = \(\(d && d\.sessions\) \|\| \[\]\);/);+ assert.match(inject, /var nextList = \(d && d\.sessions\) \|\| \[\];/);+ assert.match(inject, /sessionsState\.list = nextList;/);assert.match(inject, /if \(isTaskSessionRecordUI\(s\)\) \{ tasks\.push\(s\); return; \}/);assert.match(inject, /fmtHumanTime\(s\.last_activity_at \|\| s\.updated_at \|\| s\.created_at\)/);});@@ -996,9 +997,9 @@ test('account cards keep the compact three-row layout', () => {// 账号页暂不展示“发起独立会话保持活跃”入口;daemon 接口保留供内部/后续流程使用。assert.doesNotMatch(script, /wbs-growth-activate/);assert.doesNotMatch(script, /api\('\/api\/growth\/activate'/);- assert.match(script, /expired \|\| a\.authValid === false \? '' : '<button class="wbs-icon-btn wbs-acc-switch"/);+ assert.match(script, /\(a\.authValid === false \? '' : '<button class="wbs-icon-btn wbs-acc-switch"/);assert.match(script, /var invalidAuthBadge = a\.authValid === false/);- assert.match(script, /switchBtn\.style\.display = hidden \|\| account\.creditExpired \|\| account\.authValid === false \? 'none' : ''/);+ assert.match(script, /switchBtn\.style\.display = account\.authValid === false \? 'none' : ''/);assert.match(script, /height:5px;min-height:5px/);assert.match(script, /\.wbs-credit-segment:first-child\{border-radius:3px 0 0 3px\}/);assert.match(script, /\.wbs-credit-segment:last-child\{border-radius:0 3px 3px 0\}/);diff --git a/test/workbuddy-launch-env.test.js b/test/workbuddy-launch-env.test.jsindex 46481e7..2ecea9b 100644--- a/test/workbuddy-launch-env.test.js+++ b/test/workbuddy-launch-env.test.js@@ -8,6 +8,7 @@ const vm = require('node:vm');const { EventEmitter } = require('node:events');const { getClientLaunchArgs } = require('../scripts/client-launch-settings.js');const { getWorkBuddyLaunchEnv } = require('../scripts/workbuddy-launch-env.js');+const { PROFILES } = require('../scripts/profiles.js');function fixture(t) {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-update-424-'));@@ -41,6 +42,32 @@ function launchContext(profile, dataDir, env, spawn) {return ctx;}+for (const id of ['workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl']) {+ test(`#468 ${id}: Windows GUI startup and relaunch never request a hidden main window`, async t => {+ const dir = fixture(t);+ const launches = [];+ const profile = { ...PROFILES[id], dataRoot: path.join(dir, id), cdp: { ...PROFILES[id].cdp } };+ const ctx = launchContext(profile, dir, {}, (command, args, options) => launches.push({ command, args, options }));+ for (const mode of ['environment', 'argument']) {+ profile.cdp.mode = mode;+ ctx.launchWorkBuddy('C:\\WorkBuddy.exe');+ await ctx.relaunchWorkBuddy();+ assert.equal(launches.length, 2);+ for (const launch of launches.splice(0)) {+ assert.equal(launch.options.windowsHide, false, 'GUI spawn must not inherit SW_HIDE');+ assert.equal(launch.options.detached, true);+ assert.equal(launch.options.stdio, 'ignore');+ if (mode === 'environment') {+ assert.equal(launch.options.env.WORKBUDDY_REMOTE_DEBUGGING_PORT, '9223');+ } else {+ assert.ok(launch.args.includes('--remote-debugging-port=9223'));+ if (profile.nativeDebugPort) assert.ok(launch.args.includes(`--inspect=127.0.0.1:${profile.nativeDebugPort}`));+ }+ }+ }+ });+}+// Replay the official updater's two independent inputs: an environment override// wins over the remembered endpoint, but startup restores installers from TEMP// before checking the feed (main/update-service{,.win32}.js in WorkBuddy).