Skip to content

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

fix(windows): harden install and WorkBuddy relaunch

[email protected]a59c24e2d5c7
diff --git a/scripts/apply-update.ps1 b/scripts/apply-update.ps1
index 83cad3c..af18a98 100644
--- a/scripts/apply-update.ps1
+++ b/scripts/apply-update.ps1
@@ -20,6 +20,39 @@ Start-Transcript -Path $Log -Append -Force
Write-Host "[apply] $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') start src=$SrcZip dst=$AppDir"
+function Test-ExclusiveFile {
+ param([string]$Path)
+ if (-not (Test-Path -LiteralPath $Path)) { return $true }
+ $stream = $null
+ try {
+ $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
+ return $true
+ } catch {
+ return $false
+ } finally {
+ if ($stream) { $stream.Dispose() }
+ }
+}
+
+function Release-LockedLauncher {
+ param([string]$LauncherPath)
+ if (Test-ExclusiveFile $LauncherPath) { return $true }
+ $needle = ([IO.Path]::GetFullPath($LauncherPath)).Replace('/', '\').ToLowerInvariant()
+ try {
+ Get-CimInstance Win32_Process -Filter "Name = 'cmd.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
+ $commandLine = ([string]$_.CommandLine).Replace('/', '\').ToLowerInvariant()
+ if ($commandLine.Contains($needle) -and $_.ProcessId -ne $PID) {
+ taskkill /F /T /PID $_.ProcessId 2>$null | Out-Null
+ }
+ }
+ } catch {}
+ for ($i = 0; $i -lt 10; $i++) {
+ if (Test-ExclusiveFile $LauncherPath) { return $true }
+ Start-Sleep -Milliseconds 300
+ }
+ return (Test-ExclusiveFile $LauncherPath)
+}
+
# 1) 杀 watchdog(会连带终止 daemon;PID 文件在数据目录)
$pidFile = Join-Path $DataDir 'watchdog.pid'
if (Test-Path $pidFile) {
@@ -56,6 +89,16 @@ Start-Sleep -Seconds 1
# 3) 备份旧目录(回滚:move AppDir.old AppDir)
$oldDir = $AppDir + '.old'
+foreach ($launcherToRelease in @(
+ (Join-Path $AppDir 'scripts\launcher.cmd'),
+ (Join-Path $oldDir 'scripts\launcher.cmd')
+)) {
+ if (-not (Release-LockedLauncher $launcherToRelease)) {
+ Write-Host "[apply] 无法释放 launcher.cmd 文件锁: $launcherToRelease"
+ Stop-Transcript
+ exit 2
+ }
+}
if (Test-Path $oldDir) { Remove-Item -Recurse -Force $oldDir -ErrorAction SilentlyContinue }
if (Test-Path $AppDir) { Move-Item -Force $AppDir $oldDir -ErrorAction SilentlyContinue }
diff --git a/scripts/daemon.js b/scripts/daemon.js
index e2e3b83..8297a6d 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -84,8 +84,10 @@ const DATA_DIR = defaultDataDir();
// 不退出 WorkBuddy 即可把新账号入库;/api/open-url 供系统浏览器打开授权页
// 1.0.12:修复旧 daemon 与新版使用同一 build 标识导致启动器复用旧内存代码;
// 账号切换始终使用 JSON 替换 + CDP 刷新,不退出 WorkBuddy
-const DAEMON_VERSION = '1.0.12';
-const DAEMON_BUILD_ID = 'seamless-login-20260821-r2';
+// 1.0.13:Windows 安装/更新释放 launcher.cmd 文件锁;延长 CDP 启动等待;
+// 补充便携版 WorkBuddy 路径探测,并在重启后恢复主窗口
+const DAEMON_VERSION = '1.0.13';
+const DAEMON_BUILD_ID = 'windows-hardening-20260821';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -1069,6 +1071,36 @@ function runCommand(command, args, options = {}) {
});
}
+// Windows 的 WorkBuddy 可能记住“最小化到托盘”状态;重启后显式恢复主窗口,避免只看到托盘图标。
+async function restoreWorkBuddyWindow(pid) {
+ if (!IS_WIN || !pid) return false;
+ const source = [
+ 'using System;',
+ 'using System.Runtime.InteropServices;',
+ 'public static class WorkDaddyWindowBridge {',
+ ' delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);',
+ ' [DllImport("user32.dll")] static extern bool EnumWindows(EnumWindowsProc callback, IntPtr lParam);',
+ ' [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);',
+ ' [DllImport("user32.dll")] static extern bool ShowWindowAsync(IntPtr hWnd, int command);',
+ ' [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd);',
+ ' public static void Restore(uint targetPid) {',
+ ' EnumWindows((hWnd, lParam) => { uint owner; GetWindowThreadProcessId(hWnd, out owner);',
+ ' if (owner == targetPid) { ShowWindowAsync(hWnd, 9); SetForegroundWindow(hWnd); return false; }',
+ ' return true; }, IntPtr.Zero);',
+ ' }',
+ '}',
+ ].join('\n');
+ const command = `Add-Type -TypeDefinition @'\n${source}\n'@; [WorkDaddyWindowBridge]::Restore(${Number(pid)})`;
+ const encoded = Buffer.from(command, 'utf16le').toString('base64');
+ const result = await runCommand('powershell', ['-NoProfile', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded], { timeoutMs: 10000 });
+ if (result.error || result.code !== 0) {
+ log('[relaunch] 恢复 WorkBuddy 窗口失败: ' + (result.error ? result.error.message : 'powershell exit ' + result.code));
+ return false;
+ }
+ log('[relaunch] 已恢复并置前 WorkBuddy 窗口');
+ return true;
+}
+
function workBuddyRunning() {
try {
if (IS_WIN) {
@@ -1161,6 +1193,11 @@ function relaunchWorkBuddy() {
child.once('spawn', resolve);
});
child.unref();
+ // 窗口创建可能晚于 CDP/进程就绪,重复几次恢复,仍不影响重启流程本身。
+ for (let attempt = 0; attempt < 5; attempt++) {
+ await sleep(1000);
+ await restoreWorkBuddyWindow(child.pid);
+ }
return;
}
const workDaddy = findWorkDaddyApp();
diff --git a/scripts/install-win.ps1 b/scripts/install-win.ps1
index aa831d1..73c2640 100644
--- a/scripts/install-win.ps1
+++ b/scripts/install-win.ps1
@@ -31,6 +31,39 @@ function Send-Sentry {
} catch {}
}
+function Test-ExclusiveFile {
+ param([string]$Path)
+ if (-not (Test-Path -LiteralPath $Path)) { return $true }
+ $stream = $null
+ try {
+ $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
+ return $true
+ } catch {
+ return $false
+ } finally {
+ if ($stream) { $stream.Dispose() }
+ }
+}
+
+function Release-LockedLauncher {
+ param([string]$LauncherPath)
+ if (Test-ExclusiveFile $LauncherPath) { return $true }
+ $needle = ([IO.Path]::GetFullPath($LauncherPath)).Replace('/', '\').ToLowerInvariant()
+ try {
+ Get-CimInstance Win32_Process -Filter "Name = 'cmd.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
+ $commandLine = ([string]$_.CommandLine).Replace('/', '\').ToLowerInvariant()
+ if ($commandLine.Contains($needle) -and $_.ProcessId -ne $PID) {
+ taskkill /F /T /PID $_.ProcessId 2>$null | Out-Null
+ }
+ }
+ } catch {}
+ for ($i = 0; $i -lt 10; $i++) {
+ if (Test-ExclusiveFile $LauncherPath) { return $true }
+ Start-Sleep -Milliseconds 300
+ }
+ return (Test-ExclusiveFile $LauncherPath)
+}
+
Write-Host '=============================================================='
Write-Host ' WorkDaddy Windows 安装'
Write-Host '=============================================================='
@@ -51,6 +84,12 @@ if ([StringComparer]::OrdinalIgnoreCase.Equals($sourceFull, $targetFull)) {
# 在 Windows 上容易出现“文件正被另一个进程使用”。此时只需继续执行后续注册/快捷方式步骤。
Write-Host ' 源目录与安装目录相同,跳过自拷贝。'
} else {
+ $launcherToReplace = Join-Path $targetScripts 'launcher.cmd'
+ if (-not (Release-LockedLauncher $launcherToReplace)) {
+ Write-Host "复制前无法释放 launcher.cmd 文件锁: $launcherToReplace"
+ Send-Sentry 'windows-install-launcher-lock' "无法释放 launcher.cmd 文件锁: $launcherToReplace" 2
+ exit 2
+ }
robocopy $SrcDir $targetScripts /E /XF *.log .DS_Store /XD win\probe /R:2 /W:1
$rc = $LASTEXITCODE
if ($rc -ge 8) {
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
index 6be31f5..280cba3 100644
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@ -29,6 +29,8 @@ const cliCdpPort = process.argv.find((arg) => /^--cdp-port=\d+$/i.test(arg));
let CDP_PORT = parseInt(process.env.WBSWITCH_CDP_PORT || (cliCdpPort ? cliCdpPort.split('=')[1] : '') || '0', 10);
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;
function log(...args) {
const line = `[launcher] ${new Date().toISOString()} ${args.join(' ')}\n`;
@@ -217,11 +219,17 @@ function findNode() {
return null;
}
-// ---------- 定位 WorkBuddy.exe(环境变量 > 运行进程 > 注册表 > 常见路径) ----------
+// ---------- 定位 WorkBuddy.exe(环境变量 > 运行进程 > App Paths/卸载注册表 > 常见便携路径) ----------
let wbBinaryCache = null;
function findWorkBuddy() {
if (wbBinaryCache) return wbBinaryCache;
- const tryFile = (p) => { try { if (p && fs.existsSync(p)) return p; } catch (_) {} return null; };
+ const tryFile = (p) => {
+ try {
+ const candidate = String(p || '').trim().replace(/^"(.*)"(?:,\d+)?$/, '$1').replace(/,\d+$/, '');
+ if (candidate && fs.existsSync(candidate)) return candidate;
+ } catch (_) {}
+ return null;
+ };
const envBin = tryFile(process.env.WBSWITCH_WORKBUDDY_BIN);
if (envBin) return (wbBinaryCache = envBin);
try {
@@ -229,17 +237,40 @@ function findWorkBuddy() {
const hit = tryFile(p);
if (hit) return (wbBinaryCache = hit);
} catch (_) {}
+ try {
+ const p = psOut("Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '^(WorkBuddy|CodeBuddy|WorkBuddyAI)\\.exe$' -and $_.ExecutablePath } | Select-Object -First 1 -ExpandProperty ExecutablePath").split(/\r?\n/).filter(Boolean).pop();
+ const hit = tryFile(p);
+ if (hit) return (wbBinaryCache = hit);
+ } catch (_) {}
+ // 便携版通常没有卸载项,但可能注册了 App Paths;优先读取其真实可执行路径。
+ try {
+ const p = psOut("$k=@('HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WorkBuddy.exe','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WorkBuddy.exe','HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\CodeBuddy.exe','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\CodeBuddy.exe'); Get-ItemProperty $k -ErrorAction SilentlyContinue | ForEach-Object { if ($_.'(default)') { $_.'(default)' } elseif ($_.Path) { $_.Path } } | Select-Object -First 1").split(/\r?\n/).filter(Boolean).pop();
+ const hit = tryFile(p);
+ if (hit) return (wbBinaryCache = hit);
+ } catch (_) {}
try {
const p = psOut("$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } | Select-Object -First 1 DisplayIcon,InstallLocation | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation 'WorkBuddy.exe' } }").split(/\r?\n/).filter(Boolean).pop();
const hit = tryFile(p);
if (hit) return (wbBinaryCache = hit);
} catch (_) {}
- for (const c of [
+ const roots = [
path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddy', 'WorkBuddy.exe'),
path.join(process.env.ProgramFiles || '', 'WorkBuddy', 'WorkBuddy.exe'),
path.join(process.env['ProgramFiles(x86)'] || '', 'WorkBuddy', 'WorkBuddy.exe'),
- 'D:\\workbody\\WorkBuddy\\WorkBuddy.exe',
- ]) {
+ path.join(process.env.USERPROFILE || '', 'scoop', 'apps', 'workbuddy', 'current', 'WorkBuddy.exe'),
+ 'D:\\workbuddy\\WorkBuddy.exe',
+ ];
+ if (process.env.WBSWITCH_WORKBUDDY_DIR) roots.push(path.join(process.env.WBSWITCH_WORKBUDDY_DIR, 'WorkBuddy.exe'));
+ // 兼容类似 D:\Software\workbuddy\WorkBuddy.exe 的便携目录,不递归扫描整盘。
+ try {
+ const driveRoots = psOut('(Get-PSDrive -PSProvider FileSystem).Root').split(/\r?\n/).map((x) => x.trim()).filter(Boolean);
+ for (const root of driveRoots) {
+ roots.push(path.join(root, 'Software', 'workbuddy', 'WorkBuddy.exe'));
+ roots.push(path.join(root, 'workbuddy', 'WorkBuddy.exe'));
+ roots.push(path.join(root, 'WorkBuddy', 'WorkBuddy.exe'));
+ }
+ } catch (_) {}
+ for (const c of roots) {
const hit = tryFile(c);
if (hit) return (wbBinaryCache = hit);
}
@@ -482,9 +513,10 @@ async function injectNow() {
launchWorkBuddy(wb);
let ok = false;
- for (let i = 0; i < 20; i++) {
+ 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');
}
if (ok) {
await sleep(1500);
@@ -492,9 +524,9 @@ async function injectNow() {
log('WorkBuddy 已启动(调试模式),组件已注入');
console.log('WorkDaddy:WorkBuddy 已启动(调试模式),组件已注入 ✓');
} else {
- log('等待 20 秒未检测到调试端口 ' + CDP_PORT);
+ 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('等待 20 秒未检测到 WorkBuddy CDP 端口', { stage: 'windows-launcher-cdp-timeout', extra: { cdpPort: CDP_PORT, workBuddy: wb } }).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 } }).catch(() => {});
}
process.exit(ok ? 0 : 3);
})().catch((e) => {
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index e1b3a87..fa176e2 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -23,6 +23,20 @@ test('Windows updater stops the watchdog before waiting for the API port', () =>
assert.ok(stop < wait, 'watchdog shutdown must precede the port wait');
});
+test('Windows install and update release a locked launcher before replacing it', () => {
+ const install = read('install-win.ps1');
+ const update = read('apply-update.ps1');
+ assert.match(install, /FileShare\]\s*::None/);
+ assert.match(install, /launcher\.cmd/);
+ assert.match(install, /Get-CimInstance\s+Win32_Process/);
+ assert.match(install, /taskkill \/F \/T \/PID/);
+ assert.ok(install.indexOf('Release-LockedLauncher') < install.indexOf('robocopy $SrcDir $targetScripts'), 'install must release launcher before robocopy');
+ assert.match(update, /FileShare\]\s*::None/);
+ assert.match(update, /launcher\.cmd/);
+ assert.match(update, /Get-CimInstance\s+Win32_Process/);
+ assert.ok(update.indexOf('Release-LockedLauncher') < update.indexOf('Move-Item -Force $AppDir $oldDir'), 'update must release launcher before moving the old app');
+});
+
test('macOS updater stops the daemon before waiting for the API port', () => {
const script = read('apply-update.sh');
const stop = script.indexOf('pkill -f');
@@ -94,6 +108,25 @@ test('CDP startup supports a persisted fallback port instead of hardcoding 9222'
assert.match(winLauncher, /--remote-debugging-port=' \+ CDP_PORT/);
});
+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/);
+});
+
+test('Windows launcher discovers portable WorkBuddy installations', () => {
+ const launcher = read('win-launcher.js');
+ assert.match(launcher, /App Paths/);
+ assert.match(launcher, /Software[\\/].*workbuddy/i);
+ assert.match(launcher, /WBSWITCH_WORKBUDDY_BIN/);
+});
+
+test('Windows relaunch restores the WorkBuddy window after starting it', () => {
+ const daemon = read('daemon.js');
+ assert.match(daemon, /restoreWorkBuddyWindow/);
+ assert.match(daemon, /await restoreWorkBuddyWindow/);
+});
+
test('account cards keep the compact three-row layout', () => {
const script = read('inject.js');
assert.match(script, /wbs-name-group/);