Skip to content

WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。

fix: 修复账号切换与 Windows 启动问题

[email protected]91326ac2ee73
diff --git a/.gitignore b/.gitignore
index a3bf751..0af9da4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,3 +18,6 @@ scripts/picker-internal.js
# 工作区元数据(WorkBuddy 项目数据,不入库)
.workbuddy/
.workbuddy-ai/
+
+# 构建缓存(安装器临时产物)
+release/.cache/
diff --git a/release/macos/WorkDaddy-1.1.7.dmg b/release/macos/WorkDaddy-1.1.8.dmg
similarity index 73%
rename from release/macos/WorkDaddy-1.1.7.dmg
rename to release/macos/WorkDaddy-1.1.8.dmg
index d9ec896..53f8fec 100644
Binary files a/release/macos/WorkDaddy-1.1.7.dmg and b/release/macos/WorkDaddy-1.1.8.dmg differ
diff --git a/release/macos/WorkDaddy-AI-1.1.7.dmg b/release/macos/WorkDaddy-AI-1.1.8.dmg
similarity index 73%
rename from release/macos/WorkDaddy-AI-1.1.7.dmg
rename to release/macos/WorkDaddy-AI-1.1.8.dmg
index b5b692d..7f92570 100644
Binary files a/release/macos/WorkDaddy-AI-1.1.7.dmg and b/release/macos/WorkDaddy-AI-1.1.8.dmg differ
diff --git a/release/windows/WorkDaddy-Setup-1.1.7.exe b/release/windows/WorkDaddy-AI-Setup-1.1.8.exe
similarity index 72%
rename from release/windows/WorkDaddy-Setup-1.1.7.exe
rename to release/windows/WorkDaddy-AI-Setup-1.1.8.exe
index aee87e8..25fa456 100644
Binary files a/release/windows/WorkDaddy-Setup-1.1.7.exe and b/release/windows/WorkDaddy-AI-Setup-1.1.8.exe differ
diff --git a/release/windows/WorkDaddy-AI-Setup-1.1.7.exe b/release/windows/WorkDaddy-Setup-1.1.8.exe
similarity index 72%
rename from release/windows/WorkDaddy-AI-Setup-1.1.7.exe
rename to release/windows/WorkDaddy-Setup-1.1.8.exe
index a97aab3..3abdc4f 100644
Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.7.exe and b/release/windows/WorkDaddy-Setup-1.1.8.exe differ
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 3da4e97..07ebb5d 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -25,10 +25,11 @@ DMG_WINDOW_WIDTH=620
DMG_WINDOW_HEIGHT=400
DMG_ICON_SIZE=112
DMG_BACKGROUND_SVG="$DIR/scripts/assets/macos-dmg-background.svg"
+SKIP_FINDER="${WORKDADDY_SKIP_FINDER:-}"
PROFILE="${WORKDADDY_BUILD_PROFILE:-}"
if [ -z "$PROFILE" ]; then
for profile in workbuddy-cn workbuddy-ai; do
- WORKDADDY_BUILD_PROFILE="$profile" bash "$0"
+ WORKDADDY_BUILD_PROFILE="$profile" bash "$0" || exit $?
done
exit 0
fi
@@ -370,7 +371,7 @@ fi
VOLUME_NAME="$(basename "$MOUNT_DIR")"
# 无 GUI 会话(CI/Agent 沙箱)无法驱动 Finder 写 .DS_Store 布局:
# 设置 WORKDADDY_SKIP_FINDER=1 跳过布局步骤,产物为无 Finder 美化布局的标准 DMG。
-if [ -z "$WORKDADDY_SKIP_FINDER" ]; then
+if [ -z "$SKIP_FINDER" ]; then
sleep 2
osascript - "$VOLUME_NAME" "${PACKAGE_APP_NAME}.app" "$DMG_WINDOW_WIDTH" "$DMG_WINDOW_HEIGHT" "$DMG_ICON_SIZE" <<'APPLESCRIPT'
on run argv
@@ -428,7 +429,7 @@ end run
APPLESCRIPT
fi
-if [ -z "$WORKDADDY_SKIP_FINDER" ]; then
+if [ -z "$SKIP_FINDER" ]; then
sync
for _ in {1..20}; do
test -f "$MOUNT_DIR/.DS_Store" && break
diff --git a/scripts/daemon.js b/scripts/daemon.js
index fb64119..db633e1 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -259,8 +259,15 @@ const DATA_DIR = defaultDataDir();
// 1.1.34:签到前惰性刷新 access token,并按日使用 refresh token 保活所有备份账号。
// 1.1.35:认证解析优先官方固定 auth 文件(消除多 lastLogin 残留的切换歧义);积分接口
// 401 归类为「登录身份过期」并返回结构化 401;语言选择器移入「关于」页。
-const DAEMON_VERSION = '1.1.35';
-const DAEMON_BUILD_ID = 'release-1.1.35-20260903-auth-canonical-credits-401-i18n-about';
+// 1.1.37:修复 legacy 账号切换失败——无文件记录的旧账号无条件写回官方固定登录文件,
+// 固定文件名(workbuddy-desktop.info)跨认证通道可交替覆盖,个性化文件名保留通道校验。
+// 1.1.38:备份扫描禁止历史存档覆盖有效备份(s 身份过期事故根源);切换账号后自动打开
+// 目标账号中与当前会话同标题的复制会话(auto-focus)。
+// 1.1.39:账号脱敏状态按 profile 持久化;WorkDaddy 触发页面重载后在主执行上下文创建时提前注入。
+// 1.1.40:跨账号重载跟随新主 frame,并在会话自动复制占用事件循环前等待组件实际挂载。
+// 1.1.41:后台会话自动复制在文件边界让出 I/O;账号重载期间暂停复制,优先完成组件挂载。
+const DAEMON_VERSION = '1.1.41';
+const DAEMON_BUILD_ID = 'release-1.1.41-20260905-prioritize-switch-reload';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -1499,6 +1506,69 @@ let daemonLockPath = DAEMON_LOCK_FILE;
let lastInjectTs = 0;
let injectRetryTimer = null; // 被节流跳过的自动注入的兜底补种定时器
let manualInjectPromise = null; // launcher 超时重试时复用同一轮注入,避免并发清理/重挂载 renderer
+let pendingReloadInjection = null; // 仅对 WorkDaddy 主动触发的页面重载做一次主 frame 早期注入
+let mainFrameNavigationSerial = 0;
+let suppressPageLoadInjectionForNavigation = 0;
+
+function settlePendingReloadInjection(pending, mounted) {
+ if (!pending || pendingReloadInjection !== pending || pending.settled) return;
+ pending.settled = true;
+ if (pending.timer) clearTimeout(pending.timer);
+ pendingReloadInjection = null;
+ // 早期注入已挂载时,紧随其后的 loadEventFired 只做备份/主题恢复,不能再次销毁组件。
+ if (mounted && !pending.loadFired) {
+ suppressPageLoadInjectionForNavigation = pending.navigationSerial || mainFrameNavigationSerial;
+ }
+ pending.resolve(!!mounted);
+}
+
+function armPendingReloadInjection(frameId) {
+ if (pendingReloadInjection) settlePendingReloadInjection(pendingReloadInjection, false);
+ let resolveReady;
+ const ready = new Promise((resolve) => { resolveReady = resolve; });
+ const pending = {
+ frameId: frameId || null,
+ expiresAt: Date.now() + 5000,
+ injecting: false,
+ loadFired: false,
+ navigationSerial: mainFrameNavigationSerial,
+ attempts: 0,
+ settled: false,
+ resolve: resolveReady,
+ ready,
+ timer: null,
+ };
+ pending.timer = setTimeout(() => settlePendingReloadInjection(pending, false), 5000);
+ if (pending.timer.unref) pending.timer.unref();
+ pendingReloadInjection = pending;
+ return pending;
+}
+
+function runPendingReloadInjection(reason, executionContextId) {
+ const pending = pendingReloadInjection;
+ if (!pending || pending.injecting || pending.settled) return;
+ pending.injecting = true;
+ pending.attempts++;
+ injectWidget(reason, executionContextId)
+ .then((info) => {
+ if (pendingReloadInjection !== pending || pending.settled) return;
+ pending.injecting = false;
+ if (info && info.mounted) {
+ settlePendingReloadInjection(pending, true);
+ return;
+ }
+ if (pending.loadFired && pending.attempts < 3) {
+ setTimeout(() => runPendingReloadInjection('reload-page-load-retry'), 150);
+ }
+ })
+ .catch(() => {
+ if (pendingReloadInjection !== pending || pending.settled) return;
+ pending.injecting = false;
+ if (pending.loadFired && pending.attempts < 3) {
+ setTimeout(() => runPendingReloadInjection('reload-page-load-retry'), 150);
+ }
+ });
+}
async function findCdpEndpoint() {
// profile 已由启动器绑定时不能扫描其他产品的端口;CodeBuddy Agents/Editor
@@ -1697,6 +1767,7 @@ async function connectCdp() {
ws.onclose = () => {
cdp.connected = false;
cdp.ws = null;
+ if (pendingReloadInjection) settlePendingReloadInjection(pendingReloadInjection, false);
log('[cdp] 连接已断开,5 秒后重连');
};
});
@@ -1732,16 +1803,48 @@ function onCdpEvent(method, params) {
log('[renderer:exception] ' + redactDiagnosticText(desc || d.text || ''));
break;
}
- case 'Page.loadEventFired':
+ case 'Runtime.executionContextCreated': {
+ const context = params.context || {};
+ const auxData = context.auxData || {};
+ if (!pendingReloadInjection || Date.now() > pendingReloadInjection.expiresAt) {
+ if (pendingReloadInjection) settlePendingReloadInjection(pendingReloadInjection, false);
+ break;
+ }
+ if (auxData.isDefault === true && auxData.frameId === pendingReloadInjection.frameId) {
+ runPendingReloadInjection('reload-context', context.id);
+ }
+ break;
+ }
+ case 'Page.loadEventFired': {
scheduleBackup('cdp-page-load');
- // 页面刷新/导航后重新注入组件(组件自带幂等清理,可安全重新注入最新代码)
- injectWidget('page-load').catch(() => {});
+ if (pendingReloadInjection) {
+ pendingReloadInjection.loadFired = true;
+ runPendingReloadInjection('reload-page-load');
+ } else if (suppressPageLoadInjectionForNavigation === mainFrameNavigationSerial) {
+ suppressPageLoadInjectionForNavigation = 0;
+ log('[cdp] 页面加载完成,早期注入已挂载,跳过重复注入');
+ } else {
+ suppressPageLoadInjectionForNavigation = 0;
+ // 非 WorkDaddy 触发的刷新仍在页面加载完成后恢复组件。
+ injectWidget('page-load').catch(() => {});
+ }
// 页面刷新后 WorkBuddy 回到官方浅色,重新应用已保存主题(WorkDaddy=深色 / 默认=浅色)
restoreSavedTheme().catch((e) => log(`[theme] 页面刷新恢复主题失败: ${e.message}`));
break;
- case 'Page.frameNavigated':
+ }
+ case 'Page.frameNavigated': {
+ const frame = params.frame || {};
+ // 跨账号刷新会换掉主 frame id;必须在默认 execution context 创建前跟随新 id。
+ if (!frame.parentId && frame.id) {
+ mainFrameNavigationSerial++;
+ if (pendingReloadInjection) {
+ pendingReloadInjection.frameId = frame.id;
+ pendingReloadInjection.navigationSerial = mainFrameNavigationSerial;
+ }
+ }
scheduleBackup('cdp-navigate');
break;
+ }
default:
break;
}
@@ -1762,7 +1865,121 @@ async function cdpLoop() {
async function reloadWorkBuddyPage() {
if (!cdp.connected) throw new Error('CDP 未连接,无法自动刷新窗口');
- await cdpSend('Page.reload', { ignoreCache: false });
+ let frameId = null;
+ try {
+ const tree = await cdpSend('Page.getFrameTree');
+ frameId = tree && tree.frameTree && tree.frameTree.frame && tree.frameTree.frame.id;
+ } catch (error) {
+ log(`[cdp] 获取主页面 frame 失败,将在页面加载完成后注入: ${error.message}`);
+ }
+ const pending = armPendingReloadInjection(frameId);
+ try {
+ await cdpSend('Page.reload', { ignoreCache: false });
+ const mounted = await pending.ready;
+ if (!mounted) log('[cdp] 页面重载后组件未在 5 秒内确认挂载,继续后台流程');
+ } catch (error) {
+ settlePendingReloadInjection(pending, false);
+ throw error;
+ }
+}
+
+// 切换账号后自动打开目标账号中「与切换前当前会话同标题」的会话:
+// 自动复制会话会为目标账号创建同标题会话,刷新后轮询官方会话列表:
+// 标题精确匹配叶子 -> 定位 .conversation-item 行 -> 若已选中(_selected_)则完成,
+// 否则点击该行等待下轮确认。列表是虚拟滚动(只渲染可视行),按步进滚动扫描,
+// 并自动展开折叠的分组;最长约 26s,找不到则静默放弃。
+function autoFocusSessionByTitle(sourceTitle, logFn) {
+ const target = String(sourceTitle || '').trim();
+ if (!target) return;
+ const logger = typeof logFn === 'function' ? logFn : () => {};
+ let attempts = 0;
+ let scrollPhase = 0; // 0=顶部初始, 1=向下扫描, 2=向上回扫
+ let scrollTop = 0;
+ const SCROLL_STEP = 480;
+ const timer = setInterval(async () => {
+ attempts++;
+ try {
+ if (!cdp.connected) throw new Error('CDP 未连接');
+ // 1) 设置滚动位置(虚拟列表只渲染可视行)
+ const scrollExpr =
+ '(function(){var c=document.querySelector(".conversation-list-content");' +
+ 'if(!c) return {ok:false, max:0};' +
+ 'c.scrollTop=' + String(scrollTop) + ';' +
+ 'return {ok:true, max:Math.max(0,c.scrollHeight-c.clientHeight)};})()';
+ const sr = await cdpSend('Runtime.evaluate', { expression: scrollExpr, returnByValue: true });
+ const scrollInfo = sr && sr.result && sr.result.value;
+ // 2) 扫描匹配行:找到即返回 hit=已选中,pending=已点击待确认,miss=未渲染
+ const findExpr =
+ '(function(){' +
+ 'var wanted = ' + JSON.stringify(target) + ';' +
+ 'var list = document.querySelector(".conversation-list");' +
+ 'if (!list) return { miss: true };' +
+ 'var leaves = [];' +
+ 'var all = list.querySelectorAll("*");' +
+ 'for (var i = 0; i < all.length; i++) {' +
+ ' var el = all[i];' +
+ ' if (el.children.length === 0 && (el.textContent || "").trim() === wanted) leaves.push(el);' +
+ '}' +
+ 'if (!leaves.length) {' +
+ ' var headers = list.querySelectorAll(".collapsible-section-header");' +
+ ' for (var k = 0; k < headers.length; k++) {' +
+ ' var hdr = headers[k];' +
+ ' if (hdr.className.indexOf("expanded") === -1) hdr.click();' +
+ ' }' +
+ ' return { miss: true };' +
+ '}' +
+ 'for (var j = 0; j < leaves.length; j++) {' +
+ ' var row = leaves[j];' +
+ ' for (var d = 0; d < 8 && row && row.parentElement; d++) {' +
+ ' var rc = row.classList ? row.className : "";' +
+ ' if (rc.indexOf("conversation-item") !== -1 || rc.indexOf("_card_") !== -1) break;' +
+ ' row = row.parentElement;' +
+ ' }' +
+ ' var rcls = row && row.classList ? row.className : "";' +
+ ' if (!row || row === list || (rcls.indexOf("conversation-item") === -1 && rcls.indexOf("_card_") === -1)) continue;' +
+ ' var rect = row.getBoundingClientRect ? row.getBoundingClientRect() : null;' +
+ ' if (!rect || rect.width === 0 || rect.height === 0) continue;' +
+ ' if (rcls.indexOf("_selected_") !== -1 || rcls.indexOf("selected") !== -1) {' +
+ ' return { hit: true };' +
+ ' }' +
+ ' row.click();' +
+ ' return { pending: true };' +
+ '}' +
+ 'return { miss: true };' +
+ '})()';
+ const fr = await cdpSend('Runtime.evaluate', { expression: findExpr, returnByValue: true });
+ const out = fr && fr.result && fr.result.value;
+ if (out && out.hit) {
+ clearInterval(timer);
+ logger('[auto-focus] 已自动打开目标账号会话「' + target + '」');
+ return;
+ }
+ if (out && out.pending) {
+ // 已点击,下轮确认选中态;本轮不推进滚动
+ if (attempts >= 30) {
+ clearInterval(timer);
+ logger('[auto-focus] 已点击目标会话「' + target + '」,未确认选中(放弃继续等待)');
+ }
+ return;
+ }
+ // 3) 未渲染:推进滚动扫描
+ const max = scrollInfo && scrollInfo.max ? scrollInfo.max : 0;
+ if (scrollPhase === 0) { scrollPhase = 1; scrollTop = 0; }
+ else if (scrollPhase === 1) {
+ scrollTop += SCROLL_STEP;
+ if (scrollTop > max + SCROLL_STEP) { scrollPhase = 2; scrollTop = max; }
+ } else {
+ scrollTop -= SCROLL_STEP;
+ if (scrollTop <= -SCROLL_STEP) { scrollPhase = 1; scrollTop = 0; }
+ }
+ } catch (_) {
+ /* 页面加载中或 CDP 抖动,下一轮再试 */
+ }
+ if (attempts >= 30) {
+ clearInterval(timer);
+ logger('[auto-focus] 未找到目标会话「' + target + '」(复制未完成或标题不一致)');
+ }
+ }, 800);
}
const WORKBUDDY_TARGET = IS_WIN ? null : readWorkBuddyTarget({ dataDir: DATA_DIR, profileId: PROFILE.id });
@@ -2441,7 +2658,7 @@ async function claimDailyForAll() {
}
/** 通过 CDP 把右下角组件注入到 WorkBuddy 渲染进程(幂等,可反复调用) */
-function injectWidget(reason) {
+function injectWidget(reason, executionContextId) {
if (!cdp.connected) {
return Promise.reject(new Error('CDP 未连接,无法注入组件'));
}
@@ -2459,7 +2676,7 @@ function injectWidget(reason) {
// 否则 WorkBuddy 重启后仅有的注入机会会被节流吞掉(多台机器 FAB 缺失的根因:
// launcher 检测到 CDP 就调用 manual,但被 1.5s 节流跳过,页面又不会再触发补种)。
var now = Date.now();
- if (reason !== 'manual' && now - lastInjectTs < 1000) {
+ if (reason !== 'manual' && !String(reason).startsWith('reload-') && now - lastInjectTs < 1000) {
log(`[cdp] 注入节流跳过 (${reason})`);
// 兜底:被跳过的自动注入可能是页面刚就绪的唯一一次机会,1.5s 后补种一次(脚本幂等,安全)
if (!injectRetryTimer) {
@@ -2470,38 +2687,15 @@ function injectWidget(reason) {
}
return Promise.resolve();
}
+ if (injectRetryTimer) clearTimeout(injectRetryTimer);
injectRetryTimer = null;
lastInjectTs = now;
let script;
try {
- const compatScript = fs.readFileSync(path.join(__dirname, 'workbuddy-compat.js'), 'utf8');
- let injectScript = fs.readFileSync(path.join(__dirname, 'inject.js'), 'utf8');
- // 内部调试模块(元素检查/DevTools):picker-internal.js 存在才注入(git 不跟踪,
- // 他人环境无此文件 → 隐藏入口的拾取按钮点击会报错,符合预期,不影响面板其他功能)。
- // 注入位置:放进 build() 函数体末尾(与面板共享闭包作用域:root/toast/esc 等),
- // 这样拾取实现与原版稳定版 debug 模块完全同域,不被 IIFE 边界隔开。
- const pickerPath = path.join(__dirname, 'picker-internal.js');
- if (fs.existsSync(pickerPath)) {
- const pickerCode = fs.readFileSync(pickerPath, 'utf8');
- const anchor = 'return { destroy: lifecycle.destroy, alive: lifecycle.alive };';
- if (!injectScript.includes(anchor)) {
- return Promise.reject(new Error('picker-internal.js 注入锚点不存在'));
- }
- injectScript = injectScript.replace(anchor, pickerCode + '\n' + anchor);
- }
- script = compatScript + '\n' + injectScript;
+ script = buildInjectScript();
} catch (e) {
return Promise.reject(new Error('读取注入脚本失败: ' + e.message));
}
- // 组件内通过 fetch 调用本机 API,注入时写入实际端口
- script = script.replace(/__WBS_API__/g, `http://${HOST}:${ACTUAL_PORT}`);
- script = script.replace(/__WBS_VERSION__/g, DAEMON_VERSION);
- // 注入本地 API 能力凭证;旧版面板不会携带该 header,但新版 daemon 会在启动时重新注入新版面板。
- script = script.replace(/__WBS_API_TOKEN__/g, API_TOKEN);
- script = script.replace(/__WBS_DIAGNOSTICS_ENABLED__/g, diagnosticsEnabled() ? 'true' : 'false');
- script = script.replace(/__WBS_PROFILE__/g, PROFILE.id);
- script = script.replace(/__WBS_CAPS__/g, JSON.stringify(PROFILE.capabilities));
- script = script.replace(/__WBS_PLATFORM__/g, JSON.stringify(process.platform));
updateDebug('inject-version', { reason, injectedVersion: DAEMON_VERSION, profile: PROFILE.id });
// 注入策略:不使用 addScriptToEvaluateOnNewDocument(它会在浏览器里持久化注册,
// 多次重启会叠加旧版本;旧注册先执行并占住 window.__wbsWidget 守卫,导致新代码被拦截)。
@@ -2510,12 +2704,14 @@ function injectWidget(reason) {
log(`[cdp] 注入右下角组件 (${reason})`);
const cleanupExpr =
'try{if(window.__wbsWidget&&typeof window.__wbsWidget.destroy==="function"){window.__wbsWidget.destroy();}}catch(e){}';
- return cdpSend('Runtime.evaluate', { expression: cleanupExpr, returnByValue: false })
+ const runtimeContext = executionContextId == null ? {} : { contextId: executionContextId };
+ return cdpSend('Runtime.evaluate', { expression: cleanupExpr, returnByValue: false, ...runtimeContext })
.catch(() => {})
.then(() =>
cdpSend('Runtime.evaluate', {
expression: script,
returnByValue: false,
+ ...runtimeContext,
})
)
// 注入脚本若在页面抛错,CDP 协议不报错(无 protocol error),会被误判为"已注入";
@@ -2533,13 +2729,14 @@ function injectWidget(reason) {
// Runtime.evaluate 本身成功不代表脚本完成挂载;回读 DOM/全局守卫,区分“协议成功”与“用户可见”。
// 手动注入是 launcher 的成功判据,给页面首屏最多约 1.3 秒完成挂载,避免把正常加载延迟误报为失败。
let state = null;
- const checks = reason === 'manual' ? 5 : 1;
+ const checks = reason === 'manual' || String(reason).startsWith('reload-') ? 5 : 1;
for (let attempt = 0; attempt < checks; attempt++) {
await new Promise((resolve) => setTimeout(resolve, attempt === 0 ? 120 : 300));
try {
const check = await cdpSend('Runtime.evaluate', {
expression: '({ url: location.href, readyState: document.readyState, body: !!document.body, root: !!document.querySelector(".wbs-root"), widget: !!window.__wbsWidget })',
returnByValue: true,
+ ...runtimeContext,
});
state = check && check.result && check.result.value;
} catch (e) {
@@ -2551,7 +2748,7 @@ function injectWidget(reason) {
log(`[cdp] 注入后未检测到组件(${reason}): ${JSON.stringify(state || {})}`);
writeDiagnosticsSnapshot('inject-not-mounted').catch(() => {});
// 页面首屏尚未完成时偶发 body 已存在但应用仍在替换根节点,延迟补试一次。
- if (!String(reason).endsWith('-retry')) {
+ if (!String(reason).endsWith('-retry') && !String(reason).startsWith('reload-')) {
setTimeout(() => { if (cdp.connected) injectWidget(String(reason) + '-retry').catch(() => {}); }, 700);
}
if (reason === 'manual') throw new Error('注入后未检测到 WorkDaddy 组件(请检查 WorkBuddy 页面是否正常加载)');
@@ -2567,6 +2764,34 @@ function injectWidget(reason) {
});
}
+function buildInjectScript() {
+ const compatScript = fs.readFileSync(path.join(__dirname, 'workbuddy-compat.js'), 'utf8');
+ let injectScript = fs.readFileSync(path.join(__dirname, 'inject.js'), 'utf8');
+ // 内部调试模块(元素检查/DevTools):picker-internal.js 存在才注入(git 不跟踪,
+ // 他人环境无此文件 → 隐藏入口的拾取按钮点击会报错,符合预期,不影响面板其他功能)。
+ // 注入位置:放进 build() 函数体末尾(与面板共享闭包作用域:root/toast/esc 等),
+ // 这样拾取实现与原版稳定版 debug 模块完全同域,不被 IIFE 边界隔开。
+ const pickerPath = path.join(__dirname, 'picker-internal.js');
+ if (fs.existsSync(pickerPath)) {
+ const pickerCode = fs.readFileSync(pickerPath, 'utf8');
+ const anchor = 'return { destroy: lifecycle.destroy, alive: lifecycle.alive };';
+ if (!injectScript.includes(anchor)) {
+ throw new Error('picker-internal.js 注入锚点不存在');
+ }
+ injectScript = injectScript.replace(anchor, pickerCode + '\n' + anchor);
+ }
+ // 组件内通过 fetch 调用本机 API,注入时写入实际端口
+ return (compatScript + '\n' + injectScript)
+ .replace(/__WBS_API__/g, `http://${HOST}:${ACTUAL_PORT}`)
+ .replace(/__WBS_VERSION__/g, DAEMON_VERSION)
+ // 注入本地 API 能力凭证;旧版面板不会携带该 header,但新版 daemon 会在启动时重新注入新版面板。
+ .replace(/__WBS_API_TOKEN__/g, API_TOKEN)
+ .replace(/__WBS_DIAGNOSTICS_ENABLED__/g, diagnosticsEnabled() ? 'true' : 'false')
+ .replace(/__WBS_PROFILE__/g, PROFILE.id)
+ .replace(/__WBS_CAPS__/g, JSON.stringify(PROFILE.capabilities))
+ .replace(/__WBS_PLATFORM__/g, JSON.stringify(process.platform));
+}
+
function injectWidgetManual() {
if (manualInjectPromise) return manualInjectPromise;
manualInjectPromise = injectWidget('manual').finally(() => {
@@ -2787,10 +3012,12 @@ function sessionRangeMs(range) {
// 复制会话的消息文件:projects/<项目>/<id>.jsonl + <id>/、workspace/sessions/<id>/、
// tasks/<id>/、file-history/<id>/、artifact-index/<id>.json(全部以新 id 命名复制)
-function copySessionFiles(wbHome, oldId, newId) {
+// 异步实现:切号复制大批会话时,同步 cpSync 会阻塞主线程几十秒,把注入定时器、
+// 面板响应全部饿死(切号后 FAB 迟迟不出现的根因之一)。
+async function copySessionFiles(wbHome, oldId, newId) {
const fsMod = fs;
const result = { copied: 0, failed: 0 };
- const copyOne = (from, to) => {
+ const copyOne = async (from, to) => {
try {
if (!fsMod.existsSync(from)) return;
const fromResolved = path.resolve(from);
@@ -2802,7 +3029,7 @@ function copySessionFiles(wbHome, oldId, newId) {
return;
}
fsMod.mkdirSync(path.dirname(to), { recursive: true });
- fsMod.cpSync(from, to, { recursive: true, force: true });
+ await fsMod.promises.cp(from, to, { recursive: true, force: true });
result.copied++;
} catch (e) {
result.failed++;
@@ -2817,19 +3044,19 @@ function copySessionFiles(wbHome, oldId, newId) {
for (const pj of projs) {
const pjPath = path.join(projDir, pj);
if (!fsMod.statSync(pjPath).isDirectory()) continue;
- copyOne(path.join(pjPath, oldId + '.jsonl'), path.join(pjPath, newId + '.jsonl'));
- copyOne(path.join(pjPath, oldId), path.join(pjPath, newId));
+ await copyOne(path.join(pjPath, oldId + '.jsonl'), path.join(pjPath, newId + '.jsonl'));
+ await copyOne(path.join(pjPath, oldId), path.join(pjPath, newId));
}
}
} catch (_) {}
// 2) workspace/sessions/<id>/
- copyOne(path.join(wbHome, 'workspace', 'sessions', oldId), path.join(wbHome, 'workspace', 'sessions', newId));
+ await copyOne(path.join(wbHome, 'workspace', 'sessions', oldId), path.join(wbHome, 'workspace', 'sessions', newId));
// 3) tasks/<id>/
- copyOne(path.join(wbHome, 'tasks', oldId), path.join(wbHome, 'tasks', newId));
+ await copyOne(path.join(wbHome, 'tasks', oldId), path.join(wbHome, 'tasks', newId));
// 4) file-history/<id>/
- copyOne(path.join(wbHome, 'file-history', oldId), path.join(wbHome, 'file-history', newId));
+ await copyOne(path.join(wbHome, 'file-history', oldId), path.join(wbHome, 'file-history', newId));
// 5) artifact-index/<id>.json
- copyOne(path.join(wbHome, 'artifact-index', oldId + '.json'), path.join(wbHome, 'artifact-index', newId + '.json'));
+ await copyOne(path.join(wbHome, 'artifact-index', oldId + '.json'), path.join(wbHome, 'artifact-index', newId + '.json'));
log('[sessions-copy] 已复制消息文件 ' + oldId + ' -> ' + newId);
return result;
}
@@ -2871,12 +3098,21 @@ function sessionContentMtime(wbHome, sessionId) {
// Reconcile every live member of a shared lineage. A switch can arrive after
// either account has received new messages, so the active account is not a
// reliable source of truth; choose the freshest on-disk snapshot first.
+async function yieldAutoCopyToRenderer() {
+ await new Promise((resolve) => setImmediate(resolve));
+ const reloadPriority = rendererReloadPriorityPromise;
+ if (reloadPriority) await reloadPriority;
+ const pending = pendingReloadInjection;
+ if (pending && !pending.settled) await pending.ready;
+}
+
async function syncAutoCopyLineage(lineageId, targetUid) {
if (!lineageId || PROFILE.kind !== 'workbuddy') return { members: 0, synced: 0, failedFiles: 0, targetIds: [], targetPresent: false };
const records = getAutoCopySessionMemberRecords(DATA_DIR, lineageId);
if (!records.length) return { members: 0, synced: 0, failedFiles: 0, targetIds: [], targetPresent: false };
const live = [];
for (const member of records) {
+ await yieldAutoCopyToRenderer();
const rows = await sqliteQuery(
'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id = ? AND user_id = ? AND deleted_at IS NULL LIMIT 1;',
[member.id, member.uid]
@@ -2898,7 +3134,8 @@ async function syncAutoCopyLineage(lineageId, targetUid) {
let failedFiles = 0;
for (const target of live) {
if (target.id === latest.id) continue;
- const files = copySessionFiles(PROFILE.dataRoot, latest.id, target.id);
+ await yieldAutoCopyToRenderer();
+ const files = await copySessionFiles(PROFILE.dataRoot, latest.id, target.id);
synced++;
failedFiles += files.failed;
try {
@@ -3137,7 +3374,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
[mapping.targetId]
);
if (existing.length && String(existing[0].user_id || '') === String(targetUid)) {
- const files = copySessionFiles(wbHome, src.id, mapping.targetId);
+ const files = await copySessionFiles(wbHome, src.id, mapping.targetId);
addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, mapping.targetId);
setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
targetId: mapping.targetId,
@@ -3176,7 +3413,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
});
if (candidates.length) {
const canonicalId = candidates[0].id;
- const files = copySessionFiles(wbHome, src.id, canonicalId);
+ const files = await copySessionFiles(wbHome, src.id, canonicalId);
addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, canonicalId);
setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
targetId: canonicalId,
@@ -3190,7 +3427,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
const newId = crypto.randomUUID();
await insertCopiedSession(src, targetUid, newId);
- const files = copySessionFiles(wbHome, src.id, newId);
+ const files = await copySessionFiles(wbHome, src.id, newId);
if (lineageId) {
addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, newId);
setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
@@ -3244,6 +3481,24 @@ async function buildAutoCopyPlan(sourceUid, targetUid) {
const autoCopyJobs = new Map();
const autoCopyQueue = [];
let autoCopyWorkerRunning = false;
+const rendererReloadPriorityTokens = new Set();
+let rendererReloadPriorityPromise = null;
+let resolveRendererReloadPriority = null;
+
+function beginRendererReloadPriority() {
+ const token = {};
+ if (!rendererReloadPriorityTokens.size) {
+ rendererReloadPriorityPromise = new Promise((resolve) => { resolveRendererReloadPriority = resolve; });
+ }
+ rendererReloadPriorityTokens.add(token);
+ return () => {
+ if (!rendererReloadPriorityTokens.delete(token) || rendererReloadPriorityTokens.size) return;
+ const resolve = resolveRendererReloadPriority;
+ rendererReloadPriorityPromise = null;
+ resolveRendererReloadPriority = null;
+ if (resolve) resolve();
+ };
+}
function hasPendingAutoCopyTo(uid) {
const target = String(uid || '').trim();
@@ -3305,11 +3560,15 @@ function startAutoCopyJob(sourceUid, targetUid, plan) {
autoCopyJobs.set(id, job);
const run = async () => {
job.status = 'running';
+ // 账号切换响应、CDP 导航和注入事件必须先有机会完成;Node SQLite 与文件复制
+ // 的 Promise 可能同步结算,连续微任务会在 macOS 上长期饿死 I/O 事件。
+ await yieldAutoCopyToRenderer();
// A rapid switch chain may enqueue this job before the previous copy has
// created the target rows. Re-plan after the queue reaches this job.
job.plan = await buildAutoCopyPlan(sourceUid, targetUid);
job.total = job.plan.length;
for (const src of job.plan) {
+ await yieldAutoCopyToRenderer();
try {
let result;
if (src.lineageId) {
@@ -7224,21 +7483,45 @@ function handleApi(req, res) {
return readBody(req).then(async (body) => {
const uid = (body.uid || '').trim();
if (!uid) return json(res, 400, { ok: false, error: '缺少 uid' });
+ const releaseRendererReload = body.reload ? beginRendererReloadPriority() : null;
try {
- // 先记录源账号并规划自动复制内容;切换后异步执行,避免阻塞 WorkBuddy 刷新。
+ // 只记录源账号;自动复制队列会在 renderer 刷新并完成组件注入后重新规划。
+ // 不在这里预规划,否则大量会话的同步 SQLite/文件扫描会让切换界面长时间无响应。
const sourceUid = String((currentAccount() || {}).uid || '').trim();
- let autoCopyPlan = [];
- if (sourceUid && sourceUid !== uid) {
- try {
- autoCopyPlan = await buildAutoCopyPlan(sourceUid, uid);
- } catch (e) {
- log(`[sessions-auto-copy] 规划失败 ${sourceUid} -> ${uid}: ${e.message}`);
- }
- }
const acct = switchTo(DATA_DIR, uid, log);
const hint = '登录文件已切换,请重启 WorkBuddy 使新账号生效';
let reloaded = false;
if (body.reload) {
+ // 读取切换前当前会话标题:官方会话列表的选中行(.conversation-item 带 selected);
+// 刷新后用于在目标账号里自动打开对应的复制会话。读不到则跳过自动聚焦。
+ let sourceSessionTitle = '';
+ try {
+ if (cdp.connected) {
+ const titleExpr =
+ '(function(){' +
+ 'var list = document.querySelector(".conversation-list");' +
+ 'if (!list) return "";' +
+ 'var rows = list.querySelectorAll(".conversation-item");' +
+ 'for (var i = 0; i < rows.length; i++) {' +
+ ' var r = rows[i];' +
+ ' if ((r.className || "").indexOf("selected") === -1) continue;' +
+ ' var best = "";' +
+ ' var els = r.querySelectorAll("*");' +
+ ' for (var j = 0; j < els.length; j++) {' +
+ ' var el = els[j];' +
+ ' if (el.children.length === 0) {' +
+ ' var t = (el.textContent || "").trim();' +
+ ' if (t.length > best.length) best = t;' +
+ ' }' +
+ ' }' +
+ ' if (best) return best;' +
+ '}' +
+ 'return "";' +
+ '})()';
+ const t = await cdpSend('Runtime.evaluate', { expression: titleExpr, returnByValue: true });
+ sourceSessionTitle = String((t && t.result && t.result.value) || '').trim();
+ }
+ } catch (_) { /* 读不到就跳过自动聚焦会话 */ }
try {
await reloadWorkBuddyPage();
reloaded = true;
@@ -7247,6 +7530,9 @@ function handleApi(req, res) {
claimDailyForUid(uid)
.then((r) => log('[checkin] 切换后自动签到 ' + uid + ': ' + (r.ok ? '已领取' : '失败 ' + (r.reason || r.message))))
.catch((e) => log('[checkin] 切换后签到异常: ' + e.message));
+ if (sourceSessionTitle) {
+ autoFocusSessionByTitle(sourceSessionTitle, log);
+ }
} catch (e) {
log(`[switch] CDP 刷新失败: ${e.message}`);
}
@@ -7255,8 +7541,8 @@ function handleApi(req, res) {
// 任务规则通常能直接命中,所以旧逻辑只表现为“任务能复制、空间不复制”。
const sourceRules = sourceUid ? getAutoCopyRules(DATA_DIR, sourceUid) : { allSessions: false, sessionIds: [], workspaces: [] };
const hasSourceAutoCopyRules = !!(sourceRules.allSessions || sourceRules.sessionIds.length || sourceRules.workspaces.length);
- const autoCopyJob = (autoCopyPlan.length || hasSourceAutoCopyRules || hasPendingAutoCopyTo(sourceUid))
- ? startAutoCopyJob(sourceUid, uid, autoCopyPlan)
+ const autoCopyJob = (hasSourceAutoCopyRules || hasPendingAutoCopyTo(sourceUid))
+ ? startAutoCopyJob(sourceUid, uid, [])
: null;
return json(res, 200, {
ok: true,
@@ -7268,6 +7554,8 @@ function handleApi(req, res) {
});
} catch (e) {
return json(res, 500, { ok: false, error: e.message });
+ } finally {
+ if (releaseRendererReload) releaseRendererReload();
}
});
}
diff --git a/scripts/inject.js b/scripts/inject.js
index 47da05b..02316e7 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -550,11 +550,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// User-facing strings are translated at the injected root so dynamically-built
// panes and toasts follow the same language without touching WorkBuddy's DOM.
var WBS_LANGUAGE_KEY = 'workdaddy.ui.language';
+ var WBS_ACCOUNT_MASK_KEY = 'workdaddy.account.mask.' + PROFILE_ID;
var WBS_I18N_EN = {
'账号': 'Accounts', '主题': 'Theme', '会话': 'Sessions', '模型': 'Models', '增强': 'Enhance', '电脑': 'Computer', '关于': 'About', '设置': 'Settings',
'导出': 'Export', '导入': 'Import', '删除': 'Delete', '编辑': 'Edit', '保存': 'Save', '取消': 'Cancel', '确定': 'Confirm', '确认': 'Confirm', '复制': 'Copy', '切换': 'Switch', '启用': 'Enable', '停止': 'Stop',
'暂存提示词': 'Stash prompt', '暂存': 'Stashed', '引用文本': 'Quote text', '快捷短语': 'Quick phrases', '点击后发送': 'Send on click', '编辑 →': 'Edit →', '新增': 'Add', '批量操作': 'Batch actions', '批量管理': 'Batch manage', '全选': 'Select all', '取消全选': 'Deselect all', '已选 0': 'Selected 0',
- '账号汇总': 'Account summary', '账号数': 'Accounts', '总积分': 'Total credits', '手机': 'Phone', '有效期至': 'Expires', '当前使用中': 'Currently active', '登录新账号': 'Log in a new account', '没有可导出的账号备份': 'No account backups to export', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。': 'No account backups yet. Open or log in to WorkBuddy once and check again later.',
+ '账号汇总': 'Account summary', '账号数': 'Accounts', '总积分': 'Total credits', '手机': 'Phone', '有效期至': 'Expires', '当前使用中': 'Currently active', '隐藏敏感信息': 'Mask sensitive info', '显示明文': 'Show plaintext', '登录新账号': 'Log in a new account', '没有可导出的账号备份': 'No account backups to export', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。': 'No account backups yet. Open or log in to WorkBuddy once and check again later.',
'语言': 'Language', '中文': 'Chinese', '英语': 'English', 'English': 'English', '跟随系统': 'Follow system', '设置语言': 'Language', '首次打开时自动跟随系统语言;未匹配时使用英语。': 'The first launch follows your system language. English is used when no match is found.', '语言设置已更新': 'Language updated',
'默认': 'Default', 'WorkDaddy 主题': 'WorkDaddy theme', '毛玻璃': 'Frosted glass', '护眼绿': 'Eye-care green', '赛博紫': 'Cyber purple', '主题外观': 'Theme appearance', '壁纸': 'Wallpaper', '头像': 'Avatar', '自定义壁纸': 'Custom wallpaper', '背景蒙版': 'Background overlay', '背景毛玻璃': 'Background blur', '恢复默认': 'Restore default', '恢复官方头像': 'Restore official avatar',
'加载中…': 'Loading…', '读取中…': 'Reading…', '正在读取设置…': 'Reading settings…', '查询中…': 'Checking…', '暂无快捷短语': 'No quick phrases', '暂无快捷短语,点击「+ 新增」添加': 'No quick phrases. Click “+ Add” to create one.', '当前还未添加模型': 'No models added yet', '还没有模型备份': 'No model backups yet', '当前筛选下没有会话': 'No sessions match the current filter', '暂无进行中的会话': 'No active sessions', '暂无官方壁纸': 'No built-in wallpapers', '还没有自定义壁纸,先上传一张': 'No custom wallpapers yet. Upload one to start.', '壁纸加载中…': 'Loading wallpapers…', '壁纸加载失败(daemon 不可达)': 'Wallpaper loading failed (daemon unavailable)',
@@ -645,6 +646,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'登录文件目标路径无效': 'Invalid login file target path',
'登录文件目标不是当前客户端的有效认证文件,拒绝覆盖': 'Login file target is not a valid auth file for this client; overwrite rejected',
'登录文件名已属于其他账号,拒绝覆盖': 'Login filename already belongs to another account; overwrite rejected',
+ '登录文件目标属于其他认证通道,拒绝覆盖': 'Login file target belongs to another auth channel; overwrite rejected',
'账号缺少已确认的登录文件名,拒绝猜测写入目标': 'Account has no confirmed login filename; refusing to guess a write target',
'备份文件校验失败:uid 不匹配,已中止切换': 'Backup validation failed: uid mismatch; switch aborted',
// —— 第六批:会话/模型批量操作 + 头像 + 修补剩余整句 ——
@@ -909,7 +911,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
window.addEventListener('unhandledrejection', function (ev) { wbsReportErr('unhandledrejection', ev); });
}
- var state = { accounts: [], current: null, open: false, batchRunning: false, creditRunId: 0, creditRemaining: 0, creditSummaryValue: null, checkinPollId: null };
+ var accountMaskEnabled = false;
+ try { accountMaskEnabled = localStorage.getItem(WBS_ACCOUNT_MASK_KEY) === '1'; } catch (_) {}
+ var state = { accounts: [], current: null, open: false, batchRunning: false, creditRunId: 0, creditRemaining: 0, creditSummaryValue: null, checkinPollId: null, mask: accountMaskEnabled };
var currentBuild = null;
// 当前注入的 daemon 版本号(由 daemon.js 注入时把 __WBS_VERSION__ 替换为 DAEMON_VERSION)
// 「关于」tab 直接展示,升级 daemon 后这里自动同步
@@ -978,6 +982,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>' +
'<polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
+ // 脱敏小眼睛:睁眼 = 明文可见(点击后隐藏);闭眼(斜线) = 已脱敏(点击后显示明文)
+ var EYE_SVG =
+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
+ '<path d="M2.06 12.35C3.2 8.1 7.6 5 12 5s8.8 3.1 9.94 7.35a.5.5 0 0 1 0 .3C20.8 16.9 16.4 20 12 20s-8.8-3.1-9.94-7.35a.5.5 0 0 1 0-.3z"/>' +
+ '<circle cx="12" cy="12" r="3"/></svg>';
+ var EYE_OFF_SVG =
+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
+ '<path d="M2.06 12.35C3.2 8.1 7.6 5 12 5s8.8 3.1 9.94 7.35a.5.5 0 0 1 0 .3C20.8 16.9 16.4 20 12 20s-8.8-3.1-9.94-7.35a.5.5 0 0 1 0-.3z"/>' +
+ '<circle cx="12" cy="12" r="3"/><line x1="4.2" y1="5.6" x2="19.8" y2="18.4"/></svg>';
// 暂存提示词按钮图标:纯色「标签」图标(实心填充风,非线条);fill 用 currentColor 跟随按钮文字色(主题适配)
var STASH_SVG =
@@ -4022,6 +4035,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-acct-toolbar">' +
'<div class="wbs-acct-summary" aria-label="账号汇总">' +
'<div class="wbs-acct-stat"><span>账号数</span><strong id="wbs-acct-count">-</strong></div>' +
+ '<button class="wbs-acct-eye" type="button" title="隐藏敏感信息" aria-label="隐藏敏感信息">' + EYE_SVG + '</button>' +
'<span class="wbs-acct-stat-divider"></span>' +
'<div class="wbs-acct-stat"><span>总积分</span><strong id="wbs-acct-total">-</strong></div>' +
'</div>' +
@@ -4034,6 +4048,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<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">';
logoutBtn = root.querySelector('[data-act="logout"]');
+ var eyeBtn = root.querySelector('.wbs-acct-eye');
+ if (eyeBtn) eyeBtn.addEventListener('click', toggleAccountMask);
root.querySelector('[data-act="export"]').addEventListener('click', onExportAccounts);
root.querySelector('[data-act="import"]').addEventListener('click', function () {
root.querySelector('#wbs-import-file').click();
@@ -9318,19 +9334,23 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// UIN 与手机号共用同一标签和值间距,确保与“剩余”额度列对齐。
var isUinMode = !a.phone;
var idLbl = a.phone ? '手机' : (a.uin ? 'UIN' : '账号');
- var idVal = a.phone ? esc(a.phone) : (a.uin ? esc(a.uin) : '-');
+ var rawName = a.nickname || '(未命名)';
+ var rawId = a.phone ? a.phone : (a.uin ? a.uin : '-');
+ var nameVal = state.mask ? maskAccountName(rawName) : rawName;
+ var idVal = state.mask ? maskAccountId(rawId) : rawId;
card.innerHTML =
curMark +
'<div class="wbs-info">' +
- '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(a.nickname || '(未命名)') + '</span>' + badge + checkinBadge + '</div>' + ops + '</div>' +
+ '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(nameVal) + '</span>' + badge + checkinBadge + '</div>' + ops + '</div>' +
'<div class="wbs-meta wbs-secondary-row">' +
- '<div class="wbs-mi wbs-phone-cell' + (isUinMode ? ' wbs-uin-cell' : '') + '"><span class="wbs-lbl">' + idLbl + '</span><span class="wbs-val">' + idVal + '</span></div>' +
+ '<div class="wbs-mi wbs-phone-cell' + (isUinMode ? ' wbs-uin-cell' : '') + '"><span class="wbs-lbl">' + idLbl + '</span><span class="wbs-val">' + esc(idVal) + '</span></div>' +
'<div class="wbs-mi wbs-token-cell"><span class="wbs-lbl">有效期至</span><span class="wbs-val' + (ts.warn ? ' wbs-warn' : '') + '">' + esc(ts.label) + '</span></div>' +
'</div>' +
'<div class="wbs-credit-cell">' + creditBlockHtml(credits, a.creditSegments, a) + '</div>' +
'</div>';
list.appendChild(card);
});
+ applyAccountMask();
// 切换按钮:两击确认(第一次点击进入确认态,3s 内再点才真正切换,防止误触)
list.querySelectorAll('.wbs-acc-switch').forEach(function (btn) {
var armed = false;
@@ -9415,6 +9435,57 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
+ function maskAccountName(name) {
+ var s = String(name == null ? '' : name);
+ if (!s.length) return s;
+ if (s.length === 1) return '**';
+ if (s.length === 2) return '**';
+ return s.charAt(0) + new Array(s.length - 1).join('*') + s.charAt(s.length - 1);
+ }
+
+ function maskAccountId(v) {
+ var s = String(v == null ? '' : v).trim();
+ if (!s || s === '-') return s;
+ if (/^\d+$/.test(s)) {
+ if (s.length >= 7) return s.slice(0, 3) + '****' + s.slice(s.length - 4);
+ return s.replace(/\d/g, '*');
+ }
+ return maskAccountName(s);
+ }
+
+ // 眼睛按钮 + 卡片文本联动:恢复上次选择,点击切换脱敏/明文
+ function applyAccountMask() {
+ var eyeBtn = accountsPane.querySelector('.wbs-acct-eye');
+ if (eyeBtn) {
+ eyeBtn.innerHTML = state.mask ? EYE_OFF_SVG : EYE_SVG;
+ var tip = state.mask ? '显示明文' : '隐藏敏感信息';
+ eyeBtn.title = tip;
+ eyeBtn.setAttribute('aria-label', tip);
+ }
+ var cards = accountsPane.querySelectorAll('.wbs-card');
+ for (var c = 0; c < cards.length; c++) {
+ var uid = cards[c].getAttribute('data-uid');
+ var account = null;
+ for (var i = 0; i < state.accounts.length; i++) {
+ if (String(state.accounts[i].uid) === String(uid)) { account = state.accounts[i]; break; }
+ }
+ if (!account) continue;
+ var nameEl = cards[c].querySelector('.wbs-name');
+ if (nameEl) nameEl.textContent = state.mask ? maskAccountName(account.nickname || '(未命名)') : (account.nickname || '(未命名)');
+ var valEl = cards[c].querySelector('.wbs-phone-cell .wbs-val');
+ if (valEl) {
+ var raw = account.phone ? account.phone : (account.uin ? account.uin : '-');
+ valEl.textContent = state.mask ? maskAccountId(raw) : raw;
+ }
+ }
+ }
+
+ function toggleAccountMask() {
+ state.mask = !state.mask;
+ try { localStorage.setItem(WBS_ACCOUNT_MASK_KEY, state.mask ? '1' : '0'); } catch (_) {}
+ applyAccountMask();
+ }
+
function refresh() {
if (!CAPS.accounts) {
if (sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();
@@ -10498,6 +10569,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
/* 账号列表容器 + 退出按钮 */
'.wbs-acct-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 14px 9px;border-bottom:1px solid var(--wb-border-subtle,#f0f0f0);background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 25%,transparent);flex-shrink:0}',
'.wbs-acct-summary{display:flex;align-items:center;gap:12px;min-width:0}',
+ '.wbs-acct-eye{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;padding:0;border:none;border-radius:6px;background:transparent;color:var(--wb-icon-secondary,var(--wb-color-text-secondary,#666));cursor:pointer;flex-shrink:0;transition:color .15s,background-color .15s}',
+ '.wbs-acct-eye:hover{background:var(--wb-bg-hover,#f0f0f0);color:var(--wb-color-text,#222)}',
+ '.wbs-acct-eye:active{transform:scale(.94)}',
+ '.wbs-acct-eye:focus-visible{outline:2px solid var(--wb-accent,#4c8dff);outline-offset:1px}',
'.wbs-acct-stat{display:flex;align-items:center;gap:5px;white-space:nowrap;line-height:1}',
'.wbs-acct-stat span,.wbs-acct-stat strong{font-size:13px}',
'.wbs-acct-stat span{color:var(--wb-icon-tertiary,#999);font-weight:500}',
diff --git a/scripts/lib.js b/scripts/lib.js
index e192352..ce8debb 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -1096,17 +1096,23 @@ function readAuthFile(file = currentAuthFile()) {
return info;
}
-/** 更新 meta.json(uid -> nickname/uin/phone/时间) */
-function updateMeta(dataDir, info) {
+/** 更新 meta.json(uid -> nickname/uin/phone/时间)。preserveBinding:备份扫描路径
+ * 不漂移「账号 -> 登录文件」绑定——auth 目录里的个性化历史存档(带时间戳)即使
+ * 残留 lastLogin 标记,也不得覆盖切换路径建立的绑定关系。 */
+function updateMeta(dataDir, info, { preserveBinding = false } = {}) {
const meta = readMeta(dataDir);
const now = Date.now();
const prev = meta.accounts[info.uid] || {};
+ let authFileName = info.authFileName || prev.authFileName || '';
+ if (preserveBinding && prev.authFileName && info.authFileName && prev.authFileName !== info.authFileName) {
+ authFileName = prev.authFileName;
+ }
meta.accounts[info.uid] = {
uid: info.uid,
nickname: info.nickname || prev.nickname || '',
uin: info.uin || prev.uin || '',
phone: info.phone || prev.phone || '',
- authFileName: info.authFileName || prev.authFileName || '',
+ authFileName,
authDomain: info.authDomain || prev.authDomain || '',
authIssuer: info.authIssuer || prev.authIssuer || '',
firstSeen: prev.firstSeen || now,
@@ -1123,12 +1129,16 @@ function backupAuthFile(dataDir, file, log = () => {}) {
fs.writeFileSync(tmp, fs.readFileSync(file), { mode: 0o600 });
fs.renameSync(tmp, dest);
fs.chmodSync(dest, 0o600);
- updateMeta(dataDir, info);
+ updateMeta(dataDir, info, { preserveBinding: true });
log(`[sync] 已备份账号 ${info.nickname || info.uid} (${info.uid}) -> ${dest}`);
return info;
}
-/** 把活动登录信息备份到 accounts/<uid>.info(原子写入,0600)。 */
+/** 把活动登录信息备份到 accounts/<uid>.info(原子写入,0600)。
+ * 已有同名备份的账号只接受「官方权威登录位」(固定文件/当前登录位)作为更新源:
+ * auth 目录里的个性化历史存档(同 uid、老 token、残留 lastLogin 标记)不允许
+ * 覆盖有效备份——否则切换会写入早已失效的旧 refresh token,导致官方身份过期
+ * (真实事故:s 账号备份曾被 2026-08-21 存档覆盖成 8-19 的 token)。 */
function backupCurrent(dataDir, log = () => {}) {
if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号文件备份`);
ensureDirs(dataDir, log);
@@ -1136,11 +1146,16 @@ function backupCurrent(dataDir, log = () => {}) {
if (!records.length) throw new Error('未找到有效的登录信息文件');
const current = resolveCurrentAuth();
let result = null;
+ let backedUp = 0;
for (const record of records) {
+ const authoritative = current.file && samePath(record.file, current.file);
+ const existingBackup = fs.existsSync(backupPath(dataDir, record.uid));
+ if (existingBackup && !authoritative) continue; // 历史存档不覆盖已有备份
const info = backupAuthFile(dataDir, record.file, log);
- if (!result || (current.file && samePath(record.file, current.file))) result = info;
+ backedUp += 1;
+ if (!result || authoritative) result = info;
}
- return Object.assign(result, { backedUp: records.length, ambiguous: !!current.ambiguous });
+ return Object.assign(result || {}, { backedUp, ambiguous: !!current.ambiguous });
}
function resolveAuthTarget(dataDir, uid, authJson) {
@@ -1149,17 +1164,37 @@ function resolveAuthTarget(dataDir, uid, authJson) {
const record = meta.accounts[String(uid)] || {};
const backup = authRecordFromJson(null, authJson);
if (!backup) throw new Error('备份文件认证数据无效,拒绝切换');
+ const sameChannel = (candidate) => {
+ const expected = new Set([backup.authIssuer, backup.authDomain].filter(Boolean));
+ return [candidate && candidate.authIssuer, candidate && candidate.authDomain]
+ .some((origin) => origin && expected.has(origin));
+ };
+ // 官方固定登录位(workbuddy-desktop.info / workbuddy-desktop-ai.info)是官方实际
+ // 读取的当前登录文件。它存在时,所有显式切换一律写这里——个性化历史存档(带时间戳
+ // 的 info)只是官方多账号机制的存档,写了官方也不读。切换后 updateMeta 会同步修正
+ // 「账号 -> 登录文件」绑定,历史上被备份扫描漂移到旧文件的记录在此自愈。
+ if (AUTH_FILE && parseAuthFile(AUTH_FILE)) return AUTH_FILE;
const targetName = safeAuthFileName(record.authFileName) ? record.authFileName : '';
if (targetName) {
const target = path.join(authDir(), targetName);
if (path.dirname(path.resolve(target)) !== path.resolve(authDir())) throw new Error('登录文件目标路径无效');
const existing = fs.existsSync(target) ? parseAuthFile(target) : null;
if (fs.existsSync(target) && !existing) throw new Error('登录文件目标不是当前客户端的有效认证文件,拒绝覆盖');
- if (existing && existing.uid !== String(uid)) throw new Error('登录文件名已属于其他账号,拒绝覆盖');
+ if (existing && !sameChannel(existing)) throw new Error('登录文件目标属于其他认证通道,拒绝覆盖');
return target;
}
- const matching = listAuthRecords().filter((item) => item.uid === String(uid));
+ const records = listAuthRecords();
+ const matching = records.filter((item) => item.uid === String(uid));
if (matching.length === 1) return matching[0].file;
+ const channelMatches = records.filter(sameChannel);
+ const canonical = channelMatches.find((item) => AUTH_FILE && samePath(item.file, AUTH_FILE));
+ if (canonical) return canonical.file;
+ if (channelMatches.length === 1) return channelMatches[0].file;
+ const legacyRecord = String(record.uid || '') === String(uid) &&
+ !record.authFileName && !record.authDomain && !record.authIssuer;
+ // legacy 账号(动态发现上线前备份)没有属于自己的文件记录,其唯一正确的落点就是
+ // 官方固定登录文件(AUTH_FILE);无论该文件当前是否被占用,用户显式切换即意图覆盖。
+ if (legacyRecord && AUTH_FILE) return AUTH_FILE;
throw new Error('账号缺少已确认的登录文件名,拒绝猜测写入目标');
}
diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.iss
index 3ad0c81..59f08dd 100644
--- a/scripts/win/workdaddy.iss
+++ b/scripts/win/workdaddy.iss
@@ -61,7 +61,7 @@ Source: "{#StageRoot}\WorkDaddyLauncher.exe"; DestDir: "{app}"; Flags: ignorever
Source: "{#StageRoot}\WorkDaddyLauncher.exe"; Flags: dontcopy
Source: "{#StageRoot}\scripts\WorkDaddy.ico"; DestDir: "{app}\scripts"; DestName: "{#PackageName}-{#AppVersion}.ico"; Flags: ignoreversion
Source: "{#StageRoot}\scripts\*"; DestDir: "{app}\scripts"; Excludes: "runtime\node\*,WorkDaddy.ico"; Flags: ignoreversion recursesubdirs createallsubdirs
-Source: "{#StageRoot}\scripts\runtime\node\*"; DestDir: "{app}\scripts\runtime\node"; Flags: ignoreversion recursesubdirs createallsubdirs
+Source: "{#StageRoot}\scripts\runtime\node\*"; DestDir: "{app}\scripts\runtime\node"; Flags: ignoreversion recursesubdirs createallsubdirs; Check: ShouldReplaceRuntime
[InstallDelete]
Type: files; Name: "{app}\scripts\WorkDaddy.ico"
@@ -86,6 +86,7 @@ Type: filesandordirs; Name: "{app}"
[Code]
var
+ PreserveExistingLifecycle: Boolean;
ClientPage: TInputFileWizardPage;
ClientSourceLabel: TNewStaticText;
ClientVersionLabel: TNewStaticText;
@@ -94,6 +95,14 @@ var
SelectedWorkBuddyPath: String;
SelectedWorkBuddyVersion: String;
+function ShouldReplaceRuntime(): Boolean;
+begin
+ // 已验证的 elevated 生命周期被保留时(错误码 13),旧 daemon 仍持有
+ // runtime\node\node.exe 文件锁,跳过替换避免安装中途失败;下次启动时
+ // 新版 watchdog 会用验证边界自行接管并替换旧进程。
+ Result := not PreserveExistingLifecycle;
+end;
+
function RunNativeHelper(const Mode: String; var ResultCode: Integer): Boolean;
var
Parameters: String;
@@ -757,7 +766,11 @@ begin
Result := '无法启动 WorkDaddy 后台进程清理。可能原因是安装器原始用户权限不可用、安全软件拦截了临时 helper,或临时目录不可写。请点击“取消”,关闭安装程序后直接双击安装包重新运行;不要选择“以管理员身份运行”。UAC 无需关闭。';
exit;
end;
- if ResultCode = 11 then
+ if ResultCode = 13 then
+ // 已验证正在运行的 daemon 是本 profile 的 elevated 生命周期(通过本地
+ // API 身份凭证证明),保留它并继续安装;runtime\node 跳过本次替换。
+ PreserveExistingLifecycle := True
+ else if ResultCode = 11 then
Result := '无法安全停止 WorkDaddy 后台进程:安装无法继续。检测到 WorkDaddy 或 WorkDaddyLauncher 仍在运行,但当前安装器没有结束它的权限(错误码 11)。请按以下步骤操作:' + #13#10 +
'1. 点击“取消”;' + #13#10 +
'2. 按 Ctrl+Shift+Esc 打开任务管理器,结束 WorkDaddy 和 WorkDaddyLauncher;' + #13#10 +
diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.go
index c62e68a..5c4a419 100644
--- a/scripts/windows-native/main.go
+++ b/scripts/windows-native/main.go
@@ -3,10 +3,12 @@
package main
import (
+ "context"
"encoding/json"
"errors"
"fmt"
"io"
+ "net/http"
"os"
"os/exec"
"path/filepath"
@@ -21,18 +23,23 @@ const (
profileCN = "workbuddy-cn"
profileAI = "workbuddy-ai"
- exitFailure = 4
- exitElevated = 5
- exitWorkBuddyRunning = 10
- exitAccessDenied = 11
- exitIdentityMismatch = 12
- exitUsage = 20
+ exitFailure = 4
+ exitElevated = 5
+ exitWorkBuddyRunning = 10
+ exitAccessDenied = 11
+ exitIdentityMismatch = 12
+ exitPreserveLifecycle = 13
+ exitUsage = 20
processTerminate = 0x0001
processQueryLimitedInformation = 0x1000
synchronize = 0x00100000
+ tokenAssignPrimary = 0x0001
+ tokenDuplicate = 0x0002
tokenQuery = 0x0008
tokenElevation = 20 // TokenElevation
+ logonWithProfile = 0x00000001
+ createUnicodeEnvironment = 0x00000400
th32csSnapProcess = 0x00000002
maxPath = 260
infinite = 0xffffffff
@@ -48,12 +55,16 @@ const (
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
advapi32 = syscall.NewLazyDLL("advapi32.dll")
+ userenv = syscall.NewLazyDLL("userenv.dll")
user32 = syscall.NewLazyDLL("user32.dll")
versionDLL = syscall.NewLazyDLL("version.dll")
procCreateMutexW = kernel32.NewProc("CreateMutexW")
procGetCurrentProcess = kernel32.NewProc("GetCurrentProcess")
procOpenProcessToken = advapi32.NewProc("OpenProcessToken")
procGetTokenInformation = advapi32.NewProc("GetTokenInformation")
+ procCreateProcessWithTokenW = advapi32.NewProc("CreateProcessWithTokenW")
+ procCreateEnvironmentBlock = userenv.NewProc("CreateEnvironmentBlock")
+ procDestroyEnvironmentBlock = userenv.NewProc("DestroyEnvironmentBlock")
procCreateToolhelp32Snapshot = kernel32.NewProc("CreateToolhelp32Snapshot")
procProcess32FirstW = kernel32.NewProc("Process32FirstW")
procProcess32NextW = kernel32.NewProc("Process32NextW")
@@ -62,6 +73,8 @@ var (
procTerminateProcess = kernel32.NewProc("TerminateProcess")
procWaitForSingleObject = kernel32.NewProc("WaitForSingleObject")
procMessageBoxW = user32.NewProc("MessageBoxW")
+ procGetShellWindow = user32.NewProc("GetShellWindow")
+ procGetWindowThreadProcessID = user32.NewProc("GetWindowThreadProcessId")
procGetFileVersionInfoSizeW = versionDLL.NewProc("GetFileVersionInfoSizeW")
procGetFileVersionInfoW = versionDLL.NewProc("GetFileVersionInfoW")
procVerQueryValueW = versionDLL.NewProc("VerQueryValueW")
@@ -100,6 +113,18 @@ type workBuddyTarget struct {
ProcessNames []string `json:"processNames"`
}
+// daemonStatus mirrors the authenticated subset of the daemon /api/status
+// payload. Only fields required for capability proof are decoded.
+type daemonStatus struct {
+ OK bool `json:"ok"`
+ PID int `json:"pid"`
+ Privilege string `json:"privilege"`
+ DataDir string `json:"dataDir"`
+ Profile struct {
+ ID string `json:"id"`
+ } `json:"profile"`
+}
+
type vsFixedFileInfo struct {
Signature uint32
StructVersion uint32
@@ -158,6 +183,18 @@ func fileVersion(binary string) string {
fixed.FileVersionLS>>16, fixed.FileVersionLS&0xffff)
}
+func tokenIsElevated(token syscall.Handle) (bool, error) {
+ var elevation uint32
+ var returned uint32
+ result, _, callErr := procGetTokenInformation.Call(
+ uintptr(token), tokenElevation, uintptr(unsafe.Pointer(&elevation)), unsafe.Sizeof(elevation), uintptr(unsafe.Pointer(&returned)),
+ )
+ if result == 0 {
+ return false, callErr
+ }
+ return elevation != 0, nil
+}
+
func isElevated() (bool, error) {
current, _, _ := procGetCurrentProcess.Call()
var token syscall.Handle
@@ -166,15 +203,71 @@ func isElevated() (bool, error) {
return false, callErr
}
defer syscall.CloseHandle(token)
- var elevation uint32
- var returned uint32
- result, _, callErr = procGetTokenInformation.Call(
- uintptr(token), tokenElevation, uintptr(unsafe.Pointer(&elevation)), unsafe.Sizeof(elevation), uintptr(unsafe.Pointer(&returned)),
+ return tokenIsElevated(token)
+}
+
+func relaunchWithDesktopToken(appDir string) error {
+ shellWindow, _, callErr := procGetShellWindow.Call()
+ if shellWindow == 0 {
+ return fmt.Errorf("cannot find desktop Explorer window: %w", callErr)
+ }
+ var shellPID uint32
+ procGetWindowThreadProcessID.Call(shellWindow, uintptr(unsafe.Pointer(&shellPID)))
+ if shellPID == 0 {
+ return errors.New("cannot identify desktop Explorer process")
+ }
+ expectedExplorer := filepath.Join(os.Getenv("SystemRoot"), "explorer.exe")
+ if os.Getenv("SystemRoot") == "" || !strings.EqualFold(filepath.Clean(queryProcessPath(shellPID)), filepath.Clean(expectedExplorer)) {
+ return errors.New("desktop shell process is not the expected explorer.exe")
+ }
+ shellProcess, err := openProcess(shellPID, processQueryLimitedInformation)
+ if err != nil {
+ return fmt.Errorf("cannot open desktop Explorer process: %w", err)
+ }
+ defer syscall.CloseHandle(shellProcess)
+ var shellToken syscall.Handle
+ result, _, callErr := procOpenProcessToken.Call(
+ uintptr(shellProcess), tokenAssignPrimary|tokenDuplicate|tokenQuery, uintptr(unsafe.Pointer(&shellToken)),
)
if result == 0 {
- return false, callErr
+ return fmt.Errorf("cannot open desktop Explorer token: %w", callErr)
}
- return elevation != 0, nil
+ defer syscall.CloseHandle(shellToken)
+ elevated, err := tokenIsElevated(shellToken)
+ if err != nil {
+ return fmt.Errorf("cannot inspect desktop Explorer token: %w", err)
+ }
+ if elevated {
+ return errors.New("desktop Explorer token is elevated")
+ }
+ executable, err := os.Executable()
+ if err != nil {
+ return err
+ }
+ if strings.ContainsAny(executable, "\x00\r\n\"") {
+ return errors.New("native launcher path contains invalid characters")
+ }
+ var environment uintptr
+ result, _, callErr = procCreateEnvironmentBlock.Call(
+ uintptr(unsafe.Pointer(&environment)), uintptr(shellToken), 0,
+ )
+ if result == 0 {
+ return fmt.Errorf("cannot create desktop user environment: %w", callErr)
+ }
+ defer procDestroyEnvironmentBlock.Call(environment)
+ commandLine := utf16Ptr("\"" + executable + "\" --desktop-shell-relaunch")
+ startup := syscall.StartupInfo{Cb: uint32(unsafe.Sizeof(syscall.StartupInfo{}))}
+ var processInfo syscall.ProcessInformation
+ result, _, callErr = procCreateProcessWithTokenW.Call(
+ uintptr(shellToken), logonWithProfile, uintptr(unsafe.Pointer(utf16Ptr(executable))), uintptr(unsafe.Pointer(commandLine)),
+ createUnicodeEnvironment, environment, uintptr(unsafe.Pointer(utf16Ptr(appDir))), uintptr(unsafe.Pointer(&startup)), uintptr(unsafe.Pointer(&processInfo)),
+ )
+ if result == 0 {
+ return fmt.Errorf("cannot relaunch with desktop Explorer token: %w", callErr)
+ }
+ syscall.CloseHandle(processInfo.Thread)
+ syscall.CloseHandle(processInfo.Process)
+ return nil
}
func acquireMutex(profile string) (syscall.Handle, bool, error) {
@@ -747,6 +840,151 @@ func stopLifecycle(profile, appDir string, elevated bool) int {
return 0
}
+// profileUiPorts returns the fixed UI-port candidates for a profile in
+// preference order. They mirror scripts/ui-port.js PROFILE_UI_PORTS.
+func profileUiPorts(profile string) []int {
+ if profile == profileAI {
+ return []int{47833, 17833, 27833, 37833}
+ }
+ return []int{47832, 17832, 27832, 37832}
+}
+
+// persistedUiPort reads DATA_DIR/ui-port.json and returns the recorded port
+// when it belongs to this profile's candidate list, otherwise 0.
+func persistedUiPort(profile, dir string) int {
+ data, err := os.ReadFile(filepath.Join(dir, "ui-port.json"))
+ if err != nil {
+ return 0
+ }
+ var state struct {
+ ProfileID string `json:"profileId"`
+ Port int `json:"port"`
+ }
+ if json.Unmarshal(data, &state) != nil || state.ProfileID != profile || state.Port <= 0 {
+ return 0
+ }
+ for _, port := range profileUiPorts(profile) {
+ if port == state.Port {
+ return port
+ }
+ }
+ return 0
+}
+
+// listenerPidOnPort resolves the unique PID listening on a TCP port through
+// netstat. It is visible for elevated listeners from a standard process.
+func listenerPidOnPort(port int) (int, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "netstat", "-ano").Output()
+ if err != nil {
+ return 0, fmt.Errorf("netstat failed: %w", err)
+ }
+ target := fmt.Sprintf(":%d", port)
+ pids := map[int]bool{}
+ for _, line := range strings.Split(string(out), "\n") {
+ if !strings.Contains(line, target) || !strings.Contains(line, "LISTENING") {
+ continue
+ }
+ fields := strings.Fields(line)
+ if len(fields) == 0 {
+ continue
+ }
+ pid, parseErr := strconv.Atoi(fields[len(fields)-1])
+ if parseErr != nil {
+ continue
+ }
+ pids[pid] = true
+ }
+ if len(pids) != 1 {
+ if len(pids) == 0 {
+ return 0, fmt.Errorf("no listener found on port %d", port)
+ }
+ return 0, fmt.Errorf("multiple listeners found on port %d", port)
+ }
+ for pid := range pids {
+ return pid, nil
+ }
+ return 0, fmt.Errorf("no listener found on port %d", port)
+}
+
+func fetchDaemonStatus(port int, token string) (*daemonStatus, error) {
+ client := &http.Client{
+ Timeout: 3 * time.Second,
+ Transport: &http.Transport{
+ Proxy: nil,
+ },
+ }
+ request, err := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d/api/status", port), nil)
+ if err != nil {
+ return nil, err
+ }
+ request.Header.Set("X-WorkDaddy-Token", token)
+ response, err := client.Do(request)
+ if err != nil {
+ return nil, err
+ }
+ defer response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("status endpoint returned %s", response.Status)
+ }
+ body, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
+ if err != nil {
+ return nil, err
+ }
+ var status daemonStatus
+ if json.Unmarshal(body, &status) != nil {
+ return nil, errors.New("status endpoint returned invalid JSON")
+ }
+ return &status, nil
+}
+
+// authenticatedElevatedDaemonStatus proves that the running daemon for this
+// profile is the exact current-profile lifecycle using the local API token:
+// the per-profile /api/status response must report ok, a positive PID, the
+// matching profile id, elevated privilege and the matching data directory,
+// and the port listener must be the reported PID itself. This is a
+// non-termination capability proof: it never touches the remote process.
+func authenticatedElevatedDaemonStatus(profile string) (*daemonStatus, error) {
+ dir, err := dataDir(profile)
+ if err != nil {
+ return nil, err
+ }
+ tokenData, err := os.ReadFile(filepath.Join(dir, ".api-token"))
+ if err != nil {
+ return nil, errors.New("当前 profile 缺少本地 API 身份凭证")
+ }
+ token := strings.TrimSpace(string(tokenData))
+ if len(token) != 64 {
+ return nil, errors.New("当前 profile 的本地 API 身份凭证无效")
+ }
+ ports := profileUiPorts(profile)
+ if persisted := persistedUiPort(profile, dir); persisted > 0 {
+ ports = append([]int{persisted}, ports...)
+ }
+ expectedDataDir := strings.TrimRight(filepath.Clean(dir), `\/`)
+ for _, port := range ports {
+ status, fetchErr := fetchDaemonStatus(port, token)
+ if fetchErr != nil {
+ continue
+ }
+ if !status.OK || status.PID <= 0 || status.Profile.ID != profile ||
+ status.Privilege != "elevated" || strings.TrimSpace(status.DataDir) == "" {
+ continue
+ }
+ actualDataDir := strings.TrimRight(filepath.Clean(status.DataDir), `\/`)
+ if !strings.EqualFold(actualDataDir, expectedDataDir) {
+ continue
+ }
+ listenerPid, listenErr := listenerPidOnPort(port)
+ if listenErr != nil || listenerPid != status.PID {
+ continue
+ }
+ return status, nil
+ }
+ return nil, errors.New("无法通过本地身份凭证确认正在运行的本 profile 生命周期")
+}
+
func appendLog(dir string, args ...any) *os.File {
_ = os.MkdirAll(dir, 0700)
file, err := os.OpenFile(filepath.Join(dir, "native-launcher.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
@@ -890,7 +1128,20 @@ func helperMain(appDir, profile string) (bool, int) {
if targetApp == "" {
targetApp = appDir
}
- return true, stopLifecycle(profile, targetApp, elevated)
+ code := stopLifecycle(profile, targetApp, elevated)
+ if code == exitAccessDenied && !elevated {
+ // A standard helper cannot terminate an elevated lifecycle. Before
+ // failing closed, prove with the per-profile API token that the
+ // running daemon is this exact profile's lifecycle; the installer
+ // then preserves it and continues instead of blocking upgrades.
+ if status, verifyErr := authenticatedElevatedDaemonStatus(profile); verifyErr == nil {
+ fmt.Fprintln(os.Stderr, "verified elevated lifecycle preserved pid="+strconv.Itoa(status.PID))
+ return true, exitPreserveLifecycle
+ } else {
+ fmt.Fprintln(os.Stderr, "elevated lifecycle verification failed:", verifyErr)
+ }
+ }
+ return true, code
}
if hasArgument("--self-test") {
elevated, err := isElevated()
@@ -920,7 +1171,12 @@ func main() {
os.Exit(exitFailure)
}
if elevated {
- messageBox(productName(profile), "请使用普通方式启动 WorkDaddy,不要选择“以管理员身份运行”。\n\nUAC 可以保持开启;正常双击快捷方式不会请求管理员权限。", mbOK|mbIconWarning)
+ if !hasArgument("--desktop-shell-relaunch") {
+ if err := relaunchWithDesktopToken(appDir); err == nil {
+ os.Exit(0)
+ }
+ }
+ messageBox(productName(profile), "无法自动切换到普通用户权限。\n\n请确认 UAC 已开启,然后直接双击 WorkDaddy 快捷方式重试。", mbOK|mbIconWarning)
os.Exit(exitElevated)
}
diff --git a/test/auth-discovery.test.js b/test/auth-discovery.test.js
index 3824e29..8f78eac 100644
--- a/test/auth-discovery.test.js
+++ b/test/auth-discovery.test.js
@@ -124,6 +124,120 @@ test('missing filename metadata refuses a switch instead of falling back to a gu
}
});
+test('legacy account metadata migrates to the canonical auth file for the same channel', () => {
+ const f = fixture();
+ try {
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('current', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'legacy.info'), JSON.stringify(auth('legacy', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.dataDir, 'meta.json'), JSON.stringify({
+ accounts: {
+ legacy: { uid: 'legacy', nickname: 'legacy', firstSeen: 1, lastSeen: 2 },
+ },
+ }));
+
+ const switched = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.switchTo(process.env.WBSWITCH_DATA_DIR,"legacy")))');
+ assert.equal(switched.authFile, canonical);
+ assert.equal(JSON.parse(fs.readFileSync(canonical, 'utf8')).account.uid, 'legacy');
+ const meta = JSON.parse(fs.readFileSync(path.join(f.dataDir, 'meta.json'), 'utf8'));
+ assert.equal(meta.accounts.legacy.authFileName, 'workbuddy-desktop.info');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('recorded canonical auth target may be reused by another account in the same channel', () => {
+ const f = fixture();
+ try {
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('current', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'target.info'), JSON.stringify(auth('target', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.dataDir, 'meta.json'), JSON.stringify({
+ accounts: {
+ target: { uid: 'target', authFileName: 'workbuddy-desktop.info' },
+ },
+ }));
+
+ const switched = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.switchTo(process.env.WBSWITCH_DATA_DIR,"target")))');
+ assert.equal(switched.authFile, canonical);
+ assert.equal(JSON.parse(fs.readFileSync(canonical, 'utf8')).account.uid, 'target');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('recorded individual auth target still refuses to overwrite a different auth channel', () => {
+ const f = fixture();
+ try {
+ // 个性化文件名(非官方固定文件)是账号专属登录位,跨通道时保持拒绝。
+ const individual = path.join(f.authDir, 'opaque-target.info');
+ fs.writeFileSync(individual, JSON.stringify(auth('current', 'https://www.codebuddy.cn/auth/realms/copilot')));
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'target.info'), JSON.stringify(auth('target', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.dataDir, 'meta.json'), JSON.stringify({
+ accounts: {
+ target: { uid: 'target', authFileName: 'opaque-target.info' },
+ },
+ }));
+
+ const result = run(f.root, f.dataDir, `try { lib.switchTo(process.env.WBSWITCH_DATA_DIR,'target'); process.stdout.write('unexpected') } catch (e) { process.stdout.write(JSON.stringify(e.message)) }`);
+ assert.match(result, /其他认证通道/);
+ assert.equal(JSON.parse(fs.readFileSync(individual, 'utf8')).account.uid, 'current');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('recorded canonical auth file may be reused across different auth channels', () => {
+ const f = fixture();
+ try {
+ // 官方固定文件是跨账号轮流登录的共享登录位:当前被 codebuddy 通道占用时,
+ // workbuddy 通道账号(meta 明确记录该文件)切换应允许覆盖,否则永远切不回来。
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('current', 'https://www.codebuddy.cn/auth/realms/copilot')));
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'target.info'), JSON.stringify(auth('target', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.dataDir, 'meta.json'), JSON.stringify({
+ accounts: {
+ target: { uid: 'target', authFileName: 'workbuddy-desktop.info' },
+ },
+ }));
+
+ const switched = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.switchTo(process.env.WBSWITCH_DATA_DIR,"target")))');
+ assert.equal(switched.authFile, canonical);
+ assert.equal(JSON.parse(fs.readFileSync(canonical, 'utf8')).account.uid, 'target');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('legacy account may overwrite the occupied canonical auth file from another channel', () => {
+ const f = fixture();
+ try {
+ // 真实「切换失败」场景:legacy 账号(无任何文件记录,workbuddy.cn 通道)
+ // 切到已被 codebuddy.cn 账号占用的官方固定文件,必须允许写回。
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('current', 'https://www.codebuddy.cn/auth/realms/copilot')));
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'legacy.info'), JSON.stringify(auth('legacy', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.dataDir, 'meta.json'), JSON.stringify({
+ accounts: {
+ legacy: { uid: 'legacy', nickname: 'legacy', firstSeen: 1, lastSeen: 2 },
+ },
+ }));
+
+ const switched = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.switchTo(process.env.WBSWITCH_DATA_DIR,"legacy")))');
+ assert.equal(switched.authFile, canonical);
+ assert.equal(JSON.parse(fs.readFileSync(canonical, 'utf8')).account.uid, 'legacy');
+ const meta = JSON.parse(fs.readFileSync(path.join(f.dataDir, 'meta.json'), 'utf8'));
+ assert.equal(meta.accounts.legacy.authFileName, 'workbuddy-desktop.info');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
test('canonical fixed info file wins over historical lastLogin markers', () => {
const f = fixture();
try {
@@ -140,17 +254,77 @@ test('canonical fixed info file wins over historical lastLogin markers', () => {
}
});
-test('switch must succeed via the recorded target name despite multiple lastLogin markers', () => {
+test('switch writes the occupied canonical file despite multiple lastLogin markers', () => {
const f = fixture();
try {
fs.writeFileSync(path.join(f.authDir, 'workbuddy-desktop.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot')));
fs.writeFileSync(path.join(f.authDir, 's-history.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot', true)));
fs.writeFileSync(path.join(f.authDir, 'h-history.info'), JSON.stringify(auth('h', 'https://www.workbuddy.cn/auth/realms/copilot', true)));
run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');
- // meta.json 已记录 h 的目标文件名(h-history.info),切换不再被当前歧义一票否决
+ // 官方固定登录位是官方实际读取点:即使 meta 记录过 h 的历史存档文件名,
+ // 固定文件存在时一切显式切换也写固定文件,避免写在官方不读的历史存档上。
const switched = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.switchTo(process.env.WBSWITCH_DATA_DIR,"h")))');
- assert.equal(switched.authFile.endsWith('h-history.info'), true);
- assert.equal(JSON.parse(fs.readFileSync(path.join(f.authDir, 'h-history.info'), 'utf8')).account.uid, 'h');
+ assert.equal(switched.authFile.endsWith('workbuddy-desktop.info'), true);
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.authDir, 'workbuddy-desktop.info'), 'utf8')).account.uid, 'h');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('backup scan does not drift the account->file binding to historical archives', () => {
+ const f = fixture();
+ try {
+ // 历史存档(带 lastLogin 标记)存在时,备份扫描不得覆盖切换建立的账号->登录文件绑定
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.authDir, 'h-history.info'), JSON.stringify(auth('h', 'https://www.workbuddy.cn/auth/realms/copilot', true)));
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'h.info'), JSON.stringify(auth('h', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.dataDir, 'meta.json'), JSON.stringify({
+ accounts: { h: { uid: 'h', nickname: 'h', authFileName: 'workbuddy-desktop.info' } },
+ }));
+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');
+ const meta = run(f.root, f.dataDir, 'process.stdout.write(require("fs").readFileSync(process.env.WBSWITCH_DATA_DIR+"/meta.json","utf8"))');
+ assert.equal(meta.accounts.h.authFileName, 'workbuddy-desktop.info');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('backup scan never overwrites a valid backup with a historical archive', () => {
+ const f = fixture();
+ try {
+ // 官方固定登录位 = s(workbuddy.cn,权威);auth 目录同时存在 s 的历史存档
+ // (codebuddy.cn、lastLogin:true、老 token)。存档不得覆盖已有同名备份。
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.authDir, 's-archive.info'), JSON.stringify(auth('s', 'https://www.codebuddy.cn/auth/realms/copilot', true)));
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 's.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');
+ const backed = JSON.parse(fs.readFileSync(path.join(f.dataDir, 'accounts', 's.info'), 'utf8'));
+ // 备份来自固定登录位(workbuddy.cn),历史存档(codebuddy.cn)被拒绝覆盖
+ assert.equal(backed.auth.domain, 'https://www.workbuddy.cn');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('backup scan keeps the valid backup when the archive account is not logged in', () => {
+ const f = fixture();
+ try {
+ // 真实事故形态:当前登录 = 巴拉巴拉,s 已不在登录位;auth 目录只剩 s 的历史存档。
+ // 已有 s 备份必须保持原样,不允许被存档(8-19 老 token)覆盖。
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('balabala', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.authDir, 's-archive.info'), JSON.stringify(auth('s', 'https://www.codebuddy.cn/auth/realms/copilot', true)));
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ const fresh = JSON.stringify(auth('s', 'https://www.codebuddy.cn/auth/realms/copilot'));
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 's.info'), fresh);
+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');
+ const backed = JSON.parse(fs.readFileSync(path.join(f.dataDir, 'accounts', 's.info'), 'utf8'));
+ assert.equal(backed.account.uid, 's');
+ assert.equal(backed.auth.domain, 'https://www.codebuddy.cn');
} finally {
fs.rmSync(f.root, { recursive: true, force: true });
}
diff --git a/test/macos-dmg-layout.test.js b/test/macos-dmg-layout.test.js
index 9d90910..2808513 100644
--- a/test/macos-dmg-layout.test.js
+++ b/test/macos-dmg-layout.test.js
@@ -32,6 +32,12 @@ test('macOS DMG layout is written to a writable image before final compression',
assert.match(buildSource, /hdiutil convert[\s\S]*-format UDZO/);
});
+test('macOS batch build handles an omitted Finder flag and propagates profile failures', () => {
+ assert.match(buildSource, /SKIP_FINDER="\$\{WORKDADDY_SKIP_FINDER:-\}"/);
+ assert.match(buildSource, /WORKDADDY_BUILD_PROFILE="\$profile" bash "\$0" \|\| exit \$\?/);
+ assert.match(buildSource, /if \[ -z "\$SKIP_FINDER" \]; then/);
+});
+
test('macOS DMG uses a fixed-size SVG master for its arrow artwork', () => {
assert.equal(fs.existsSync(backgroundPath), true, 'missing DMG SVG background');
const svg = fs.readFileSync(backgroundPath, 'utf8');
diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.js
index a7ec24a..6e6b08f 100644
--- a/test/renderer-escaping.test.js
+++ b/test/renderer-escaping.test.js
@@ -84,14 +84,22 @@ test('model, wallpaper, and account cards escape each dynamic HTML sink', () =>
const accounts = sourceBetween('function render(data)', 'function updateAccountSummary()');
assert.equal((accounts.match(/escAttr\(a\.uid\)/g) || []).length, 2);
assert.equal((accounts.match(/escAttr\(a\.nickname \|\| '未命名'\)/g) || []).length, 2);
- assert.match(accounts, /var idVal = a\.phone \? esc\(a\.phone\) : \(a\.uin \? esc\(a\.uin\) : '-'\)/);
- assert.match(accounts, /wbs-name">' \+ esc\(a\.nickname/);
- assert.match(accounts, /wbs-val">' \+ idVal/);
+ assert.match(accounts, /var nameVal = state\.mask \? maskAccountName\(rawName\) : rawName;/);
+ assert.match(accounts, /var idVal = state\.mask \? maskAccountId\(rawId\) : rawId;/);
+ assert.match(accounts, /wbs-name">' \+ esc\(nameVal\)/);
+ assert.match(accounts, /wbs-val">' \+ esc\(idVal\)/);
assert.match(accounts, /wbs-val[^\n]+esc\(ts\.label\)/);
assert.doesNotMatch(accounts, /data-(?:uid|name)="' \+ a\./);
assert.doesNotMatch(accounts, /var idVal = a\.phone \? a\.phone/);
});
+test('account masking preference persists per WorkDaddy profile', () => {
+ assert.match(source, /var WBS_ACCOUNT_MASK_KEY = 'workdaddy\.account\.mask\.' \+ PROFILE_ID;/);
+ assert.match(source, /localStorage\.getItem\(WBS_ACCOUNT_MASK_KEY\) === '1'/);
+ const toggle = sourceBetween('function toggleAccountMask()', 'function refresh()');
+ assert.match(toggle, /localStorage\.setItem\(WBS_ACCOUNT_MASK_KEY, state\.mask \? '1' : '0'\)/);
+});
+
test('dynamic error and check-in messages are escaped before HTML insertion', () => {
assert.match(source, /wbs-checkin-tag fail[^\n]+esc\(msg\)/);
assert.match(source, /会话加载失败: ' \+ esc\(e\.message \|\| e\)/);
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index 72a8923..8e77ffb 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -168,6 +168,55 @@ test('account switching refreshes WorkBuddy after replacing auth without restart
assert.match(lib, /retireLogoutMarker\(log\);/);
});
+test('WorkDaddy-triggered reload injects on the new main execution context before page load', () => {
+ const script = read('daemon.js');
+ const reloadStart = script.indexOf('async function reloadWorkBuddyPage()');
+ const reloadEnd = script.indexOf('\n// 切换账号后自动打开', reloadStart);
+ const reload = script.slice(reloadStart, reloadEnd);
+ const eventsStart = script.indexOf('function onCdpEvent(method, params)');
+ const eventsEnd = script.indexOf('\nasync function cdpLoop()', eventsStart);
+ const events = script.slice(eventsStart, eventsEnd);
+
+ assert.match(reload, /Page\.getFrameTree/);
+ assert.match(reload, /const pending = armPendingReloadInjection\(frameId\)/);
+ assert.ok(reload.indexOf('armPendingReloadInjection') < reload.indexOf("cdpSend('Page.reload'"), 'reload must be armed before navigation starts');
+ assert.ok(reload.indexOf("cdpSend('Page.reload'") < reload.indexOf('await pending.ready'), 'auto-copy callers must wait until the widget is mounted');
+ assert.match(events, /case 'Runtime\.executionContextCreated'/);
+ assert.match(events, /auxData\.isDefault === true/);
+ assert.match(events, /auxData\.frameId === pendingReloadInjection\.frameId/);
+ assert.match(events, /runPendingReloadInjection\('reload-context', context\.id\)/);
+ assert.match(events, /case 'Page\.frameNavigated'/);
+ assert.match(events, /pendingReloadInjection\.frameId = frame\.id/);
+ assert.match(events, /case 'Page\.loadEventFired'/);
+ assert.match(events, /runPendingReloadInjection\('reload-page-load'\)/);
+ assert.match(events, /suppressPageLoadInjectionForNavigation === mainFrameNavigationSerial/);
+
+ const switchStart = script.indexOf("if (req.method === 'POST' && p === '/api/switch')");
+ const switchRoute = script.slice(switchStart, switchStart + 9000);
+ const switchWrite = switchRoute.indexOf('switchTo(DATA_DIR, uid, log)');
+ assert.notEqual(switchWrite, -1);
+ assert.doesNotMatch(switchRoute.slice(0, switchWrite), /buildAutoCopyPlan\(/, 'session planning must not delay auth replacement and renderer reload');
+ assert.ok(switchRoute.indexOf('await reloadWorkBuddyPage()') < switchRoute.indexOf('startAutoCopyJob('), 'widget readiness must precede the synchronous auto-copy queue');
+ const autoCopyStart = script.indexOf('function startAutoCopyJob(');
+ const autoCopyEnd = script.indexOf('\nfunction publicAutoCopyJob(', autoCopyStart);
+ const autoCopy = script.slice(autoCopyStart, autoCopyEnd);
+ assert.ok((autoCopy.match(/await yieldAutoCopyToRenderer\(\)/g) || []).length >= 2, 'auto-copy must yield before planning and each synchronous file batch');
+
+ const yieldStart = script.indexOf('async function yieldAutoCopyToRenderer()');
+ const syncStart = script.indexOf('async function syncAutoCopyLineage(', yieldStart);
+ const yieldHelper = script.slice(yieldStart, syncStart);
+ assert.match(yieldHelper, /setImmediate/);
+ assert.match(yieldHelper, /rendererReloadPriorityPromise/);
+ assert.match(yieldHelper, /await reloadPriority/);
+ assert.match(yieldHelper, /pendingReloadInjection/);
+ assert.match(yieldHelper, /await pending\.ready/);
+ const syncEnd = script.indexOf('\nconst MAX_SESSION_EXPORT_BYTES', syncStart);
+ const syncLineage = script.slice(syncStart, syncEnd);
+ assert.ok((syncLineage.match(/await yieldAutoCopyToRenderer\(\)/g) || []).length >= 2, 'lineage scans and copies must pause for renderer reloads');
+ assert.match(switchRoute, /const releaseRendererReload = body\.reload \? beginRendererReloadPriority\(\) : null/);
+ assert.match(switchRoute, /finally \{\s*if \(releaseRendererReload\) releaseRendererReload\(\)/);
+});
+
test('account switching retires WorkBuddy logout marker', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-auth-'));
const authFile = path.join(dir, 'workbuddy-desktop.info');
@@ -1052,7 +1101,7 @@ test('automatic session copy includes workspace-only rules when the initial plan
assert.match(daemon, /const sourceRules = sourceUid \? getAutoCopyRules\(DATA_DIR, sourceUid\)/);
assert.match(daemon, /hasSourceAutoCopyRules/);
assert.match(daemon, /hasPendingAutoCopyTo\(uid\)/);
- assert.match(daemon, /startAutoCopyJob\(sourceUid, uid, autoCopyPlan\)/);
+ assert.match(daemon, /startAutoCopyJob\(sourceUid, uid, \[\]\)/);
assert.match(daemon, /syncAutoCopyLineage\(src\.lineageId, targetUid\)/);
assert.match(daemon, /selectLatestAutoCopyMember\(live\)/);
assert.match(daemon, /ensureAutoCopySessions\(DATA_DIR, source, lineageSessionIds, \{ enabled: !rules\.allSessions \}\)/);
diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.js
index 0bbfdd7..f22c996 100644
--- a/test/windows-native-flow.test.js
+++ b/test/windows-native-flow.test.js
@@ -33,7 +33,7 @@ test('Windows shortcuts use a versioned icon path to invalidate the shell icon c
assert.doesNotMatch(installer, /IconFilename: "\{app\}\\scripts\\WorkDaddy\.ico"/);
});
-test('normal Windows startup does not use Explorer de-elevation or CIM', () => {
+test('normal Windows startup does not use PowerShell de-elevation or CIM', () => {
const launcher = read('scripts/win-launcher.js');
const watchdog = read('scripts/watchdog.js');
@@ -47,6 +47,27 @@ test('normal Windows startup does not use Explorer de-elevation or CIM', () => {
assert.doesNotMatch(watchdog, /Get-CimInstance|windows-process-boundary|pending\.json/);
});
+test('native launcher retries inherited elevation with the verified desktop Explorer token', () => {
+ const source = read('scripts/windows-native/main.go');
+ const main = source.slice(source.indexOf('func main()'));
+
+ assert.match(source, /GetShellWindow/);
+ assert.match(source, /GetWindowThreadProcessId/);
+ assert.match(source, /CreateProcessWithTokenW/);
+ assert.match(source, /CreateEnvironmentBlock/);
+ assert.match(source, /DestroyEnvironmentBlock/);
+ assert.match(source, /createUnicodeEnvironment, environment/);
+ assert.match(source, /queryProcessPath\(shellPID\)/);
+ assert.match(source, /explorer\.exe/);
+ assert.match(source, /tokenIsElevated\(shellToken\)/);
+ assert.match(main, /--desktop-shell-relaunch/);
+ assert.ok(
+ main.indexOf('relaunchWithDesktopToken') < main.indexOf('runNodeLauncher'),
+ 'native privilege normalization must happen before starting Node lifecycle processes'
+ );
+ assert.doesNotMatch(main, /powershell|windows-relaunch-standard/i);
+});
+
test('WorkBuddy GUI startup stays visible while the watchdog stays hidden', () => {
const launcher = read('scripts/win-launcher.js');
const watchdog = read('scripts/watchdog.js');
@@ -320,3 +341,35 @@ test('native CDP startup detects failed child launches instead of waiting for th
assert.match(wait, /windows-native-launcher-workbuddy-exit/);
assert.match(wait, /stopNativeWorkBuddy\(\)[\s\S]*start\(\)/);
});
+
+test('denied elevated lifecycle is preserved after an authenticated status proof', () => {
+ const source = read('scripts/windows-native/main.go');
+ assert.match(source, /exitPreserveLifecycle\s*=\s*13/);
+ assert.match(source, /func authenticatedElevatedDaemonStatus\(profile string\)/);
+ assert.match(source, /\.api-token/);
+ assert.match(source, /len\(token\) != 64/);
+ assert.match(source, /api\/status/);
+ assert.match(source, /X-WorkDaddy-Token/);
+ assert.match(source, /privil[e]ge\s*!=\s*"elevated"|Privilege\s*!=\s*"elevated"/);
+ assert.match(source, /status\.Profile\.ID != profile/);
+ assert.match(source, /listenerPidOnPort\(port\)/);
+ assert.match(source, /netstat/);
+
+ const helperStart = source.indexOf('if hasArgument("--stop-lifecycle")');
+ const helperEnd = source.indexOf('\n\tif hasArgument("--self-test")', helperStart);
+ assert.ok(helperStart >= 0 && helperEnd > helperStart);
+ const block = source.slice(helperStart, helperEnd);
+ assert.match(block, /code == exitAccessDenied && !elevated/);
+ assert.match(block, /authenticatedElevatedDaemonStatus\(profile\)/);
+ assert.match(block, /exitPreserveLifecycle/);
+ assert.doesNotMatch(block, /if elevated \{[\s\S]*return true, exitAccessDenied/);
+});
+
+test('installer continues with a preserved lifecycle instead of blocking', () => {
+ const installer = read('scripts/win/workdaddy.iss');
+ assert.match(installer, /PreserveExistingLifecycle: Boolean/);
+ assert.match(installer, /function ShouldReplaceRuntime/);
+ assert.match(installer, /Result := not PreserveExistingLifecycle/);
+ assert.match(installer, /Check: ShouldReplaceRuntime/);
+ assert.match(installer, /if ResultCode = 13 then[\s\S]*PreserveExistingLifecycle := True/);
+});