Skip to content

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

修复问题

[email protected]1dc71c23e30e
diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.sh
index 468b7a5..b878497 100644
--- a/scripts/build-win-zip.sh
+++ b/scripts/build-win-zip.sh
@@ -42,6 +42,10 @@ rm -f "$OUT"
# 3.1) 顶层入口(zip 根):Install-WorkDaddy.cmd / Start-WorkDaddy.cmd
cp scripts/Install-WorkDaddy.cmd "$STAGE/Install-WorkDaddy.cmd"
cp scripts/Start-WorkDaddy.cmd "$STAGE/Start-WorkDaddy.cmd"
+# 3.1a) Windows 故障排查提示词(供用户在安装失败时交给修复 agent)
+if [ -f "$DIR/安装失败自主解决提示词.txt" ]; then
+ cp "$DIR/安装失败自主解决提示词.txt" "$STAGE/安装失败自主解决提示词.txt"
+fi
# 3.2) scripts\ 本体(含 node_modules/ws、builtin)
cp -R scripts "$STAGE/scripts"
# 3.2a) Logo 图标:放入 scripts\(install-win.ps1 从 SrcDir 同名找并复制到安装目录根)
@@ -58,21 +62,45 @@ rm -rf "$STAGE/scripts/win/probe" "$STAGE/scripts/win/probe/"* 2>/dev/null || tr
rm -f "$STAGE/scripts/Install-WorkDaddy.cmd" "$STAGE/scripts/Start-WorkDaddy.cmd" 2>/dev/null || true
find "$STAGE" -name '*.log' -delete 2>/dev/null || true
find "$STAGE" -name '.DS_Store' -delete 2>/dev/null || true
-# 3.3.5) 非 ASCII 文件名守护(必杀项)
-# Windows 的 .NET Expand-Archive 解压含非 ASCII 条目名的 zip 时,文件名按 OEM 代码页解码成
-# 非法字符,直接抛「路径中具有非法字符」→ Windows 自动更新在解压阶段崩溃,备份/替换/回滚全失效。
-# 发布包严禁混入中文/特殊字符文件名(曾出现过「安装失败自主解决提示词.txt」导致 1.0.6 更新必炸)。
-if find "$STAGE" -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C grep -q '[^ -~]'; then
- echo "==> ERROR: 发布包包含非 ASCII 文件路径(.NET Expand-Archive 解压必失败),已终止打包!"
- find "$STAGE" -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C grep '[^ -~]' | head -20
+# 3.3.5) 非 ASCII 文件名守护:仅允许根目录的故障排查提示词,其余路径必须保持 ASCII。
+# macOS 自带 Info-ZIP 会使用 UTF-8 条目写入;安装/更新脚本本身仍全部使用 ASCII 路径。
+NON_ASCII_PATHS="$(find "$STAGE" -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C grep '[^ -~]' || true)"
+UNEXPECTED_NON_ASCII="$(printf '%s\n' "$NON_ASCII_PATHS" | LC_ALL=C grep -v '安装失败自主解决提示词\.txt$' || true)"
+if [ -n "$UNEXPECTED_NON_ASCII" ]; then
+ echo "==> ERROR: 发布包包含未批准的非 ASCII 文件路径,已终止打包!"
+ printf '%s\n' "$UNEXPECTED_NON_ASCII" | head -20
rm -rf "$STAGE"
exit 3
fi
-echo "==> 非 ASCII 文件名守护通过(全 ASCII 路径)"
-# 3.4) 打包:zip 优先;无 zip 的环境用 Windows 系统自带 bsdtar(生成标准 / 分隔符 zip)。
-# 绝不用 PowerShell Compress-Archive —— 它产出反斜杠分隔符,非标准 zip 会被解压工具把
-# scripts\daemon.js 当单个文件名,导致解压结构错乱、入口秒退。
-if command -v zip >/dev/null 2>&1; then
+echo "==> 非 ASCII 文件名守护通过(仅包含批准的故障排查提示词)"
+# 3.4) 打包:优先使用 Python zipfile,确保中文提示词写入 UTF-8 文件名标记。
+# macOS 自带 zip 会把中文文件名按本地代码页写入,Windows/Python 解压后会出现乱码。
+# 没有 Python 且需要中文提示词时直接失败,避免生成名字损坏的发布包。
+if command -v python3 >/dev/null 2>&1; then
+ python3 - "$STAGE" "$DIR/$OUT" <<'PY'
+import os
+import sys
+import zipfile
+
+stage, output = sys.argv[1:]
+with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
+ for root, dirs, files in os.walk(stage):
+ dirs.sort()
+ files.sort()
+ for name in dirs:
+ source = os.path.join(root, name)
+ arcname = os.path.relpath(source, stage).replace(os.sep, '/') + '/'
+ archive.write(source, arcname)
+ for name in files:
+ source = os.path.join(root, name)
+ arcname = os.path.relpath(source, stage).replace(os.sep, '/')
+ archive.write(source, arcname)
+PY
+elif [ -f "$STAGE/安装失败自主解决提示词.txt" ]; then
+ echo "==> ERROR: 包含中文故障排查提示词,但当前环境没有 python3,无法生成 UTF-8 ZIP。"
+ rm -rf "$STAGE"
+ exit 4
+elif command -v zip >/dev/null 2>&1; then
(cd "$STAGE" && zip -r -q "$DIR/$OUT" .)
else
tar -a -cf "$DIR/$OUT" -C "$STAGE" .
@@ -88,4 +116,4 @@ echo "==> 完成: $(ls -lh "$OUT" | awk '{print $5}')"
echo ""
echo "在 Windows 上:解压 zip 后,在顶层直接双击 Install-WorkDaddy.cmd 一键安装(自动建桌面图标+自启);"
echo "日常启动双击 Start-WorkDaddy.cmd 或桌面 WorkDaddy 图标。"
-echo "每 6 小时自动检查更新(GitHub Releases 需同时上传 .dmg 与 -win64.zip 两个资产,Windows 自动静默升级)。"
\ No newline at end of file
+echo "每 6 小时自动检查更新(GitHub Releases 需同时上传 .dmg 与 -win64.zip 两个资产,Windows 自动静默升级)。"
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 2c48d94..b8fe4c9 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -80,7 +80,7 @@ const {
enableModelBackup,
} = require('./lib.js');
const { extractCreditSegments, sortCreditSegments } = require('./credit-segments.js');
-const { captureException } = require('./sentry-report.js');
+const { captureException, captureMessage } = require('./sentry-report.js');
const DATA_DIR = defaultDataDir();
// 版本号:改动 daemon/inject/theme-patches/builtin 资产后递增,launcher 检测到运行中版本不一致会强制用 app 内置代码重启
@@ -110,7 +110,8 @@ const DATA_DIR = defaultDataDir();
// 另:daemon 单实例锁、启动竞态修复、注入结果校验与本地诊断快照;
// 修复跨平台自动更新并展示按到期时间拆分的积分明细
// 1.0.7:兼容无全局 WebSocket 的 Node 18/20,使用内置 ws 建立 CDP
-// 1.0.8:去除 launchd 重定向造成的重复日志,并记录 launcher 选择的 Node 运行时
+// 1.0.8:Windows 数据目录锁文件遇到权限/残留 ACL 时,降级到用户临时目录锁,避免 daemon 未捕获退出
+// 历史:去除 launchd 重定向造成的重复日志,并记录 launcher 选择的 Node 运行时
// 1.0.9:诊断快照中的常见 token 字段脱敏
// 1.0.10:daemon.log 按 10 MB 滚动保留最近 3 份,避免长期运行无限增长
// 1.0.11:「登录新账号」新增「无感登录」(OAuth state 轮询采集,流程同 workbuddy-switch),
@@ -128,8 +129,8 @@ const DATA_DIR = defaultDataDir();
// 1.0.19:官方模型批量删除、模型卡片稳定布局与固定 650px 面板
// 1.0.20:模型卡片悬浮操作、官方连通测试、完整长度脱敏 API Key
// 1.0.21:模型页改为当前/备选模型列表风格,去除刷新入口并优化字段排版
-const DAEMON_VERSION = '1.0.7';
-const DAEMON_BUILD_ID = 'release-1.0.7-20260822';
+const DAEMON_VERSION = '1.0.8';
+const DAEMON_BUILD_ID = 'release-1.0.8-20260822';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -806,30 +807,72 @@ function log(...args) {
}
}
+function isLockPermissionError(error) {
+ return !!error && ['EACCES', 'EPERM', 'EROFS'].includes(error.code);
+}
+
+function reportDaemonLockFallback(error) {
+ const code = error && error.code ? error.code : 'unknown';
+ log(`[lock] 数据目录锁不可用 (${code}),已使用临时目录锁`);
+ captureMessage('daemon 使用临时目录锁(数据目录锁权限不可用)', {
+ level: 'warning',
+ stage: 'daemon-lock-fallback',
+ extra: { lockErrorCode: code, lockFallback: true },
+ }).catch(() => {});
+}
+
// launchd 应只启动一个 daemon;启动器的 nohup 兜底和 launchd 异步拉起可能短暂重叠,
// 用原子创建锁文件把这类竞态变成可观测的单实例退出,而不是两个进程同时清理/注入页面。
+// Windows 数据目录锁不可写时,使用同一台机器用户临时目录中的哈希锁继续保证单实例。
function acquireDaemonLock() {
const payload = JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), version: DAEMON_VERSION, buildId: DAEMON_BUILD_ID });
- for (let attempt = 0; attempt < 2; attempt++) {
- try {
- daemonLockFd = fs.openSync(DAEMON_LOCK_FILE, 'wx', 0o600);
- fs.writeFileSync(daemonLockFd, payload, 'utf8');
- log(`[lock] daemon 单实例锁已获取 (pid=${process.pid})`);
- return true;
- } catch (e) {
- if (e.code !== 'EEXIST') throw e;
- let owner = null;
- try { owner = JSON.parse(fs.readFileSync(DAEMON_LOCK_FILE, 'utf8')); } catch (_) {}
- const ownerPid = Number(owner && owner.pid);
- let alive = false;
- if (ownerPid > 0 && ownerPid !== process.pid) {
- try { process.kill(ownerPid, 0); alive = true; } catch (_) {}
- }
- if (alive) {
- process.stdout.write(`[${new Date().toISOString()}] [lock] 已有 daemon 运行 (pid=${ownerPid}),当前进程退出\n`);
- return false;
+ const candidates = [DAEMON_LOCK_FILE];
+ if (IS_WIN && DAEMON_LOCK_FALLBACK_FILE !== DAEMON_LOCK_FILE) candidates.push(DAEMON_LOCK_FALLBACK_FILE);
+ let fallbackReason = null;
+
+ for (const lockPath of candidates) {
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ daemonLockFd = fs.openSync(lockPath, 'wx', 0o600);
+ fs.writeFileSync(daemonLockFd, payload, 'utf8');
+ daemonLockPath = lockPath;
+ if (lockPath !== DAEMON_LOCK_FILE) reportDaemonLockFallback(fallbackReason || { code: 'EEXIST' });
+ log(`[lock] daemon 单实例锁已获取 (pid=${process.pid})`);
+ return true;
+ } catch (e) {
+ if (daemonLockFd !== null) {
+ try { fs.closeSync(daemonLockFd); } catch (_) {}
+ daemonLockFd = null;
+ }
+ if (e.code === 'EEXIST') {
+ let owner = null;
+ try { owner = JSON.parse(fs.readFileSync(lockPath, 'utf8')); } catch (_) {}
+ const ownerPid = Number(owner && owner.pid);
+ let alive = false;
+ if (ownerPid > 0 && ownerPid !== process.pid) {
+ try { process.kill(ownerPid, 0); alive = true; } catch (_) {}
+ }
+ if (alive) {
+ process.stdout.write(`[${new Date().toISOString()}] [lock] 已有 daemon 运行 (pid=${ownerPid}),当前进程退出\n`);
+ return false;
+ }
+ try {
+ fs.unlinkSync(lockPath);
+ } catch (unlinkError) {
+ if (IS_WIN && lockPath === DAEMON_LOCK_FILE && isLockPermissionError(unlinkError)) {
+ fallbackReason = unlinkError;
+ break;
+ }
+ return false;
+ }
+ continue;
+ }
+ if (IS_WIN && lockPath === DAEMON_LOCK_FILE && isLockPermissionError(e)) {
+ fallbackReason = e;
+ break;
+ }
+ throw e;
}
- try { fs.unlinkSync(DAEMON_LOCK_FILE); } catch (_) { return false; }
}
}
return false;
@@ -840,8 +883,8 @@ function releaseDaemonLock() {
try { fs.closeSync(daemonLockFd); } catch (_) {}
daemonLockFd = null;
try {
- const owner = JSON.parse(fs.readFileSync(DAEMON_LOCK_FILE, 'utf8'));
- if (Number(owner.pid) === process.pid) fs.unlinkSync(DAEMON_LOCK_FILE);
+ const owner = JSON.parse(fs.readFileSync(daemonLockPath, 'utf8'));
+ if (Number(owner.pid) === process.pid) fs.unlinkSync(daemonLockPath);
} catch (_) {}
}
@@ -882,7 +925,13 @@ const cdp = {
const DIAGNOSTICS_FILE = path.join(DATA_DIR, 'diagnostics-latest.json');
const DAEMON_LOCK_FILE = path.join(DATA_DIR, '.daemon.lock');
+// Windows 上旧版可能以不同权限创建锁文件,导致当前用户无法覆盖;临时锁按数据目录哈希隔离。
+const DAEMON_LOCK_FALLBACK_FILE = path.join(
+ os.tmpdir(),
+ 'WorkDaddy-daemon-' + crypto.createHash('sha256').update(path.resolve(DATA_DIR)).digest('hex').slice(0, 16) + '.lock'
+);
let daemonLockFd = null;
+let daemonLockPath = DAEMON_LOCK_FILE;
// 注入节流:仅避免 connect 与 loadEventFired 在同一瞬间(<1.5s)重复注入导致闪烁;
// 但每次页面刷新(含 Command+R)都应重新注入最新代码,因此不用“一次加载只注入一次”的布尔去重,
// 否则 Electron 重载未触发 loadEventFired 时会遗留旧版本组件。
@@ -3843,8 +3892,9 @@ function handleApi(req, res) {
const rangeMs = sessionRangeMs(range);
const clauses = ["deleted_at IS NULL"];
if (uid) clauses.push("user_id = '" + uid.replace(/'/g, "''") + "'");
- if (rangeMs) clauses.push('created_at >= ' + rangeMs);
- return sqliteQuery("SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, project_id FROM sessions WHERE " + clauses.join(' AND ') + " ORDER BY created_at DESC;")
+ if (rangeMs) clauses.push('COALESCE(last_activity_at, updated_at, created_at) >= ' + rangeMs);
+ // 时间筛选和排序按最近活动/修改时间;旧记录缺字段时回退到创建时间。
+ return sqliteQuery("SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, project_id FROM sessions WHERE " + clauses.join(' AND ') + " ORDER BY COALESCE(last_activity_at, updated_at, created_at) DESC, created_at DESC;")
.then((rows) => {
const rulesByUid = {};
rows.forEach((row) => {
diff --git a/scripts/inject.js b/scripts/inject.js
index 300b176..3078fbd 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -1591,7 +1591,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var url = '/api/sessions?range=' + (sessionsState.range || '7d');
if (sessionsState.uid !== undefined) url += '&uid=' + encodeURIComponent(sessionsState.uid);
api(url).then(function (d) {
- sessionsState.list = (d && d.sessions) || [];
+ // 任务会话不支持复制,也不参与批量操作;从会话页数据源直接隐藏,避免出现不可操作的只读分组。
+ sessionsState.list = ((d && d.sessions) || []).filter(function (s) { return !isTaskSessionRecordUI(s.cwd); });
sessionsState.autoCopy = (d && d.autoCopy) || null;
sessionsState.selected = {};
sessionsState.wsExpanded = {};
@@ -1656,7 +1657,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var title = s.custom_title || s.title || '(无标题)';
html += '<div class="wbs-sess-row">' +
'<span class="wbs-sess-main"><span class="wbs-sess-title">' + esc(title) + '</span>' +
- '<span class="wbs-sess-meta">' + fmtHumanTime(s.created_at) + '</span></span>' +
+ '<span class="wbs-sess-meta">' + fmtHumanTime(s.last_activity_at || s.updated_at || s.created_at) + '</span></span>' +
'</div>';
});
if (taskMore > 0) html += '<button class="wbs-sess-more" type="button" data-ws="__TASKS__">展开 ' + Math.min(taskMore, SESS_WS_STEP) + ' 条(剩余 ' + taskMore + ')</button>';
@@ -1686,7 +1687,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
html += '<div class="wbs-sess-row">' +
(batch ? '<input type="checkbox" class="wbs-sess-check" data-id="' + escAttr(s.id) + '"' + sel + '>' : '') +
'<span class="wbs-sess-main"><span class="wbs-sess-title">' + esc(title) + '</span>' +
- '<span class="wbs-sess-meta">' + fmtHumanTime(s.created_at) + '</span></span>' +
+ '<span class="wbs-sess-meta">' + fmtHumanTime(s.last_activity_at || s.updated_at || s.created_at) + '</span></span>' +
(batch ? '' : autoCopyButton('session', s.id, s.user_id, marked, inherited)) +
'</div>';
});
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
index 280cba3..ebc0196 100644
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@ -31,6 +31,7 @@ const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');
const ELEVATED_HELPER_MODE = process.argv.includes('--inject-helper');
// 便携版/低速磁盘上的 WorkBuddy 首次启动可能超过 20 秒;超时只应在足够长的窗口后报告。
const CDP_STARTUP_TIMEOUT_MS = 60000;
+const WORKBUDDY_PROCESS_NAMES = new Set(['workbuddy.exe', 'codebuddy.exe', 'workbuddyai.exe']);
function log(...args) {
const line = `[launcher] ${new Date().toISOString()} ${args.join(' ')}\n`;
@@ -156,12 +157,14 @@ async function isWorkBuddyCdp() {
return isWorkBuddyCdpAt(CDP_PORT);
}
-async function isWorkBuddyCdpAt(port) {
+async function isWorkBuddyCdpAt(port, binary = null) {
const version = await httpGet(port, '/json/version');
if (!version || version.status !== 200) return false;
try {
const info = JSON.parse(version.body || '{}');
- return /workbuddy|codebuddy/i.test([info.Browser, info['User-Agent']].filter(Boolean).join(' '));
+ if (/workbuddy|codebuddy/i.test([info.Browser, info['User-Agent']].filter(Boolean).join(' '))) return true;
+ // 某些 WorkBuddy 版本隐藏 Electron 品牌;端口响应 + 同安装目录进程的精确参数仍可确认归属。
+ return Boolean(binary && workBuddyProcesses(binary).some((p) => processCdpPort(p) === Number(port)));
} catch (_) { return false; }
}
@@ -193,6 +196,70 @@ function psOut(cmd) {
} catch (_) { return ''; }
}
+// 进程名并不总是可靠:Electron 的单实例宿主可能以 CodeBuddy.exe 或辅助进程名存在。
+// 通过 CIM 同时拿到路径、父 PID 和命令行,只在本地诊断使用;命令行正文绝不写入日志/Sentry。
+function getWorkBuddyProcesses() {
+ const command = [
+ '$names=@("WorkBuddy.exe","CodeBuddy.exe","WorkBuddyAI.exe")',
+ 'Get-CimInstance Win32_Process -ErrorAction SilentlyContinue',
+ '| Where-Object { $names -contains $_.Name }',
+ '| Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine',
+ '| ConvertTo-Json -Compress',
+ ].join(' ');
+ const raw = psOut(command).trim();
+ if (!raw) return [];
+ try {
+ const parsed = JSON.parse(raw);
+ return (Array.isArray(parsed) ? parsed : [parsed]).filter((p) => p && Number(p.ProcessId) > 0);
+ } catch (_) {
+ return [];
+ }
+}
+
+function sameWindowsPath(a, b) {
+ if (!a || !b) return false;
+ return String(a).replace(/[\\/]+$/, '').toLowerCase() === String(b).replace(/[\\/]+$/, '').toLowerCase();
+}
+
+function workBuddyProcesses(binary = null) {
+ return getWorkBuddyProcesses().filter((p) => {
+ if (!WORKBUDDY_PROCESS_NAMES.has(String(p.Name || '').toLowerCase())) return false;
+ if (!binary || !p.ExecutablePath) return true;
+ // WorkBuddy 可能把 Electron 主进程拆成同目录下的 CodeBuddy.exe/辅助宿主;按安装目录归组。
+ return sameWindowsPath(p.ExecutablePath, binary) ||
+ sameWindowsPath(path.dirname(p.ExecutablePath), path.dirname(binary));
+ });
+}
+
+function processCdpPort(process) {
+ const commandLine = String(process && process.CommandLine || '');
+ const match = commandLine.match(/(?:^|\s)--remote-debugging-port(?:=|\s+)(\d+)(?:\s|$)/i);
+ return match ? Number(match[1]) : 0;
+}
+
+function processHasCdpArg(process, port = CDP_PORT) {
+ return processCdpPort(process) === Number(port);
+}
+
+function processDiagnostics(binary = null) {
+ return workBuddyProcesses(binary).map((p) => ({
+ pid: Number(p.ProcessId),
+ parentPid: Number(p.ParentProcessId) || null,
+ name: String(p.Name || ''),
+ executable: path.basename(String(p.ExecutablePath || '')),
+ hasCommandLine: Boolean(String(p.CommandLine || '').trim()),
+ hasCdpArg: processCdpPort(p) > 0,
+ cdpPort: processCdpPort(p) || null,
+ hasExpectedCdpArg: processHasCdpArg(p),
+ }));
+}
+
+function logProcessDiagnostics(binary, prefix = 'WorkBuddy 进程诊断') {
+ const rows = processDiagnostics(binary);
+ log(prefix + ': ' + (rows.length ? JSON.stringify(rows) : '无匹配进程'));
+ return rows;
+}
+
function readDaemonVersion() {
try {
const src = fs.readFileSync(path.join(SCRIPTS_DIR, 'daemon.js'), 'utf8');
@@ -350,14 +417,19 @@ function stopDaemonByPort() {
}
// ---------- 2/3. WorkBuddy CDP 处理 ----------
-function workBuddyRunning() {
+function workBuddyRunning(binary = null) {
+ const processes = workBuddyProcesses(binary);
+ if (processes.length) return true;
+ // CIM 失败时保守回退到 tasklist,避免误判为已退出后把启动参数交给旧实例。
try {
- const r = spawnSync(
- 'tasklist',
- ['/FI', 'IMAGENAME eq WorkBuddy.exe', '/FO', 'CSV', '/NH'],
- { encoding: 'utf8', timeout: 5000, windowsHide: true }
+ const filters = Array.from(WORKBUDDY_PROCESS_NAMES).map((name) =>
+ spawnSync('tasklist', ['/FI', 'IMAGENAME eq ' + name, '/FO', 'CSV', '/NH'], {
+ encoding: 'utf8', timeout: 5000, windowsHide: true,
+ })
);
- return r.status === 0 && /"WorkBuddy\.exe"/i.test(r.stdout || '');
+ return filters.some((r) => r.status === 0 && WORKBUDDY_PROCESS_NAMES.has(
+ String(r.stdout || '').match(/"([^"]+\.exe)"/i)?.[1]?.toLowerCase() || ''
+ ));
} catch (_) {
return true;
}
@@ -380,21 +452,31 @@ function runTaskkill(args) {
});
}
-async function waitForWorkBuddyExit(timeoutMs) {
+async function waitForWorkBuddyExit(timeoutMs, binary = null) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
- if (!workBuddyRunning()) return true;
+ if (!workBuddyRunning(binary)) return true;
await sleep(200);
}
- return !workBuddyRunning();
+ return !workBuddyRunning(binary);
}
-async function quitWorkBuddy() {
- if (!workBuddyRunning()) return true;
- await runTaskkill(['/IM', 'WorkBuddy.exe']);
- if (await waitForWorkBuddyExit(1800)) return true;
- await runTaskkill(['/F', '/T', '/IM', 'WorkBuddy.exe']);
- if (await waitForWorkBuddyExit(4000)) return true;
+async function quitWorkBuddy(binary) {
+ const initial = workBuddyProcesses(binary);
+ if (!initial.length && !workBuddyRunning(binary)) return true;
+
+ // 按实际 PID 精确结束安装目录中的进程树,避免 /IM 只结束主进程而留下单实例宿主。
+ const pids = new Set(initial.map((p) => String(Number(p.ProcessId))).filter((pid) => pid !== '0'));
+ if (!pids.size) pids.add('0');
+ for (const pid of pids) {
+ if (pid !== '0') await runTaskkill(['/T', '/PID', pid]);
+ }
+ if (await waitForWorkBuddyExit(2500, binary)) return true;
+ for (const pid of pids) {
+ if (pid !== '0') await runTaskkill(['/F', '/T', '/PID', pid]);
+ }
+ if (await waitForWorkBuddyExit(5500, binary)) return true;
+ logProcessDiagnostics(binary, '结束 WorkBuddy 后仍有进程');
throw new Error('无法确认 WorkBuddy 已退出');
}
@@ -427,22 +509,77 @@ function launchWorkBuddy(wb) {
);
if (result.status === 0) {
log('WorkBuddy 已通过 Explorer ShellExecute 以当前用户权限启动');
- return true;
+ return { method: 'shell-execute' };
}
log('ShellExecute 启动 WorkBuddy 失败,改用 explorer.exe 兜底 (code=' + result.status + ')');
try {
const shell = spawn('explorer.exe', [wb, args], { detached: true, stdio: 'ignore', windowsHide: true });
shell.unref();
- return true;
+ return { method: 'explorer-fallback' };
} catch (e) {
log('explorer.exe 启动 WorkBuddy 失败: ' + e.message);
}
}
- const child = spawn(wb, [args], { detached: true, stdio: 'ignore', windowsHide: true });
+ const child = spawn(wb, [args], {
+ cwd: path.dirname(wb), detached: true, stdio: 'ignore', windowsHide: true,
+ });
child.on('error', (e) => { log('启动 WorkBuddy 失败: ' + e.message); });
child.unref();
- return true;
+ return { method: 'node-spawn', pid: child.pid };
+}
+
+async function waitForWorkBuddyCdp(binary) {
+ const deadline = Date.now() + CDP_STARTUP_TIMEOUT_MS;
+ let retryWithoutCdpArg = false;
+ let lastDiagnosticAt = 0;
+ let launchStartedAt = Date.now();
+
+ const start = () => {
+ const launched = launchWorkBuddy(binary);
+ launchStartedAt = Date.now();
+ log('WorkBuddy 启动请求已派发 method=' + launched.method + ' expectedPort=' + CDP_PORT +
+ (launched.pid ? ' pid=' + launched.pid : ''));
+ };
+ start();
+
+ while (Date.now() < deadline) {
+ await sleep(1000);
+ if (await isWorkBuddyCdpAt(CDP_PORT, binary)) return true;
+
+ const elapsed = Date.now() - launchStartedAt;
+ const diagnostics = processDiagnostics(binary);
+ const hasProcessWithoutArg = diagnostics.length > 0 && diagnostics.every((p) => p.hasCommandLine) &&
+ !diagnostics.some((p) => p.hasCdpArg);
+ if (hasProcessWithoutArg && elapsed >= 5000 && !retryWithoutCdpArg) {
+ // 单实例宿主可能接管了第一次启动请求;精确结束该安装目录的进程树后只重试一次。
+ logProcessDiagnostics(binary, '启动后进程未携带 CDP 参数,准备重试');
+ retryWithoutCdpArg = true;
+ await quitWorkBuddy(binary);
+ await sleep(1000);
+ start();
+ continue;
+ }
+ if (Date.now() - lastDiagnosticAt >= 5000) {
+ lastDiagnosticAt = Date.now();
+ log('等待 WorkBuddy CDP: ' + Math.min(Date.now() - (deadline - CDP_STARTUP_TIMEOUT_MS), CDP_STARTUP_TIMEOUT_MS) +
+ 'ms/' + CDP_STARTUP_TIMEOUT_MS + 'ms');
+ if (diagnostics.length) logProcessDiagnostics(binary, '等待期间');
+ }
+ }
+
+ // 端口可能在启动后被系统/其他进程抢占;超时前再扫描候选端口一次,避免只盯着旧的 9222。
+ for (const port of cdpPortCandidates()) {
+ if (port === CDP_PORT) continue;
+ if (await isWorkBuddyCdpAt(port, binary)) {
+ CDP_PORT = port;
+ writeCdpPortFile(port);
+ log('超时前发现 WorkBuddy 使用备用 CDP 端口: ' + port);
+ return true;
+ }
+ }
+ logProcessDiagnostics(binary, 'CDP 超时最终诊断');
+ return false;
}
async function injectNow() {
@@ -508,16 +645,9 @@ async function injectNow() {
log('重启 WorkBuddy(带 --remote-debugging-port=' + CDP_PORT + ',GUI 使用当前用户权限): ' + wb);
console.log('正在以调试模式重启 WorkBuddy(约几秒)...');
- await quitWorkBuddy();
- await sleep(500);
- launchWorkBuddy(wb);
-
- let ok = false;
- for (let elapsedMs = 0; elapsedMs < CDP_STARTUP_TIMEOUT_MS; elapsedMs += 1000) {
- await sleep(1000);
- if (await isWorkBuddyCdp()) { ok = true; break; }
- if ((elapsedMs + 1000) % 5000 === 0) log('等待 WorkBuddy CDP: ' + (elapsedMs + 1000) + 'ms/' + CDP_STARTUP_TIMEOUT_MS + 'ms');
- }
+ await quitWorkBuddy(wb);
+ await sleep(1000);
+ const ok = await waitForWorkBuddyCdp(wb);
if (ok) {
await sleep(1500);
await injectNow();
@@ -526,7 +656,10 @@ async function injectNow() {
} else {
log('等待 ' + (CDP_STARTUP_TIMEOUT_MS / 1000) + ' 秒未检测到调试端口 ' + CDP_PORT);
console.log('等待超时:未检测到调试端口 ' + CDP_PORT + '。可手动执行:cd /d ' + path.dirname(wb) + ' && "' + wb + '" --remote-debugging-port=' + CDP_PORT);
- await captureMessage('等待 ' + (CDP_STARTUP_TIMEOUT_MS / 1000) + ' 秒未检测到 WorkBuddy CDP 端口', { stage: 'windows-launcher-cdp-timeout', extra: { cdpPort: CDP_PORT, workBuddy: wb, timeoutMs: CDP_STARTUP_TIMEOUT_MS } }).catch(() => {});
+ await captureMessage('等待 ' + (CDP_STARTUP_TIMEOUT_MS / 1000) + ' 秒未检测到 WorkBuddy CDP 端口', {
+ stage: 'windows-launcher-cdp-timeout',
+ extra: { cdpPort: CDP_PORT, workBuddy: wb, timeoutMs: CDP_STARTUP_TIMEOUT_MS, processes: processDiagnostics(wb) },
+ }).catch(() => {});
}
process.exit(ok ? 0 : 3);
})().catch((e) => {
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index aa8562f..0ee4bb2 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -129,7 +129,20 @@ test('CDP startup supports a persisted fallback port instead of hardcoding 9222'
test('Windows launcher tolerates slow WorkBuddy startup beyond the old 20 second limit', () => {
const launcher = read('win-launcher.js');
assert.match(launcher, /CDP_STARTUP_TIMEOUT_MS\s*=\s*60000/);
- assert.match(launcher, /elapsedMs\s*<\s*CDP_STARTUP_TIMEOUT_MS/);
+ assert.match(launcher, /Date\.now\(\)\s*<\s*deadline/);
+ assert.match(launcher, /await sleep\(1000\)/);
+});
+
+test('Windows launcher verifies the real WorkBuddy process tree and launch arguments', () => {
+ const launcher = read('win-launcher.js');
+ assert.match(launcher, /Get-CimInstance Win32_Process/);
+ assert.match(launcher, /CommandLine/);
+ assert.match(launcher, /同安装目录进程的精确参数/);
+ assert.match(launcher, /按实际 PID 精确结束安装目录中的进程树/);
+ assert.match(launcher, /waitForWorkBuddyCdp\(wb\)/);
+ assert.match(launcher, /启动后进程未携带 CDP 参数,准备重试/);
+ assert.match(launcher, /CDP 超时最终诊断/);
+ assert.match(launcher, /processes: processDiagnostics\(wb\)/);
});
test('Windows launcher discovers portable WorkBuddy installations', () => {
@@ -139,6 +152,32 @@ test('Windows launcher discovers portable WorkBuddy installations', () => {
assert.match(launcher, /WBSWITCH_WORKBUDDY_BIN/);
});
+test('Windows release package includes the troubleshooting prompt as UTF-8', () => {
+ const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-win-zip.sh'), 'utf8');
+ assert.match(build, /安装失败自主解决提示词\.txt/);
+ assert.match(build, /Python zipfile/);
+ assert.match(build, /ZIP_DEFLATED/);
+});
+
+test('daemon lock falls back when the data-directory lock is not writable on Windows', () => {
+ const daemon = read('daemon.js');
+ assert.match(daemon, /DAEMON_LOCK_FALLBACK_FILE/);
+ assert.match(daemon, /os\.tmpdir\(\)/);
+ assert.match(daemon, /\['EACCES', 'EPERM', 'EROFS'\]/);
+ assert.match(daemon, /daemon-lock-fallback/);
+ assert.match(daemon, /daemonLockPath/);
+ assert.match(daemon, /releaseDaemonLock[\s\S]*daemonLockPath/);
+});
+
+test('session ranges use last-modified time and hide non-copyable task sessions', () => {
+ const daemon = read('daemon.js');
+ const inject = read('inject.js');
+ assert.match(daemon, /COALESCE\(last_activity_at, updated_at, created_at\) >=/);
+ assert.match(daemon, /ORDER BY COALESCE\(last_activity_at, updated_at, created_at\) DESC/);
+ assert.match(inject, /sessionsState\.list = \(\(d && d\.sessions\) \|\| \[\]\)\.filter\(function \(s\) \{ return !isTaskSessionRecordUI\(s\.cwd\); \}\)/);
+ assert.match(inject, /fmtHumanTime\(s\.last_activity_at \|\| s\.updated_at \|\| s\.created_at\)/);
+});
+
test('Windows relaunch restores the WorkBuddy window after starting it', () => {
const daemon = read('daemon.js');
assert.match(daemon, /restoreWorkBuddyWindow/);