Skip to content

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

fix: /api/status 客户端运行状态改后台子进程探测,解除温启动 daemon 发现失败

zhangweildlh51812afd2c55
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 622254c..22d9b83 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -31,7 +31,7 @@ const net = require('net');
let sessionSync = require('./session-sync.js');
const {createCodeBuddyFiles} = require('./codebuddy-files.js');
const { createAccountCreditCache } = require('./account-credit-cache.js');
-const { spawn, spawnSync } = require('child_process');
+const { spawn, spawnSync, execFile } = require('child_process');
const {
assertSameProcessIdentity,
detectWindowsPrivilege,
@@ -45,6 +45,14 @@ const {
selectRunningProfileBinary,
selectPreferredDiscoveredBinary,
} = require('./windows-process-boundary.js');
+// 一次性子进程模式:供 /api/status 的后台缓存刷新以非阻塞方式执行同步进程探测。
+// Windows 上的 safeClientRunning() 会阻塞事件循环数秒(PowerShell 冷启 + CIM 枚举),
+// 绝不能跑在 daemon 主线程里;本分支只做一次探测并输出结果后立即退出,
+// 不触碰 daemon 的单实例锁、HTTP 服务与任何其它顶层副作用。
+if (process.argv.includes('--probe-client-running')) {
+ process.stdout.write(JSON.stringify({ running: safeClientRunning() }));
+ process.exit(0);
+}
const DAEMON_PRIVILEGE = process.platform === 'win32'
? (process.env.WBSWITCH_NATIVE_LAUNCHER === '1'
? detectNativeWindowsPrivilege(path.resolve(__dirname, '..'), process.env.WBSWITCH_PROFILE || 'workbuddy-cn')
@@ -480,8 +488,13 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.18:自动化 session.create 可选 cwd(绝对路径)/ workspace(侧栏工作区名)指定新会话
// 工作目录;工作区不存在或绑定校验不通过时拒绝发送,不退回默认目录。
// 1.2.20:CodeBuddy 原生安全存储不可用时保护已有加密会话,并给出钥匙串/密钥环修复提示。
-const DAEMON_VERSION = '1.2.28';
-const DAEMON_BUILD_ID = 'release-1.2.28-20261011-windows-installer-dedupe';
+// 1.2.29:/api/status 的客户端运行状态改为后台定时刷新 + 请求直读缓存。Windows 上
+// safeClientRunning() 会冷启 PowerShell 做 CIM 进程枚举(实测 2.4-6.7s),
+// 在请求线程里执行会把状态接口拖到远超 launcher HTTP 发现预算的程度,温启动
+// 时 launcher 发现不到已在监听的 daemon,误选备用 UI 端口后失败退出。
+// launcher 的 httpGet 预算同步对齐到 HTTP_GET_TIMEOUT_MS。
+const DAEMON_VERSION = '1.2.29';
+const DAEMON_BUILD_ID = 'release-1.2.29-20261012-status-nonblocking';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -2680,6 +2693,37 @@ function safeClientRunning() {
}
}
+// /api/status 曾直接在请求线程里调用 safeClientRunning():Windows 上这会同步冷启
+// PowerShell 做 CIM 进程枚举(实测 2.4-6.7s),把状态接口拖到远超 launcher HTTP
+// 探测预算(1500ms)的程度,温启动时 launcher 发现不到已在监听的 daemon,误选
+// 备用 UI 端口并覆写 ui-port.json,最终以「daemon 未绑定当前 UI 端口与当前 profile
+// 状态」失败退出。现改为后台定时刷新 + 请求直读缓存,状态接口恒为毫秒级;缓存
+// 未就绪时为 null(未知),与探测失败时的既有语义一致。
+// 注意:刷新必须走一次性子进程(--probe-client-running)——同步探测会阻塞 daemon
+// 事件循环数秒,放在主线程里只会把「每次请求慢」变成「周期性不可用」。
+const clientRunningState = { value: null, checkedAt: 0 };
+const CLIENT_RUNNING_REFRESH_MS = 5000;
+function refreshClientRunning() {
+ return new Promise((resolve) => {
+ execFile(process.execPath, [__filename, '--probe-client-running'], {
+ encoding: 'utf8', timeout: 15000, windowsHide: true,
+ }, (error, stdout) => {
+ // 探测失败(超时/异常/输出不可解析)时保留上一次已知值,绝不让状态接口失败
+ if (!error) {
+ try { clientRunningState.value = JSON.parse(String(stdout)).running; } catch (_) {}
+ }
+ clientRunningState.checkedAt = Date.now();
+ resolve(clientRunningState.value);
+ });
+ });
+}
+// 启动时立即刷新一次,随后按固定间隔在后台刷新(unref 避免阻止进程退出)
+refreshClientRunning().catch(() => {});
+if (typeof setInterval === 'function') {
+ const timer = setInterval(() => { refreshClientRunning().catch(() => {}); }, CLIENT_RUNNING_REFRESH_MS);
+ if (timer && typeof timer.unref === 'function') timer.unref();
+}
+
async function cdpLoop() {
for (;;) {
if (!cdp.connected) {
@@ -10104,7 +10148,8 @@ function handleApi(req, res) {
},
client: {
// 客户端进程是否在跑 / 调试端口是否可达 / 是否命中"更新后丢失调试端口"状态
- running: safeClientRunning(),
+ // running 由后台定时刷新(refreshClientRunning),请求线程直读缓存,不再同步探测
+ running: clientRunningState.value,
cdpReachable: cdp.connected,
needsDebugRelaunch: clientDebugState.needsDebugRelaunch,
debugStateUpdatedAt: clientDebugState.updatedAt || null,
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
index 5bfab63..8948066 100644
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@ -91,6 +91,11 @@ const CDP_STARTUP_TIMEOUT_MS = 60000;
// Electron/ShellExecute 冷启动可能超过 5 秒;过早换端口会让首个实例与重试实例发生单实例冲突。
const CDP_PORT_RETRY_GRACE_MS = 15000;
const INJECT_REQUEST_TIMEOUT_MS = 5000;
+// daemon 的 /api/status 可能等待后台客户端进程枚举(Windows 上旧实现曾达数秒)。
+// 启动器的 UI 端口发现与 daemon 状态读取必须容忍这种慢响应:预算过短会把仍在
+// 监听的 daemon 误判为不存在,进而误选备用端口并以「daemon 未绑定当前 UI 端口」
+// 失败退出。与 daemon 侧 spawnSync 的 10s 进程查询预算保持同量级并留出余量。
+const HTTP_GET_TIMEOUT_MS = 8000;
const INJECT_MAX_ATTEMPTS = 6;
const INJECT_RETRY_DELAY_MS = 1000;
// 每个 profile 只查询自己的主程序镜像;其他 CodeBuddy/WorkBuddy profile 不参与退出判定。
@@ -303,7 +308,7 @@ function reserveEphemeralCdpPort() {
function httpGet(port, p, headers = {}) {
return new Promise((resolve) => {
- const req = http.get({ host: HOST, port, path: p, headers, timeout: 1500 }, (res) => {
+ const req = http.get({ host: HOST, port, path: p, headers, timeout: HTTP_GET_TIMEOUT_MS }, (res) => {
let body = '';
res.on('data', (c) => (body += c));
res.on('end', () => resolve({ status: res.statusCode, body }));
@@ -1827,4 +1832,5 @@ module.exports = {
workBuddyRunning,
cdpPortCandidates,
reserveEphemeralCdpPort,
+ httpGet,
};
diff --git a/test/daemon-status-nonblocking.test.js b/test/daemon-status-nonblocking.test.js
new file mode 100644
index 0000000..9464c67
--- /dev/null
+++ b/test/daemon-status-nonblocking.test.js
@@ -0,0 +1,142 @@
+'use strict';
+
+// 回归锁定:daemon 的 /api/status 不得在请求线程里同步枚举客户端进程。
+// 背景:Windows 上 safeClientRunning() 会冷启 PowerShell 做 CIM 进程枚举
+// (实测 2.4-6.7s,远超 launcher 的 HTTP 发现预算 1.5s)。温启动场景下
+// launcher 发现不到已在监听的 daemon,误选备用 UI 端口并覆写 ui-port.json,
+// 最终以「daemon 未绑定当前 UI 端口与当前 profile 状态」失败退出,
+// WorkBuddy 永远不会被拉起。
+// 平台说明:daemon.js 顶层有副作用(直接启动服务),这里沿用
+// session-sync-daemon.test.js 的 vm 切片手法,只执行目标代码段;
+// launcher 的 httpGet 行为测试使用本地 HTTP 服务器,跨平台可真实运行。
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const http = require('node:http');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+
+const daemonSource = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+
+test('status handler reads the cached client state instead of probing in the request thread', () => {
+ const handlerStart = daemonSource.indexOf("if (req.method === 'GET' && p === '/api/status')");
+ assert.ok(handlerStart > 0, 'status handler not found in daemon.js');
+ const handlerEnd = daemonSource.indexOf('if (authenticated) {', handlerStart);
+ assert.ok(handlerEnd > handlerStart, 'authenticated block not found after status handler');
+ const handler = daemonSource.slice(handlerStart, handlerEnd);
+ assert.doesNotMatch(
+ handler,
+ /running:\s*safeClientRunning\(\)/,
+ 'status handler still enumerates processes inline; /api/status stays seconds-slow'
+ );
+ assert.match(handler, /running:\s*clientRunningState\.value/, 'status handler should read the background-refreshed cache');
+});
+
+test('client running probe runs in a one-shot subprocess so the daemon event loop stays free', () => {
+ assert.match(daemonSource, /--probe-client-running/, 'one-shot probe subprocess mode not found in daemon.js');
+ assert.match(daemonSource, /\bexecFile\b/, 'execFile must be imported for the non-blocking refresh');
+ assert.match(daemonSource, /execFile\(process\.execPath, \[__filename, '--probe-client-running'\]/, 'refresh must shell out to the one-shot probe');
+});
+
+test('one-shot probe subprocess answers without starting the daemon', () => {
+ const { execFileSync } = require('node:child_process');
+ const startedAt = Date.now();
+ const stdout = execFileSync(
+ process.execPath,
+ [path.join(__dirname, '..', 'scripts', 'daemon.js'), '--probe-client-running'],
+ { encoding: 'utf8', timeout: 20000, windowsHide: true }
+ );
+ const parsed = JSON.parse(stdout);
+ assert.ok(parsed.running === true || parsed.running === false || parsed.running === null,
+ 'probe must answer a boolean or null');
+ // 子进程只做一次探测后退出:不得进入单实例锁/HTTP 服务等启动路径
+ assert.ok(Date.now() - startedAt < 15000, 'probe subprocess should exit quickly without booting the daemon');
+});
+
+test('client running cache refreshes in the background and survives probe failures', async () => {
+ const anchor = daemonSource.indexOf('const clientRunningState = {');
+ assert.ok(anchor > 0, 'client running cache block not found in daemon.js');
+ const end = daemonSource.indexOf('async function cdpLoop', anchor);
+ assert.ok(end > anchor, 'cache block end anchor not found');
+ const block = daemonSource.slice(anchor, end);
+
+ let probeCalls = 0;
+ let probeShouldFail = false;
+ let probeResult = true;
+ const ctx = {
+ // mock execFile:模拟一次性子进程探测,异步回调
+ execFile: (bin, args, options, callback) => {
+ probeCalls += 1;
+ setImmediate(() => {
+ if (probeShouldFail) callback(new Error('probe failed'));
+ else callback(null, JSON.stringify({ running: probeResult }));
+ });
+ },
+ process: { execPath: process.execPath },
+ __filename: 'daemon.js',
+ Date,
+ setInterval: () => ({ unref() {} }),
+ console,
+ };
+ vm.runInNewContext(block, ctx);
+
+ // 启动时立即刷新一次(fire-and-forget),缓存随后就位
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.equal(probeCalls, 1, 'cache should refresh once at startup');
+ assert.equal(await ctx.refreshClientRunning(), true, 'cache should hold the probe result');
+ assert.equal(probeCalls, 2);
+
+ // 后台可重复刷新,缓存值随探测更新
+ probeResult = false;
+ assert.equal(await ctx.refreshClientRunning(), false);
+ assert.equal(probeCalls, 3);
+
+ // 探测失败时保留上一次已知值,绝不让状态接口因探测失败而失败
+ probeShouldFail = true;
+ assert.equal(await ctx.refreshClientRunning(), false, 'failed probe must preserve the last known value');
+ assert.equal(probeCalls, 4);
+});
+
+test('daemon behavior change ships a version and build bump so stale daemons are replaced', () => {
+ const version = daemonSource.match(/const DAEMON_VERSION = '([^']+)'/);
+ const buildId = daemonSource.match(/const DAEMON_BUILD_ID = '([^']+)'/);
+ assert.ok(version && buildId, 'DAEMON_VERSION/DAEMON_BUILD_ID not found');
+ assert.notEqual(version[1], '1.2.28', 'DAEMON_VERSION must be incremented for a daemon behavior change');
+ assert.match(buildId[1], /^release-1\.2\.29-/, 'DAEMON_BUILD_ID must be rewritten for the new build');
+});
+
+test('launcher httpGet uses a budget aligned with the daemon probe cost', () => {
+ const src = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'win-launcher.js'), 'utf8');
+ const start = src.indexOf('function httpGet(');
+ assert.ok(start > 0, 'httpGet not found in win-launcher.js');
+ const end = src.indexOf('\n}', start);
+ const body = src.slice(start, end);
+ assert.doesNotMatch(body, /timeout:\s*1500\b/, 'httpGet still uses the 1500ms budget that cannot see a slow daemon');
+ assert.match(body, /timeout:\s*HTTP_GET_TIMEOUT_MS\b/, 'httpGet should use the shared HTTP_GET_TIMEOUT_MS budget');
+});
+
+test('launcher httpGet tolerates a daemon slower than the old 1500ms budget', async () => {
+ const launcher = require('../scripts/win-launcher.js');
+ assert.equal(typeof launcher.httpGet, 'function', 'httpGet must be exported for the discovery path');
+
+ // 2500ms:旧预算(1500ms)必然放弃,新预算(8000ms)必须等到响应
+ const server = http.createServer((req, res) => {
+ setTimeout(() => {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, slow: true }));
+ }, 2500);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const port = server.address().port;
+ try {
+ const startedAt = Date.now();
+ const response = await launcher.httpGet(port, '/api/status', {});
+ assert.ok(response, 'httpGet must not give up on a 2.5s daemon response');
+ assert.equal(response.status, 200);
+ assert.deepEqual(JSON.parse(response.body), { ok: true, slow: true });
+ assert.ok(Date.now() - startedAt >= 2400, 'response should have been awaited, not failed fast');
+ } finally {
+ server.close();
+ }
+});