Skip to content

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

fix: 补齐 Linux 休眠控制和外链打开

[email protected]ea5c1aa39cd6
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 6b6ccc7..64c783d 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -420,8 +420,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.145:识别仅 updated_at 的激活漂移,清除无变更脏标记;无结果任务不再弹同步进度窗口。
// 1.2.126:5.6 加密账号改为密文原样备份、内存解密;导入兼容明文 token,
// 刷新结果不把解密后的 token 写回加密备份。
-const DAEMON_VERSION = '1.2.148';
-const DAEMON_BUILD_ID = 'release-1.2.148-20260923-windows-compat-target';
+const DAEMON_VERSION = '1.2.152';
+const DAEMON_BUILD_ID = 'release-1.2.152-20260924-linux-sleep-open-url';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -8564,6 +8564,20 @@ function handleApi(req, res) {
const u = String((body && body.url) || '');
if (!/^https?:\/\//i.test(u)) return json(res, 400, { ok: false, error: '仅支持 http(s) 链接' });
try {
+ if (IS_LINUX) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('xdg-open', [u], { detached: true, stdio: 'ignore' });
+ // 不记录 URL:授权链接可能包含登录 state。缺少命令时也不能让 error 事件退出 daemon。
+ child.once('error', reject);
+ child.once('spawn', () => {
+ child.unref();
+ resolve();
+ });
+ }).then(
+ () => json(res, 200, { ok: true }),
+ () => json(res, 500, { ok: false, error: '无法启动系统浏览器,请确认已安装 xdg-utils' })
+ );
+ }
if (IS_WIN) {
spawn('rundll32', ['url.dll,FileProtocolHandler', u], { detached: true, stdio: 'ignore' }).unref();
} else {
@@ -9281,7 +9295,7 @@ function handleApi(req, res) {
if (req.method === 'GET' && p === '/api/sleep-mode') {
let st = { mode: 'allow', displaySleep: false };
try { st = Object.assign(st, JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'sleep-mode.json'), 'utf8'))); } catch (_) {}
- return json(res, 200, { ok: true, mode: st.mode, displaySleep: !!st.displaySleep, preventing: st.mode === 'keep' || st.mode === 'until-done', active: !!(IS_WIN ? sleepPowershell : sleepCaffeinate), antiLock: !!sleepUserActivityTimer });
+ return json(res, 200, { ok: true, mode: st.mode, displaySleep: !!st.displaySleep, preventing: st.mode === 'keep' || st.mode === 'until-done', active: !!(IS_WIN ? sleepPowershell : IS_LINUX ? sleepInhibit : sleepCaffeinate), antiLock: !!sleepUserActivityTimer });
}
if (req.method === 'POST' && p === '/api/sleep-mode') {
return readBody(req).then((body) => {
@@ -10412,14 +10426,22 @@ function handleApi(req, res) {
}
-// ===== 电脑休眠控制(三模式:allow/keep/until-done + 显示器开关 + 立即休眠 pmset sleepnow)=====
+// ===== 电脑休眠控制(三模式:allow/keep/until-done + 显示器开关 + 立即休眠)=====
// mode: 'allow' 允许电脑休眠(默认)| 'keep' 持续禁止休眠 | 'until-done' 所有任务结束后允许休眠
// displaySleep: 禁止休眠时是否允许显示器休眠(默认 false = 显示器也保持唤醒)
let sleepCaffeinate = null;
let sleepUserActivity = null; // 防锁屏:caffeinate -u -t 300(UserIsActive 断言,阻止屏保启动/空闲锁屏)
let sleepUserActivityTimer = null; // -u 断言每 240s 续期一次(-t 300 超时前续期,保持无间隙)
let sleepPowershell = null; // Windows: 常驻 powershell 进程持有 SetThreadExecutionState
+let sleepInhibit = null; // Linux: systemd-inhibit 持有 sleep/idle inhibitor
function stopCaffeinate() {
+ if (IS_LINUX) {
+ const c = sleepInhibit;
+ sleepInhibit = null;
+ // detached 子进程独占进程组;同时结束 inhibitor 和 sleep,避免遗留后台进程。
+ if (c && c.pid) { try { process.kill(-c.pid, 'SIGTERM'); } catch (_) {} }
+ return;
+ }
if (IS_WIN) {
const c = sleepPowershell;
sleepPowershell = null; // 先置 null 再 kill,避免 exit 回调把旧引用覆盖
@@ -10441,7 +10463,7 @@ function stopUserActivity() {
// 系统认为用户一直在操作,屏保与空闲锁屏便不会触发;每 240s 重启一个 -t 300 的断言实现无间隙续期。
// 无需辅助功能权限(-u 走系统 IOKit 用户活动断言)。
function startUserActivityLoop() {
- if (IS_WIN) return; // Windows 无 caffeinate -u 等价;防锁屏由系统电源策略控制
+ if (IS_WIN || IS_LINUX) return; // 防锁屏由系统/桌面策略控制,不运行 macOS 用户活动断言
stopUserActivity();
const tick = () => {
if (!sleepCaffeinate) return; // 防休眠已停止(allow 模式),不再续期
@@ -10456,6 +10478,17 @@ function startUserActivityLoop() {
if (sleepUserActivityTimer.unref) sleepUserActivityTimer.unref();
}
function startCaffeinate(displaySleep) {
+ if (IS_LINUX) {
+ // logind 的 idle inhibitor 不保证阻止 Wayland 锁屏;不接管合盖策略。
+ const child = spawn('systemd-inhibit', [
+ '--what=' + (displaySleep ? 'sleep' : 'sleep:idle'), '--mode=block',
+ '--who=WorkDaddy', '--why=WorkDaddy 正在运行任务', 'sleep', 'infinity',
+ ], { detached: true, stdio: 'ignore' });
+ child.on('error', (e) => { log('[sleep] systemd-inhibit 启动失败: ' + e.message); if (sleepInhibit === child) sleepInhibit = null; });
+ child.on('exit', () => { if (sleepInhibit === child) sleepInhibit = null; });
+ sleepInhibit = child;
+ return child;
+ }
if (IS_WIN) {
// Windows:常驻 powershell 循环调用 SetThreadExecutionState。
// 0x80000000 ES_CONTINUOUS | 0x1 ES_SYSTEM_REQUIRED | 0x2 ES_DISPLAY_REQUIRED
@@ -10478,12 +10511,12 @@ function startCaffeinate(displaySleep) {
function applySleepMode(mode, displaySleep) {
const preventing = mode === 'keep' || mode === 'until-done';
if (preventing) {
- if (IS_WIN) {
- // Windows:powershell 持有进程参数固定,无法比较 spawnargs,直接重启(低频操作,代价可接受)
+ if (IS_WIN || IS_LINUX) {
+ // 平台持有进程直接重启(低频操作),同步更新显示器休眠策略。
stopCaffeinate();
try {
startCaffeinate(!!displaySleep);
- log('[sleep] 禁止休眠已开启(Windows,模式=' + mode + (displaySleep ? ',允许显示器休眠' : ',显示器保持唤醒') + ')');
+ log('[sleep] 禁止休眠已开启(' + (IS_LINUX ? 'Linux,systemd-inhibit' : 'Windows') + ',模式=' + mode + (displaySleep ? ',允许显示器休眠' : IS_LINUX ? ',请求阻止空闲休眠' : ',显示器保持唤醒') + ')');
} catch (e) { log('[sleep] 开启失败: ' + e.message); return false; }
return true;
}
@@ -10498,7 +10531,7 @@ function applySleepMode(mode, displaySleep) {
log('[sleep] 禁止休眠已开启(模式=' + mode + (displaySleep ? ',允许显示器休眠,防锁屏关闭' : ',显示器保持唤醒,防锁屏开启') + ')');
} catch (e) { log('[sleep] 开启失败: ' + e.message); return false; }
} else {
- if (!sleepCaffeinate && !sleepPowershell && !sleepUserActivityTimer) return true;
+ if (!sleepCaffeinate && !sleepPowershell && !sleepInhibit && !sleepUserActivityTimer) return true;
stopCaffeinate();
log('[sleep] 禁止休眠已解除(允许电脑休眠)');
}
@@ -10506,6 +10539,12 @@ function applySleepMode(mode, displaySleep) {
}
function sleepNow() {
try {
+ if (IS_LINUX) {
+ const c = spawn('systemctl', ['suspend'], { stdio: 'ignore' });
+ c.on('error', (e) => log('[sleep] 立即休眠失败: ' + e.message));
+ c.on('exit', (code) => log(code === 0 ? '[sleep] 已请求立即休眠(systemctl suspend)' : '[sleep] systemctl suspend 失败,退出码=' + code));
+ return true;
+ }
if (IS_WIN) {
// Windows:SetSuspendState(Hibernate=0, ForceCritical=0, DisableWakeEvent=0) → 睡眠
const c = spawn('rundll32.exe', ['powrprof.dll,SetSuspendState', '0,1,0'], { stdio: 'ignore', windowsHide: true });
diff --git a/test/open-url.test.js b/test/open-url.test.js
new file mode 100644
index 0000000..5dbfcfc
--- /dev/null
+++ b/test/open-url.test.js
@@ -0,0 +1,63 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { EventEmitter } = require('node:events');
+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+const route = source.slice(source.indexOf(" if (req.method === 'POST' && p === '/api/open-url')"), source.indexOf(" if (req.method === 'GET' && p === '/api/status')"));
+
+async function openUrl(platform, url, failure) {
+ const calls = [];
+ const context = {
+ IS_WIN: platform === 'win32', IS_LINUX: platform === 'linux',
+ req: { method: 'POST' }, p: '/api/open-url', res: {},
+ readBody: async () => ({ url }),
+ json: (_res, status, body) => ({ status, ...body }),
+ spawn(command, args, options) {
+ const child = new EventEmitter();
+ child.unref = () => { child.unreferenced = true; };
+ calls.push({ command, args: Array.from(args), options, child });
+ queueMicrotask(() => {
+ if (failure) child.emit('error', Object.assign(new Error('missing opener'), { code: 'ENOENT' }));
+ else child.emit('spawn');
+ });
+ return child;
+ },
+ };
+ const result = await vm.runInNewContext('(function(){' + route + '})()', context);
+ return { calls, result };
+}
+
+test('open-url uses the platform opener and passes the URL as one unchanged argument', async () => {
+ const url = 'https://example.invalid/login?state=a%2Bb&next=%2F';
+ for (const [platform, command, args] of [
+ ['linux', 'xdg-open', [url]], ['darwin', 'open', [url]],
+ ['win32', 'rundll32', ['url.dll,FileProtocolHandler', url]],
+ ]) {
+ const { calls, result } = await openUrl(platform, url);
+ assert.equal(result.status, 200);
+ assert.equal(result.ok, true);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].command, command);
+ assert.deepEqual(calls[0].args, args);
+ assert.equal(calls[0].options.shell, undefined);
+ assert.equal(calls[0].child.unreferenced, true);
+ }
+});
+
+test('open-url rejects non-HTTP URLs before spawning an opener', async () => {
+ for (const url of ['file:///tmp/test', 'javascript:alert(1)', '']) {
+ const { calls, result } = await openUrl('linux', url);
+ assert.equal(result.status, 400);
+ assert.equal(calls.length, 0);
+ }
+});
+
+test('Linux missing xdg-open returns an error without leaking the URL or an unhandled event', async () => {
+ const { result } = await openUrl('linux', 'https://example.invalid/?state=private-fixture', true);
+ assert.equal(result.status, 500);
+ assert.equal(result.ok, false);
+ assert.doesNotMatch(result.error, /private-fixture/);
+});
diff --git a/test/sleep-mode.test.js b/test/sleep-mode.test.js
index 6103f9e..c26bfda 100644
--- a/test/sleep-mode.test.js
+++ b/test/sleep-mode.test.js
@@ -5,12 +5,13 @@ const fs = require('node:fs');
const vm = require('node:vm');
const { EventEmitter } = require('node:events');
const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/daemon.js'), 'utf8');
-function harness(windows = false) {
- const children = [], timers = new Set();
- const ctx = { IS_WIN: windows, log() {},
- spawn(command, args) {
+function harness(windows = false, linux = false) {
+ const children = [], timers = new Set(), signals = [];
+ const ctx = { IS_WIN: windows, IS_LINUX: linux, log() {},
+ process: { kill(pid, signal) { signals.push({ pid, signal }); } },
+ spawn(command, args, options) {
const child = new EventEmitter();
- Object.assign(child, { spawnargs: [command, ...args], killed: false,
+ Object.assign(child, { pid: 1000 + children.length, options, spawnargs: [command, ...args], killed: false,
kill() { this.killed = true; this.emit('exit'); },
});
children.push(child);
@@ -20,8 +21,15 @@ function harness(windows = false) {
clearInterval(timer) { timers.delete(timer); },
};
vm.createContext(ctx);
- vm.runInContext(source.slice(source.indexOf('let sleepCaffeinate ='), source.indexOf('function sleepNow()')), ctx);
- return { ctx, children, timers };
+ vm.runInContext(source.slice(source.indexOf('let sleepCaffeinate ='), source.indexOf('function restoreSleepMode()')), ctx);
+ const statusBlock = source.slice(source.indexOf(" if (req.method === 'GET' && p === '/api/sleep-mode')"), source.indexOf(" if (req.method === 'POST' && p === '/api/sleep-mode')"));
+ Object.assign(ctx, {
+ req: { method: 'GET' }, p: '/api/sleep-mode', res: {}, DATA_DIR: '',
+ fs: { readFileSync: () => '{"mode":"keep"}' }, path: { join: () => '' },
+ json: (_res, _status, body) => body,
+ });
+ const status = () => vm.runInContext('(function(){' + statusBlock + '})()', ctx);
+ return { ctx, children, timers, signals, status };
}
test('Windows allow releases the exact keep-awake process', () => {
const h = harness(true);
@@ -48,10 +56,52 @@ test('macOS unchanged mode reuses assertions; display sleep removes display and
});
test('sleep status reports the Windows power process as active', () => {
- const block = source.slice(source.indexOf(" if (req.method === 'GET' && p === '/api/sleep-mode')"), source.indexOf(" if (req.method === 'POST' && p === '/api/sleep-mode')"));
- const readStatus = new Function('req', 'p', 'fs', 'path', 'DATA_DIR', 'res', 'json', 'IS_WIN', 'sleepPowershell', 'sleepCaffeinate', 'sleepUserActivityTimer', block);
- const result = readStatus({method:'GET'}, '/api/sleep-mode', {readFileSync:()=>'{"mode":"keep"}'}, {join:()=>''}, '', {}, (res, code, body)=>body, true, {}, null, null);
- assert.equal(result.active, true);
+ const h = harness(true);
+ h.ctx.applySleepMode('keep', false);
+ assert.equal(h.status().active, true);
+});
+
+test('Linux keep/until-done uses an inhibitor and allow releases its entire process group', () => {
+ const h = harness(false, true);
+ assert(h.ctx.applySleepMode('keep', false));
+ const first = h.children[0];
+ assert.equal(first.spawnargs[0], 'systemd-inhibit');
+ assert(first.spawnargs.includes('--what=sleep:idle'));
+ assert.equal(first.options.detached, true);
+ assert.equal(h.children.length, 1, 'Linux must not start caffeinate for screen locking');
+ assert.equal(h.timers.size, 0);
+ assert.equal(h.status().active, true);
+ assert.equal(h.status().antiLock, false);
+ h.ctx.applySleepMode('until-done', true);
+ const second = h.children[1];
+ assert(second.spawnargs.includes('--what=sleep'));
+ assert.deepEqual(h.signals, [{ pid: -first.pid, signal: 'SIGTERM' }]);
+ first.emit('exit', 0);
+ assert.equal(h.status().active, true, 'old exit must not clear the replacement inhibitor');
+ h.ctx.applySleepMode('allow', true);
+ assert.deepEqual(h.signals[1], { pid: -second.pid, signal: 'SIGTERM' });
+ assert.equal(h.status().active, false);
+});
+
+test('Linux inhibitor startup failure and exit clear active state without macOS fallback', () => {
+ const h = harness(false, true);
+ h.ctx.applySleepMode('keep', false);
+ h.children[0].emit('error', Object.assign(new Error('missing command'), { code: 'ENOENT' }));
+ assert.equal(h.status().active, false);
+ h.ctx.applySleepMode('keep', true);
+ h.children[1].emit('exit', 1);
+ assert.equal(h.status().active, false);
+ assert(h.children.every(child => child.spawnargs[0] === 'systemd-inhibit'));
+});
+
+test('immediate sleep selects the native command on each platform', () => {
+ for (const [win, linux, command] of [[false, true, 'systemctl'], [false, false, 'pmset'], [true, false, 'rundll32.exe']]) {
+ const h = harness(win, linux);
+ assert.equal(h.ctx.sleepNow(), true);
+ assert.equal(h.children[0].spawnargs[0], command);
+ if (linux) assert.deepEqual(h.children[0].spawnargs, ['systemctl', 'suspend']);
+ h.children[0].emit('error', new Error('unavailable'));
+ }
});
test('until-done waits for every discovered session, including blocked and recently hidden sessions', async () => {