WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
兼容 Windows 不同权限模式
[email protected]b7b3ef41ac5c
diff --git a/.gitignore b/.gitignoreindex 02ca1c3..53cabd8 100644--- a/.gitignore+++ b/.gitignore@@ -5,9 +5,8 @@node_modules/npm-debug.log*-# 构建产物与安装包(GitHub Release Assets 单独上传,不入库)+# 构建产物与安装包WorkDaddy.app-/release/# 本地运行数据与日志*.logdiff --git a/release/WorkDaddy.ico b/release/WorkDaddy.iconew file mode 100644index 0000000..e5e6e0aBinary files /dev/null and b/release/WorkDaddy.ico differdiff --git a/release/macos/WorkDaddy-1.0.18.dmg b/release/macos/WorkDaddy-1.0.18.dmgnew file mode 100644index 0000000..1031187Binary files /dev/null and b/release/macos/WorkDaddy-1.0.18.dmg differdiff --git a/release/macos/WorkDaddy-AI-1.0.18.dmg b/release/macos/WorkDaddy-AI-1.0.18.dmgnew file mode 100644index 0000000..8e7ceb2Binary files /dev/null and b/release/macos/WorkDaddy-AI-1.0.18.dmg differdiff --git a/release/windows/WorkDaddy-AI-Setup-1.1.0.exe b/release/windows/WorkDaddy-AI-Setup-1.1.0.exenew file mode 100644index 0000000..fabfdddBinary files /dev/null and b/release/windows/WorkDaddy-AI-Setup-1.1.0.exe differdiff --git a/release/windows/WorkDaddy-AI-Setup-1.1.1.exe b/release/windows/WorkDaddy-AI-Setup-1.1.1.exenew file mode 100644index 0000000..949bc5bBinary files /dev/null and b/release/windows/WorkDaddy-AI-Setup-1.1.1.exe differdiff --git a/release/windows/WorkDaddy-Setup-1.1.0.exe b/release/windows/WorkDaddy-Setup-1.1.0.exenew file mode 100644index 0000000..cf76b6fBinary files /dev/null and b/release/windows/WorkDaddy-Setup-1.1.0.exe differdiff --git a/release/windows/WorkDaddy-Setup-1.1.1.exe b/release/windows/WorkDaddy-Setup-1.1.1.exenew file mode 100644index 0000000..16e08c4Binary files /dev/null and b/release/windows/WorkDaddy-Setup-1.1.1.exe differdiff --git a/scripts/apply-update.ps1 b/scripts/apply-update.ps1index c7049bf..c68819d 100644--- a/scripts/apply-update.ps1+++ b/scripts/apply-update.ps1@@ -14,12 +14,9 @@ try {$identity = [Security.Principal.WindowsIdentity]::GetCurrent()$principal = New-Object Security.Principal.WindowsPrincipal($identity)$isElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)- if ($isElevated -ne $false) {- [Console]::Error.WriteLine('拒绝以管理员权限运行 WorkDaddy 更新脚本;请使用普通用户终端。')- exit 5- }+ $env:WBSWITCH_PRIVILEGE_MODE = if ($isElevated) { 'elevated' } else { 'standard' }} catch {- [Console]::Error.WriteLine('无法确认当前 PowerShell 为普通用户权限;更新已停止。')+ [Console]::Error.WriteLine('无法确认当前 PowerShell 的 Windows 权限模式;更新已停止。')exit 5}diff --git a/scripts/build-win-release.cmd b/scripts/build-win-release.cmdnew file mode 100644index 0000000..2306645--- /dev/null+++ b/scripts/build-win-release.cmd@@ -0,0 +1,16 @@+@echo off+rem WorkDaddy Windows 双版本发布打包入口+rem 双击运行会提示输入版本号;命令行可追加 -Version 1.1.1 等参数。+setlocal+chcp 65001 >nul 2>&1++powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0build-win-release.ps1" %*+set "EXIT_CODE=%ERRORLEVEL%"+echo.+if "%EXIT_CODE%"=="0" (+ echo 双版本安装包已生成。+) else (+ echo 打包失败,退出码 %EXIT_CODE%。+)+pause+exit /b %EXIT_CODE%diff --git a/scripts/build-win-release.ps1 b/scripts/build-win-release.ps1new file mode 100644index 0000000..3cb4fab--- /dev/null+++ b/scripts/build-win-release.ps1@@ -0,0 +1,156 @@+[CmdletBinding()]+param(+ [string]$Version = '',+ [string]$OutputDirectory = '',+ [string]$GitBashPath = '',+ [string]$IsccPath = '',+ [string]$PythonPath = ''+)++$ErrorActionPreference = 'Stop'+Set-StrictMode -Version 2.0++$scriptsRoot = $PSScriptRoot+$repoRoot = Split-Path -Parent $scriptsRoot+if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repoRoot 'release\windows' }+$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)++function Find-Executable {+ param(+ [string]$ExplicitPath,+ [string[]]$Candidates,+ [string]$CommandName,+ [string]$MissingMessage+ )++ if ($ExplicitPath) {+ $resolved = [IO.Path]::GetFullPath($ExplicitPath)+ if (Test-Path -LiteralPath $resolved -PathType Leaf) { return $resolved }+ throw "找不到指定的 ${CommandName}: $resolved"+ }++ $command = Get-Command $CommandName -ErrorAction SilentlyContinue+ if ($command -and $command.Source -and (Test-Path -LiteralPath $command.Source -PathType Leaf)) {+ return $command.Source+ }+ foreach ($candidate in $Candidates) {+ if ($candidate -and (Test-Path -LiteralPath $candidate -PathType Leaf)) { return $candidate }+ }+ throw $MissingMessage+}++function ConvertTo-GitBashPath {+ param([Parameter(Mandatory)][string]$Path)++ $full = [IO.Path]::GetFullPath($Path)+ if ($full -match '^(?<drive>[A-Za-z]):\\(?<rest>.*)$') {+ return ('/{0}/{1}' -f $matches.drive.ToLowerInvariant(), ($matches.rest -replace '\\', '/'))+ }+ return ($full -replace '\\', '/')+}++function Get-SourceVersion {+ $source = Get-Content -LiteralPath (Join-Path $scriptsRoot 'daemon.js') -Raw -Encoding UTF8+ $match = [regex]::Match($source, "const DAEMON_VERSION = '([^']+)'")+ if (-not $match.Success) { throw 'daemon.js 中找不到 DAEMON_VERSION。' }+ return $match.Groups[1].Value+}++function Invoke-WindowsZipBuild {+ param(+ [Parameter(Mandatory)][string]$Bash,+ [Parameter(Mandatory)][string]$Profile,+ [Parameter(Mandatory)][string]$ReleaseVersion,+ [string]$CachedPython+ )++ $bashRepo = ConvertTo-GitBashPath $repoRoot+ $pythonAssignment = ''+ if ($CachedPython) {+ $pythonBash = ConvertTo-GitBashPath $CachedPython+ $pythonAssignment = " WORKDADDY_PYTHON=`"$pythonBash`""+ }+ $command = "cd `"$bashRepo`" && WORKDADDY_BUILD_PROFILE=`"$Profile`" WORKDADDY_BUILD_VERSION=`"$ReleaseVersion`"$pythonAssignment bash scripts/build-win-zip.sh"+ Write-Host "`n==> 生成 $Profile staging ZIP"+ & $Bash -lc $command+ if ($LASTEXITCODE -ne 0) {+ throw "$Profile staging ZIP 生成失败(退出码 $LASTEXITCODE)。"+ }+}++function Invoke-WindowsInstallerBuild {+ param(+ [Parameter(Mandatory)][string]$Profile,+ [Parameter(Mandatory)][string]$ReleaseVersion,+ [Parameter(Mandatory)][string]$Compiler+ )++ Write-Host "==> 编译 $Profile Setup.exe"+ & (Join-Path $scriptsRoot 'build-win-installer.ps1') `+ -Profile $Profile `+ -Version $ReleaseVersion `+ -OutputDirectory $OutputDirectory `+ -IsccPath $Compiler+ if ($LASTEXITCODE -ne 0) {+ throw "$Profile Setup.exe 生成失败(退出码 $LASTEXITCODE)。"+ }+ $packageName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy-AI' } else { 'WorkDaddy' }+ $setup = Join-Path $OutputDirectory "$packageName-Setup-$ReleaseVersion.exe"+ if (-not (Test-Path -LiteralPath $setup -PathType Leaf)) {+ throw "未找到生成的安装包: $setup"+ }+ return $setup+}++try {+ $sourceVersion = Get-SourceVersion+ if ([string]::IsNullOrWhiteSpace($Version)) {+ $answer = Read-Host "请输入发布版本号(直接回车使用 $sourceVersion)"+ $Version = if ([string]::IsNullOrWhiteSpace($answer)) { $sourceVersion } else { $answer.Trim() }+ } else {+ $Version = $Version.Trim()+ }+ if ($Version -notmatch '^\d+\.\d+\.\d+$') {+ throw "版本号必须是 x.y.z 格式,实际为: $Version"+ }++ $gitBashCandidates = @(+ (Join-Path ${env:ProgramFiles} 'Git\bin\bash.exe'),+ (Join-Path ${env:ProgramFiles} 'Git\usr\bin\bash.exe'),+ (Join-Path ${env:ProgramFiles(x86)} 'Git\bin\bash.exe'),+ (Join-Path ${env:ProgramFiles(x86)} 'Git\usr\bin\bash.exe')+ )+ $bash = Find-Executable $GitBashPath $gitBashCandidates 'bash.exe' '找不到 Git Bash(bash.exe),请安装 Git for Windows 或使用 -GitBashPath 指定路径。'++ $isccCandidates = @(+ (Join-Path ${env:LOCALAPPDATA} 'Programs\Inno Setup 6\ISCC.exe'),+ (Join-Path ${env:ProgramFiles(x86)} 'Inno Setup 6\ISCC.exe'),+ (Join-Path ${env:ProgramFiles} 'Inno Setup 6\ISCC.exe')+ )+ $iscc = Find-Executable $IsccPath $isccCandidates 'ISCC.exe' '找不到 Inno Setup 6 的 ISCC.exe,请安装 Inno Setup 或使用 -IsccPath 指定路径。'++ if (-not $PythonPath) {+ $cachedPython = Join-Path $repoRoot 'release\.cache\python3.exe'+ if (Test-Path -LiteralPath $cachedPython -PathType Leaf) { $PythonPath = $cachedPython }+ } elseif (-not (Test-Path -LiteralPath $PythonPath -PathType Leaf)) {+ throw "找不到指定的 Python: $PythonPath"+ }++ New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null+ $packages = @()+ foreach ($profile in @('workbuddy-cn', 'workbuddy-ai')) {+ Invoke-WindowsZipBuild -Bash $bash -Profile $profile -ReleaseVersion $Version -CachedPython $PythonPath+ $packages += Invoke-WindowsInstallerBuild -Profile $profile -ReleaseVersion $Version -Compiler $iscc+ }++ Write-Host "`n============================================================"+ Write-Host "Windows 双版本安装包生成完成(版本 $Version)"+ foreach ($package in $packages) {+ $item = Get-Item -LiteralPath $package+ Write-Host ("{0} ({1:N0} bytes)" -f $item.FullName, $item.Length)+ }+ Write-Host "============================================================"+} catch {+ Write-Error $_.Exception.Message+ exit 1+}diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 2dc71df..557c45a 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -29,17 +29,17 @@ const net = require('net');const { spawn, spawnSync } = require('child_process');const {assertSameProcessIdentity,- assertStandardWindowsPrivilege,+ detectWindowsPrivilege,buildNativeProcessQuery,filterVerifiedWindowsProcesses,parseCimProcessResult,resolveWindowsExecutable,sameWindowsPath,selectRunningProfileBinary,- selectUniqueDiscoveredBinary,+ selectPreferredDiscoveredBinary,} = require('./windows-process-boundary.js');const DAEMON_PRIVILEGE = process.platform === 'win32'- ? assertStandardWindowsPrivilege()+ ? detectWindowsPrivilege(): 'standard';// ws(WebSocketServer)用于 DevTools 代理:Electron 的 CDP server 拒绝带 Origin 的 WS 连接// (浏览器必带 Origin → DevTools 前端 "websocket disconnected"),daemon 代理中转去掉 Origin@@ -197,8 +197,8 @@ const DATA_DIR = defaultDataDir();// 1.0.49:主题 CDP 应用增加异常回读/重试,失败主题不再覆盖已保存主题。// 1.0.18:主题应用在页面刷新/切换期间自动重连 CDP,并补充失败诊断。// 1.1.0:Windows launcher 固定传递 profile UI 端口;显式端口冲突时不再递增到相邻 profile。-const DAEMON_VERSION = '1.1.0';-const DAEMON_BUILD_ID = 'release-1.1.0-20260827-cross-platform-queue-settings-fix';+const DAEMON_VERSION = '1.1.1';+const DAEMON_BUILD_ID = 'release-1.1.1-20260827-windows-privilege-path-fixes';const HOST = '127.0.0.1';const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app@@ -1749,7 +1749,10 @@ function resolveWorkBuddyBinary() {'}',].join('; ');for (const candidate of psCmd(command).split(/\r?\n/).map((line) => line.trim()).filter(Boolean)) addCandidate(candidate);- const selected = selectUniqueDiscoveredBinary(PROFILE_BINARY_NAMES, discovered);+ const selected = selectPreferredDiscoveredBinary(PROFILE_BINARY_NAMES, discovered);+ if (discovered.length > 1) {+ log('检测到多个 dormant WorkBuddy 安装目录,按发现优先级选择: ' + selected);+ }return selected ? (wbBinaryCache = selected) : null;}@@ -3131,7 +3134,7 @@ function replaceFileWithRetry(file, content, mode) {const tmp = `${file}.wbs-tmp-${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;fs.writeFileSync(tmp, content, 'utf8');if (mode !== undefined) fs.chmodSync(tmp, mode);- const maxAttempts = process.platform === 'win32' ? 15 : 1;+ const maxAttempts = process.platform === 'win32' ? 80 : 1;let lastError;for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {try {@@ -3140,10 +3143,17 @@ function replaceFileWithRetry(file, content, mode) {} catch (error) {lastError = error;const retryable = process.platform === 'win32' && ['EPERM', 'EACCES', 'EBUSY'].includes(error && error.code);- if (!retryable || attempt === maxAttempts) throw error;- sleepSync(75);+ if (!retryable || attempt === maxAttempts) break;+ // A stale read-only attribute can surface as EPERM independently of a+ // sharing violation. Clearing it is limited to this known config file;+ // the atomic rename remains the only successful write path.+ if (attempt === 1 && error && error.code === 'EPERM') {+ try { fs.chmodSync(file, 0o666); } catch (_) {}+ }+ sleepSync(Math.min(250, 50 + attempt * 10));}}+ try { fs.unlinkSync(tmp); } catch (_) {}throw lastError;}diff --git a/scripts/install-win.ps1 b/scripts/install-win.ps1index 9aef0df..78e6892 100644--- a/scripts/install-win.ps1+++ b/scripts/install-win.ps1@@ -12,12 +12,9 @@ try {$identity = [Security.Principal.WindowsIdentity]::GetCurrent()$principal = New-Object Security.Principal.WindowsPrincipal($identity)$isElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)- if ($isElevated -ne $false) {- [Console]::Error.WriteLine('拒绝以管理员权限运行 WorkDaddy 安装脚本;请使用普通用户终端。')- exit 5- }+ $env:WBSWITCH_PRIVILEGE_MODE = if ($isElevated) { 'elevated' } else { 'standard' }} catch {- [Console]::Error.WriteLine('无法确认当前 PowerShell 为普通用户权限;安装已停止。')+ [Console]::Error.WriteLine('无法确认当前 PowerShell 的 Windows 权限模式;安装已停止。')exit 5}diff --git a/scripts/prepare-win-install.ps1 b/scripts/prepare-win-install.ps1index 1d110dc..8bad292 100644--- a/scripts/prepare-win-install.ps1+++ b/scripts/prepare-win-install.ps1@@ -7,12 +7,9 @@ param(try {$identity = [Security.Principal.WindowsIdentity]::GetCurrent()$principal = New-Object Security.Principal.WindowsPrincipal($identity)- if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -ne $false) {- [Console]::Error.WriteLine('Refusing to prepare WorkDaddy installation with elevated privileges.')- exit 5- }+ $privilege = if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { 'elevated' } else { 'standard' }} catch {- [Console]::Error.WriteLine('Cannot verify that the installer is running as a standard user.')+ [Console]::Error.WriteLine('Cannot determine the Windows privilege mode for the installer.')exit 5}@@ -23,7 +20,7 @@ $diagnosticFile = Join-Path ([IO.Path]::GetTempPath()) 'WorkDaddy-prepare-instaltry {[IO.File]::AppendAllText($diagnosticFile,- ('[' + [DateTime]::UtcNow.ToString('o') + '] start profile=' + $Profile + ' appDir=' + $AppDir + [Environment]::NewLine),+ ('[' + [DateTime]::UtcNow.ToString('o') + '] start profile=' + $Profile + ' privilege=' + $privilege + ' appDir=' + $AppDir + [Environment]::NewLine),(New-Object Text.UTF8Encoding($false))). $BoundaryPath$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'diff --git a/scripts/uninstall-win.ps1 b/scripts/uninstall-win.ps1index a79b639..f26e40b 100644--- a/scripts/uninstall-win.ps1+++ b/scripts/uninstall-win.ps1@@ -12,12 +12,9 @@ try {$identity = [Security.Principal.WindowsIdentity]::GetCurrent()$principal = New-Object Security.Principal.WindowsPrincipal($identity)$isElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)- if ($isElevated -ne $false) {- [Console]::Error.WriteLine('拒绝以管理员权限运行 WorkDaddy 卸载脚本;请使用普通用户终端。')- exit 5- }+ $env:WBSWITCH_PRIVILEGE_MODE = if ($isElevated) { 'elevated' } else { 'standard' }} catch {- [Console]::Error.WriteLine('无法确认当前 PowerShell 为普通用户权限;卸载已停止。')+ [Console]::Error.WriteLine('无法确认当前 PowerShell 的 Windows 权限模式;卸载已停止。')exit 5}diff --git a/scripts/watchdog.js b/scripts/watchdog.jsindex 2b8000b..ee2f746 100644--- a/scripts/watchdog.js+++ b/scripts/watchdog.js@@ -17,7 +17,7 @@ const os = require('os');const { spawn, spawnSync } = require('child_process');const {assertSameProcessIdentity,- assertStandardWindowsPrivilege,+ detectWindowsPrivilege,assertVerifiedNodeProcess,buildNativeProcessQuery,filterVerifiedNodeProcesses,@@ -25,7 +25,7 @@ const {} = require('./windows-process-boundary.js');const { getProfile, profileDataDir } = require('./profiles.js');-if (process.platform === 'win32') assertStandardWindowsPrivilege();+const WINDOWS_PRIVILEGE = process.platform === 'win32' ? detectWindowsPrivilege() : 'standard';const SCRIPTS_DIR = __dirname;const PROFILE_ID = process.env.WBSWITCH_PROFILE || 'workbuddy-cn';diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex e875492..4c67597 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -8,7 +8,8 @@* 3) 否则以自动选择的 CDP 端口启动 → 等端口 → 注入** 由 launcher.cmd 调用(cmd 负责兜底找 node),也可 node win-launcher.js 直接运行。- * 所有操作用户态完成(HKCU / %LOCALAPPDATA% / %APPDATA%),无需管理员权限。+ * 默认按普通用户运行;用户明确以管理员身份启动时,整条 launcher/daemon+ * 链路继承 elevated 模式并在状态中校验,避免混用两个权限层级。*/'use strict';@@ -22,7 +23,7 @@ const {assertDaemonServiceIdentity,assertDaemonTerminationIdentity,assertSameProcessIdentity,- assertStandardWindowsPrivilege,+ detectWindowsPrivilege,assertVerifiedNodeProcess,buildNativeProcessQuery,filterVerifiedNodeProcesses,@@ -31,11 +32,12 @@ const {resolveWindowsExecutable,sameWindowsPath,selectRunningProfileBinary,- selectUniqueDiscoveredBinary,+ selectPreferredDiscoveredBinary,} = require('./windows-process-boundary.js');+let WINDOWS_PRIVILEGE = 'standard';if (process.platform === 'win32') {try {- assertStandardWindowsPrivilege();+ WINDOWS_PRIVILEGE = detectWindowsPrivilege();} catch (error) {console.error(error.message);process.exit(5);@@ -439,7 +441,9 @@ function findNode() {try {if (fs.existsSync(bundled)) return resolveWindowsExecutable(bundled);} catch (_) {}- if (verDirs.length) return resolveWindowsExecutable(verDirs[verDirs.length - 1]);+ if (verDirs.length) {+ try { return resolveWindowsExecutable(verDirs[verDirs.length - 1]); } catch (_) {}+ }try {const r = spawnSync('where.exe', ['node.exe'], { encoding: 'utf8', timeout: 3000, windowsHide: true });const candidate = String(r.stdout || '').split(/\r?\n/).map((line) => line.trim()).find(Boolean);@@ -541,7 +545,10 @@ function findWorkBuddy() {'}',].join('; ');for (const candidate of bestEffortPowerShellLines(scanCommand, '安装目录扫描')) addCandidate(candidate);- const selected = selectUniqueDiscoveredBinary(PROFILE_BINARY_NAMES, discovered);+ const selected = selectPreferredDiscoveredBinary(PROFILE_BINARY_NAMES, discovered);+ if (discovered.length > 1) {+ log('检测到多个 dormant WorkBuddy 安装目录,按发现优先级选择: ' + selected);+ }return selected ? (wbBinaryCache = selected) : null;}@@ -566,10 +573,14 @@ function listenerPids(port) {return [...pids];}-function queryNodeProcesses(nodeBin, pids = null) {+function queryNodeProcesses(nodeBin, pids = null, commandLineHint = '') {if (!nodeBin) throw new Error('Node 运行时路径缺失,无法验证进程');const expectedNode = powershellLiteral(nodeBin);let source = `Get-CimInstance Win32_Process -Filter \"Name = 'node.exe'\" -ErrorAction Stop | Where-Object { $_.ExecutablePath -ieq ${expectedNode} }`;+ if (commandLineHint) {+ const hint = String(commandLineHint).replace(/'/g, "''");+ source += ` | Where-Object { $_.CommandLine -like '*${hint}*' }`;+ }if (pids !== null) {const safePids = [...new Set(pids.map(Number))];if (!safePids.length) return [];@@ -590,7 +601,11 @@ function queryNodeProcesses(nodeBin, pids = null) {}function uniqueNodeProcess(nodeBin, expectedScript) {- const matches = filterVerifiedNodeProcesses(nodeBin, expectedScript, queryNodeProcesses(nodeBin));+ const matches = filterVerifiedNodeProcesses(+ nodeBin,+ expectedScript,+ queryNodeProcesses(nodeBin, null, path.basename(expectedScript))+ );if (matches.length > 1) throw new Error(`目标 Node 入口存在多个进程: ${expectedScript}`);return matches[0] || null;}@@ -611,9 +626,21 @@ function watchdogState(nodeBin) {const pid = readWatchdogPid();const exact = uniqueNodeProcess(nodeBin, WATCHDOG_SCRIPT);if (!pid) return exact ? { kind: 'untracked', pid: null, process: exact } : { kind: 'absent', pid: null };- const processes = queryNodeProcesses(nodeBin, [pid]);+ let processes;+ try {+ processes = queryNodeProcesses(nodeBin, [pid], path.basename(WATCHDOG_SCRIPT));+ } catch (error) {+ if (!exact || exact.ProcessId === pid) throw error;+ processes = [];+ }if (processes.length === 0) {- if (exact) throw new Error('watchdog.pid 指向不存在的 PID,但发现了另一个精确 watchdog 进程');+ if (exact) {+ const current = readWatchdogPid();+ if (current !== pid) throw new Error('watchdog.pid 在修复前发生变化');+ fs.writeFileSync(WATCHDOG_PID_FILE, String(exact.ProcessId), 'utf8');+ log(`watchdog.pid 已从陈旧 PID=${pid} 修复为精确 PID=${exact.ProcessId}`);+ return { kind: 'verified', pid: exact.ProcessId, process: exact };+ }return { kind: 'stale', pid };}const process = assertVerifiedNodeProcess(pid, nodeBin, WATCHDOG_SCRIPT, processes);@@ -634,7 +661,7 @@ function validateDaemonProcess(nodeBin, status = null) {return { listenerPids: listeners, nodeProcesses: processes };}-function exactDaemonStatus(nodeBin, status) {+function exactDaemonStatus(nodeBin, status, allowPrivilegeMismatch = false) {const identity = readDaemonIdentity();const processIdentity = validateDaemonProcess(nodeBin, status);assertDaemonServiceIdentity({@@ -645,6 +672,7 @@ function exactDaemonStatus(nodeBin, status) {listenerPids: processIdentity.listenerPids,expectedNode: nodeBin,expectedScript: DAEMON_SCRIPT,+ expectedPrivilege: allowPrivilegeMismatch ? '' : WINDOWS_PRIVILEGE,nodeProcesses: processIdentity.nodeProcesses,});return status;@@ -685,7 +713,7 @@ function killVerifiedNodeProcess(process, nodeBin, expectedScript) {return true;}-function authorizeDaemonTermination(nodeBin, status) {+function authorizeDaemonTermination(nodeBin, status, allowLowerPrivilege = false) {const processIdentity = validateDaemonProcess(nodeBin, status);return assertDaemonTerminationIdentity({status,@@ -693,6 +721,7 @@ function authorizeDaemonTermination(nodeBin, status) {listenerPids: processIdentity.listenerPids,expectedNode: nodeBin,expectedScript: DAEMON_SCRIPT,+ expectedPrivilege: allowLowerPrivilege ? '' : WINDOWS_PRIVILEGE,nodeProcesses: processIdentity.nodeProcesses,});}@@ -704,7 +733,7 @@ function removeWatchdogPidIf(pid) {fs.unlinkSync(WATCHDOG_PID_FILE);}-async function stopDaemonByPort(nodeBin) {+async function stopDaemonByPort(nodeBin, allowLowerPrivilege = false) {const watchdog = watchdogState(nodeBin);if (watchdog.kind === 'untracked') {throw new Error('发现没有当前 profile PID 文件的 watchdog 进程,拒绝复用或结束');@@ -722,12 +751,12 @@ async function stopDaemonByPort(nodeBin) {if (!status || listeners.length !== 1) {throw new Error('daemon 未绑定当前 UI 端口与当前 profile 状态,拒绝结束');}- authorizedDaemon = authorizeDaemonTermination(nodeBin, status);+ authorizedDaemon = authorizeDaemonTermination(nodeBin, status, allowLowerPrivilege);if (!daemon || daemon.ProcessId !== authorizedDaemon.ProcessId) {throw new Error('daemon 监听 PID 与枚举到的精确 daemon 进程不一致');}const identity = readDaemonIdentity();- if (status.version === identity.version && status.buildId === identity.buildId) {+ if (!allowLowerPrivilege && status.version === identity.version && status.buildId === identity.buildId) {throw new Error('daemon 版本与构建已匹配,拒绝结束当前实例');}}@@ -753,15 +782,41 @@ async function ensureDaemon(nodeBin) {const status = await readStatus();const listeners = listenerPids(UI_PORT);if (status || listeners.length) {- authorizeDaemonTermination(nodeBin, status);- const identity = readDaemonIdentity();- if (status.version === identity.version && status.buildId === identity.buildId) {- exactDaemonStatus(nodeBin, status);- log('daemon 身份、版本、构建和权限均已验证,跳过启动');- return true;+ let upgradedPrivilege = false;+ try {+ authorizeDaemonTermination(nodeBin, status);+ } catch (error) {+ // An explicitly elevated launcher may replace an older standard daemon.+ // The inverse transition is refused because a standard process cannot+ // safely terminate an elevated one.+ if (WINDOWS_PRIVILEGE === 'elevated' && status && status.privilege === 'standard') {+ log('检测到旧 daemon 为 standard,当前 launcher 为 elevated,准备升级权限模式');+ await stopDaemonByPort(nodeBin, true);+ upgradedPrivilege = true;+ } else if (WINDOWS_PRIVILEGE === 'standard' && status && status.privilege === 'elevated') {+ // 普通权限无法安全终止 elevated daemon。若其身份、版本和构建均已+ // 匹配,则复用这个同用户、同 profile 的服务,让桌面快捷方式可幂等打开。+ const identity = readDaemonIdentity();+ if (status.version === identity.version && status.buildId === identity.buildId) {+ exactDaemonStatus(nodeBin, status, true);+ log('检测到已匹配的 elevated daemon,普通权限 launcher 复用现有服务');+ return true;+ }+ throw error;+ } else {+ throw error;+ }+ }+ if (!upgradedPrivilege) {+ const identity = readDaemonIdentity();+ if (status.version === identity.version && status.buildId === identity.buildId) {+ exactDaemonStatus(nodeBin, status);+ log('daemon 身份、版本、构建和权限均已验证,跳过启动');+ return true;+ }+ log('daemon 版本或构建不匹配,停止已绑定当前 profile 的旧进程');+ await stopDaemonByPort(nodeBin);}- log('daemon 版本或构建不匹配,停止已绑定当前 profile 的旧进程');- await stopDaemonByPort(nodeBin);}let watchdog = watchdogState(nodeBin);@@ -887,7 +942,7 @@ async function quitWorkBuddy(binary) {log(`[exit] 无法确认退出 profile=${PROFILE.id} final=${JSON.stringify(final)}`);const names = final.processes.map((p) => p.name).filter(Boolean).join(',') || 'unknown';const pidsLeft = final.processes.map((p) => p.pid).filter(Boolean).join(',') || 'unknown';- throw new Error(`${PROFILE.name} 无法以普通用户权限安全退出(剩余镜像=${names}; PID=${pidsLeft})。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试`);+ throw new Error(`${PROFILE.name} 无法在当前权限模式下安全退出(剩余镜像=${names}; PID=${pidsLeft})。请手动关闭该程序,并用相同权限重新启动 WorkDaddy`);}function launchWorkBuddy(wb) {@@ -1052,7 +1107,7 @@ if (require.main === module) (async () => {return;}- log('重启 WorkBuddy(带 --remote-debugging-port=' + CDP_PORT + ',GUI 使用当前用户权限): ' + wb);+ log('重启 WorkBuddy(带 --remote-debugging-port=' + CDP_PORT + ',GUI 继承当前启动权限): ' + wb);console.log('正在以调试模式重启 WorkBuddy(约几秒)...');showWindowsNotification('WorkBuddy', '正在打开 WorkBuddy,请稍等…');diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.issindex 2e626e6..3394ad3 100644--- a/scripts/win/workdaddy.iss+++ b/scripts/win/workdaddy.iss@@ -98,6 +98,8 @@ beginResult := '无法启动安装前的 WorkDaddy 进程检查。';exit;end;- if ResultCode <> 0 then+ if ResultCode = 5 then+ Result := '安装前检查无法确认 Windows 权限模式。请直接双击安装程序重试;如使用了企业安全策略,请联系管理员。'+ else if ResultCode <> 0 thenResult := '无法安全停止现有 WorkDaddy 进程(退出码 ' + IntToStr(ResultCode) + ')。请完全退出客户端后重试。';end;diff --git a/scripts/windows-process-boundary.js b/scripts/windows-process-boundary.jsindex 274ca5d..dcb62ac 100644--- a/scripts/windows-process-boundary.js+++ b/scripts/windows-process-boundary.js@@ -10,7 +10,7 @@ const ALLOWED_WORKBUDDY_PROCESS_NAMES = new Set(['codebuddy.exe',]);-function assertStandardWindowsPrivilege(run = spawnSync) {+function detectWindowsPrivilege(run = spawnSync) {const command = "([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)";let result;try {@@ -29,10 +29,16 @@ function assertStandardWindowsPrivilege(run = spawnSync) {}const value = String(result.stdout || '').trim().toLowerCase();if (value === 'false') return 'standard';- if (value === 'true') throw new Error('拒绝以管理员或 elevated 权限运行 WorkDaddy');+ if (value === 'true') return 'elevated';throw new Error('无法确认 Windows 进程是否为普通用户权限');}+function assertStandardWindowsPrivilege(run = spawnSync) {+ const privilege = detectWindowsPrivilege(run);+ if (privilege !== 'standard') throw new Error('拒绝以管理员或 elevated 权限运行 WorkDaddy');+ return privilege;+}+function validateProcessRecord(row, options = {}) {if (!row || typeof row !== 'object' || Array.isArray(row)) {throw new Error('CIM process query returned an invalid process record');@@ -165,7 +171,9 @@ function filterVerifiedWindowsProcesses(expectedBinary, processes, realpath = fslet executable;try {executable = resolveWindowsExecutable(process.ExecutablePath, realpath);- } catch (_) {+ } catch (error) {+ // A process can disappear between CIM enumeration and realpath.+ if (error && error.code === 'ENOENT') continue;throw new Error(`Cannot verify executable path for PID ${process.ProcessId}`);}if (path.win32.basename(executable).toLowerCase() !== name) {@@ -189,7 +197,11 @@ function selectRunningProfileBinary(profileNames, processes, realpath = fs.realpconst process = validateProcessRecord(item);const name = process.Name.toLowerCase();if (!names.has(name)) continue;- const executable = resolveWindowsExecutable(process.ExecutablePath, realpath);+ let executable;+ try { executable = resolveWindowsExecutable(process.ExecutablePath, realpath); } catch (error) {+ if (error && error.code === 'ENOENT') continue;+ throw error;+ }if (path.win32.basename(executable).toLowerCase() !== name) {throw new Error(`Executable name does not match CIM Name for PID ${process.ProcessId}`);}@@ -203,7 +215,11 @@ function selectUniqueDiscoveredBinary(profileNames, candidates, realpath = fs.reconst names = profileNames instanceof Set ? profileNames : new Set(profileNames || []);const binaries = new Map();for (const candidate of Array.isArray(candidates) ? candidates : []) {- const executable = resolveWindowsExecutable(candidate, realpath);+ let executable;+ try { executable = resolveWindowsExecutable(candidate, realpath); } catch (error) {+ if (error && error.code === 'ENOENT') continue;+ throw error;+ }if (!names.has(path.win32.basename(executable).toLowerCase())) continue;binaries.set(executable.toLowerCase(), executable);}@@ -213,14 +229,46 @@ function selectUniqueDiscoveredBinary(profileNames, candidates, realpath = fs.rereturn binaries.size ? Array.from(binaries.values())[0] : null;}+// Discovery order is a priority order in the callers: explicit profile path,+// registry entries, conventional installs, then bounded scans. Dormant copies+// should not make startup fail when the first valid candidate is unambiguous.+function selectPreferredDiscoveredBinary(profileNames, candidates, realpath = fs.realpathSync.native) {+ const names = profileNames instanceof Set ? profileNames : new Set(profileNames || []);+ const seen = new Map();+ for (const candidate of Array.isArray(candidates) ? candidates : []) {+ let executable;+ try { executable = resolveWindowsExecutable(candidate, realpath); } catch (error) {+ if (error && error.code === 'ENOENT') continue;+ throw error;+ }+ if (!names.has(path.win32.basename(executable).toLowerCase())) continue;+ const key = executable.toLowerCase();+ if (!seen.has(key)) seen.set(key, executable);+ }+ return seen.size ? Array.from(seen.values())[0] : null;+}+function filterVerifiedNodeProcesses(expectedNode, expectedScript, processes, realpath = fs.realpathSync.native) {- const node = resolveWindowsExecutable(expectedNode, realpath);- const script = resolveWindowsExecutable(expectedScript, realpath);+ let node;+ let script;+ try {+ node = resolveWindowsExecutable(expectedNode, realpath);+ script = resolveWindowsExecutable(expectedScript, realpath);+ } catch (error) {+ // Stale installs and in-flight updates can remove the expected runtime or+ // script after discovery. There is no verified process to return then.+ if (error && error.code === 'ENOENT') return [];+ throw error;+ }const verified = [];for (const item of Array.isArray(processes) ? processes : []) {const process = validateProcessRecord(item, { requireCommandLine: true, requireNativeArguments: true });if (process.Name.toLowerCase() !== 'node.exe') continue;- const executable = resolveWindowsExecutable(process.ExecutablePath, realpath);+ let executable;+ try { executable = resolveWindowsExecutable(process.ExecutablePath, realpath); } catch (error) {+ if (error && error.code === 'ENOENT') continue;+ throw error;+ }if (!sameWindowsFilePath(executable, node)) continue;const args = process.Arguments;let entryIndex = 1;@@ -257,7 +305,12 @@ function assertDaemonTerminationIdentity(options) {if (!status || typeof status !== 'object') throw new Error('daemon status is missing');const profileId = status.profile && status.profile.id;if (profileId !== options.expectedProfileId) throw new Error('daemon profile mismatch');- if (status.privilege !== 'standard') throw new Error('daemon privilege is not standard');+ if (status.privilege !== 'standard' && status.privilege !== 'elevated') {+ throw new Error('daemon privilege is invalid');+ }+ if (options.expectedPrivilege && status.privilege !== options.expectedPrivilege) {+ throw new Error(`daemon privilege mismatch: expected ${options.expectedPrivilege}, got ${status.privilege}`);+ }const pid = status.pid;if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('daemon status PID is invalid');const listenerPids = Array.from(new Set((options.listenerPids || []).map(Number)));@@ -282,6 +335,7 @@ module.exports = {assertDaemonServiceIdentity,assertDaemonTerminationIdentity,assertSameProcessIdentity,+ detectWindowsPrivilege,assertStandardWindowsPrivilege,assertVerifiedNodeProcess,buildNativeProcessQuery,@@ -291,6 +345,7 @@ module.exports = {resolveWindowsExecutable,sameWindowsPath,selectRunningProfileBinary,+ selectPreferredDiscoveredBinary,selectUniqueDiscoveredBinary,selectVerifiedProcessPids,};diff --git a/scripts/windows-process-boundary.ps1 b/scripts/windows-process-boundary.ps1index 19f1a31..32c4480 100644--- a/scripts/windows-process-boundary.ps1+++ b/scripts/windows-process-boundary.ps1@@ -245,10 +245,19 @@ function Get-UniqueNodeProcessForScript {[int]$ExpectedParentProcessId = 0)$matches = @()+ $scriptName = [IO.Path]::GetFileName($ExpectedScript)+ if ([string]::IsNullOrWhiteSpace($scriptName) -or+ $scriptName.IndexOfAny([char[]]@([char]0, [char]10, [char]13, [char]39)) -ge 0) {+ throw '目标 Node 入口脚本名称无效'+ }+ $scriptName = $scriptName.Replace("'", "''")$currentSessionId = [int](Get-Process -Id $PID -ErrorAction Stop).SessionId+ # 先让 CIM 在服务端按可信脚本名筛选,避免同会话中无关的受保护 Node+ # 进程(命令行/路径不可读)阻断当前 profile 的精确身份验证。+ $commandHint = " AND CommandLine LIKE '%$scriptName%'"$filter = if ($ExpectedParentProcessId -gt 0) {- "Name = 'node.exe' AND SessionId = $currentSessionId AND ParentProcessId = $ExpectedParentProcessId"- } else { "Name = 'node.exe' AND SessionId = $currentSessionId" }+ "Name = 'node.exe' AND SessionId = $currentSessionId AND ParentProcessId = $ExpectedParentProcessId$commandHint"+ } else { "Name = 'node.exe' AND SessionId = $currentSessionId$commandHint" }$rows = @(Get-CimInstance Win32_Process -Filter $filter -ErrorAction Stop)foreach ($row in $rows) {if ([string]$row.Name -ine 'node.exe' -or@@ -360,21 +369,52 @@ function Stop-VerifiedWorkDaddyLifecycle {# 子进程,避免无关或其他会话中不可读取命令行的 Node 阻断当前 profile。# PID 文件缺失或 stale 时仍扫描完整 Node 列表,证明没有未跟踪实例。$watchdog = $null+ $pidFilePid = $watchdogPidif ($pidFileExists) {- $pidCandidate = Get-StrictProcessRecord -ProcessId $watchdogPid+ $pidCandidate = $null+ $pidProbeError = $null+ try {+ $pidCandidate = Get-StrictProcessRecord -ProcessId $watchdogPid+ } catch {+ # A stale PID can be reused by an unrelated/protected process whose CIM+ # identity is incomplete. Recover only when a separately enumerated,+ # exact watchdog proves the current profile still owns the lifecycle.+ $pidProbeError = $_+ }if ($null -ne $pidCandidate) {$watchdog = Assert-NodeProcessIdentity -Process $pidCandidate -ExpectedPid $watchdogPid -ExpectedScript $ExpectedWatchdogScript} else {- $watchdog = Get-UniqueNodeProcessForScript -ExpectedScript $ExpectedWatchdogScript+ $replacementWatchdog = Get-UniqueNodeProcessForScript -ExpectedScript $ExpectedWatchdogScript+ if ($null -ne $replacementWatchdog) {+ $currentPidText = (Get-Content -LiteralPath $pidFile -Raw -ErrorAction Stop).Trim()+ if ($currentPidText -cne [string]$pidFilePid) {+ throw 'watchdog.pid 在修复前发生变化'+ }+ [IO.File]::WriteAllText(+ $pidFile,+ [string]$replacementWatchdog.ProcessId,+ (New-Object Text.UTF8Encoding($false)))+ $watchdogPid = [int]$replacementWatchdog.ProcessId+ $watchdog = $replacementWatchdog+ } elseif ($null -ne $pidProbeError) {+ throw $pidProbeError+ }if ($null -ne $watchdog) {- throw 'watchdog.pid 指向不存在的 PID,但发现了另一个精确 watchdog 进程'+ # The PID file was stale/reused; the exact replacement above is now+ # the only lifecycle candidate and has been persisted atomically enough+ # for the subsequent identity re-checks.+ } elseif ($null -eq $pidCandidate) {+ $staleWatchdogPidFile = $true}- $staleWatchdogPidFile = $true}} else {$watchdog = Get-UniqueNodeProcessForScript -ExpectedScript $ExpectedWatchdogScript}+ # Stop the verified watchdog before taking the daemon/listener snapshot. This+ # prevents its restart loop from changing the listener PID mid-validation.+ if ($null -ne $watchdog) { Stop-VerifiedProcess -Process $watchdog }+$listenerPid = Get-UniqueListeningProcessId -Port $Port$daemon = if ($null -ne $watchdog) {Get-UniqueNodeProcessForScript -ExpectedScript $ExpectedDaemonScript -ExpectedParentProcessId ([int]$watchdog.ProcessId)@@ -391,7 +431,6 @@ function Stop-VerifiedWorkDaddyLifecycle {}# 所有候选先完成身份验证;外来监听进程不会导致任何 WorkDaddy 进程被提前终止。- if ($null -ne $watchdog) { Stop-VerifiedProcess -Process $watchdog }if ($null -ne $daemon) {$currentListenerPid = Get-UniqueListeningProcessId -Port $Port# watchdog 退出后 daemon 可能自行退出并先释放端口;只有被其他 PIDdiff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex d18f9c4..b729f29 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -388,9 +388,11 @@ test('daemon settings writes tolerate transient Windows file locks', () => {assert.ok(helperStart >= 0 && helperEnd > helperStart, 'atomic replacement helper must exist');const helper = daemon.slice(helperStart, helperEnd);assert.match(helper, /\.wbs-tmp-\$\{process\.pid\}-\$\{Date\.now\(\)\}-\$\{crypto\.randomBytes\(/);- assert.match(helper, /process\.platform === 'win32' \? 15 : 1/);+ assert.match(helper, /process\.platform === 'win32' \? 80 : 1/);assert.match(helper, /\['EPERM', 'EACCES', 'EBUSY'\]/);- assert.match(helper, /sleepSync\(75\)/);+ assert.match(helper, /sleepSync\(Math\.min\(250, 50 \+ attempt \* 10\)\)/);+ assert.match(helper, /chmodSync\(file, 0o666\)/);+ assert.match(helper, /unlinkSync\(tmp\)/);assert.doesNotMatch(helper, /unlinkSync\(file\)|rmSync\(file\)/);const settingsStart = daemon.indexOf('function writeWorkbuddySettings(');@@ -567,6 +569,9 @@ test('Windows Setup stops a verified lifecycle before replacing bundled Node', (assert.match(installer, /ExtractTemporaryFile\('windows-process-boundary\.ps1'\)/);assert.match(installer, /ewWaitUntilTerminated/);assert.match(prepare, /Stop-VerifiedWorkDaddyLifecycle/);+ assert.match(prepare, /\$privilege = if \(\$principal\.IsInRole/);+ assert.doesNotMatch(prepare, /Refusing to prepare WorkDaddy installation with elevated privileges/);+ assert.match(installer, /ResultCode = 5/);assert.match(prepare, /WorkDaddy-prepare-install\.log/);assert.match(prepare, /-ExpectedWatchdogScript \(Join-Path \$AppDir 'scripts\\watchdog\.js'\)/);assert.match(verify, /prepare-win-install\.ps1/);diff --git a/test/windows-launcher-boundary-repair.test.js b/test/windows-launcher-boundary-repair.test.jsindex d43b3f9..34a630e 100644--- a/test/windows-launcher-boundary-repair.test.js+++ b/test/windows-launcher-boundary-repair.test.js@@ -113,9 +113,13 @@ test('lifecycle entry matching rejects unexpected trailing arguments', () => {test('launcher enumerates exact lifecycle entries and never kills process trees', () => {assert.doesNotMatch(launcherSource, /taskkill[^\r\n]*['"]\/T['"]/i);assert.doesNotMatch(launcherSource, /includeTree/);- assert.match(launcherSource, /queryNodeProcesses\(nodeBin\)/);+ assert.match(launcherSource, /queryNodeProcesses\(nodeBin/);assert.match(launcherSource, /uniqueNodeProcess\(nodeBin, WATCHDOG_SCRIPT\)/);assert.match(launcherSource, /uniqueNodeProcess\(nodeBin, DAEMON_SCRIPT\)/);+ assert.match(launcherSource, /queryNodeProcesses\(nodeBin, null, path\.basename\(expectedScript\)\)/);+ assert.match(launcherSource, /watchdog\.pid 已从陈旧 PID=/);+ assert.match(launcherSource, /普通权限 launcher 复用现有服务/);+ assert.match(launcherSource, /exactDaemonStatus\(nodeBin, status, true\)/);assert.match(launcherSource, /assertSameProcessIdentity/);assert.match(launcherSource, /requireCurrentOwner:\s*true/);for (const source of [launcherSource, daemonSource, watchdogSource]) {@@ -142,6 +146,7 @@ test('daemon termination authorization is bound to current profile status and liconst input = {status: { pid: 716, profile: { id: 'workbuddy-cn' }, privilege: 'standard' },expectedProfileId: 'workbuddy-cn',+ expectedPrivilege: 'standard',listenerPids: [716],expectedNode: node,expectedScript: script,@@ -216,6 +221,16 @@ test('Windows launcher and watchdog recover a PID file whose process is gone', (assert.match(watchdogSource, /existing\.kind === 'stale'[\s\S]*removePidFileIf\(existing\.pid\)/);});+test('Windows launcher reconciles a reused PID file to an exact watchdog', () => {+ const stateSource = launcherSource.slice(+ launcherSource.indexOf('function watchdogState'),+ launcherSource.indexOf('function validateDaemonProcess')+ );+ assert.match(stateSource, /queryNodeProcesses\(nodeBin, \[pid\], path\.basename\(WATCHDOG_SCRIPT\)\)/);+ assert.match(stateSource, /if \(exact\) \{[\s\S]*fs\.writeFileSync\(WATCHDOG_PID_FILE, String\(exact\.ProcessId\)/);+ assert.match(stateSource, /watchdog\.pid 在修复前发生变化/);+});+test('Windows process queries are scoped to the selected Node runtime', () => {assert.match(launcherSource, /ExecutablePath -ieq/);assert.match(watchdogSource, /ExecutablePath -ieq/);@@ -262,7 +277,7 @@ test('Windows cold-start guards an already running WorkBuddy and sends a native});test('Windows daemon repairs only missing cwd directories with stored session payloads', () => {- assert.match(daemonSource, /const DAEMON_VERSION = '1\.1\.0'/);+ assert.match(daemonSource, /const DAEMON_VERSION = '1\.1\.1'/);assert.match(daemonSource, /function sessionPayloadExists\(wbHome, sessionId\)/);assert.match(daemonSource, /function createDirectoryNoFollow\(directory\)/);assert.match(daemonSource, /repairMissingSessionWorkspaces\(\)\.catch/);diff --git a/test/windows-powershell-boundary.test.js b/test/windows-powershell-boundary.test.jsindex 47fc011..1a024eb 100644--- a/test/windows-powershell-boundary.test.js+++ b/test/windows-powershell-boundary.test.js@@ -11,7 +11,7 @@ const scriptsDir = path.join(root, 'scripts');const helperPath = path.join(scriptsDir, 'windows-process-boundary.ps1');const lifecycleScripts = ['install-win.ps1', 'uninstall-win.ps1', 'apply-update.ps1'];-test('PowerShell lifecycle scripts reject elevation before side effects', () => {+test('PowerShell lifecycle scripts detect privilege mode before side effects', () => {for (const name of lifecycleScripts) {const source = fs.readFileSync(path.join(scriptsDir, name), 'utf8');const probe = source.indexOf('IsInRole');@@ -78,6 +78,11 @@ test('PowerShell source validates owner, exact launcher token, PID, and listenerassert.match(helper, /\[string\]\$Status\.version -cne \$ExpectedVersion/);assert.match(helper, /Get-UniqueNodeProcessForScript -ExpectedScript \$ExpectedWatchdogScript/);assert.match(helper, /Get-UniqueNodeProcessForScript -ExpectedScript \$ExpectedDaemonScript -ExpectedParentProcessId/);+ assert.match(helper, /CommandLine LIKE '%\$scriptName%'/);+ assert.match(helper, /目标 Node 入口脚本名称无效/);+ assert.match(helper, /pidProbeError/);+ assert.match(helper, /replacementWatchdog/);+ assert.match(helper, /Stop the verified watchdog before taking the daemon\/listener snapshot/);assert.match(helper, /Stop-VerifiedProcess/);assert.match(helper, /function Stop-VerifiedWorkBuddyProcesses/);assert.match(helper, /多个 WorkBuddy 安装正在运行/);diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.jsindex ec37c69..cd6cbee 100644--- a/test/windows-privilege-boundary.test.js+++ b/test/windows-privilege-boundary.test.js@@ -25,8 +25,10 @@ const nativeProcess = (process, args) => ({Arguments: args,});-test('privilege probe accepts only an explicit standard-user result', () => {+test('privilege probe distinguishes standard and elevated modes', () => {const fake = (result) => () => result;+ assert.equal(boundary.detectWindowsPrivilege(fake({ status: 0, stdout: 'False\r\n' })), 'standard');+ assert.equal(boundary.detectWindowsPrivilege(fake({ status: 0, stdout: 'True\r\n' })), 'elevated');assert.equal(boundary.assertStandardWindowsPrivilege(fake({ status: 0, stdout: 'False\r\n' })), 'standard');assert.throws(() => boundary.assertStandardWindowsPrivilege(fake({ status: 0, stdout: 'True\r\n' })), /管理员|elevated/i);assert.throws(() => boundary.assertStandardWindowsPrivilege(fake({ status: 0, stdout: '' })), /确认|determine/i);@@ -110,6 +112,31 @@ test('disk discovery rejects duplicate current-profile installations', () => {);});+test('dormant duplicate installations use discovery priority while missing paths are ignored', () => {+ const resolveMissing = (value) => {+ if (String(value).includes('missing')) {+ const error = new Error('not found');+ error.code = 'ENOENT';+ throw error;+ }+ return path.win32.normalize(value);+ };+ assert.equal(+ boundary.selectPreferredDiscoveredBinary(+ new Set(['workbuddy.exe']),+ ['C:\\missing\\WorkBuddy.exe', 'D:\\Preferred\\WorkBuddy.exe', 'E:\\Old\\WorkBuddy.exe'],+ resolveMissing+ ),+ path.win32.normalize('D:\\Preferred\\WorkBuddy.exe')+ );+ assert.deepEqual(+ boundary.filterVerifiedNodeProcesses(+ 'C:\\missing\\node.exe', 'C:\\missing\\daemon.js', [], resolveMissing+ ),+ []+ );+});+test('daemon status identity binds metadata, listener PID, node path, and script path', () => {const expectedNode = 'C:\\Node\\node.exe';const expectedScript = 'C:\\WorkDaddy\\scripts\\daemon.js';@@ -120,25 +147,33 @@ test('daemon status identity binds metadata, listener PID, node path, and scriptconst status = { version: '1.0.14', buildId: 'build-a', profile: { id: 'workbuddy-cn' }, privilege: 'standard', pid: 301 };const input = {status,- expectedVersion: '1.0.14', expectedBuildId: 'build-a', expectedProfileId: 'workbuddy-cn',+ expectedVersion: '1.0.14', expectedBuildId: 'build-a', expectedProfileId: 'workbuddy-cn', expectedPrivilege: 'standard',listenerPids: [301], nodeProcesses: [process], expectedNode, expectedScript, realpath: resolveWindows,};assert.equal(boundary.assertDaemonServiceIdentity(input).ProcessId, 301);+ assert.equal(+ boundary.assertDaemonServiceIdentity({+ ...input,+ expectedPrivilege: 'elevated',+ status: { ...status, privilege: 'elevated' },+ }).ProcessId,+ 301+ );assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, status: { ...status, buildId: 'old' } }), /build/i);assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, listenerPids: [999] }), /listener|监听|PID/i);assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, status: { ...status, privilege: 'elevated' } }), /privilege|权限/i);assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, status: { ...status, pid: '301' } }), /PID/i);});-test('Windows entry points fail closed and expose a standard daemon identity', () => {+test('Windows entry points detect and expose a matching daemon privilege mode', () => {assert.equal(fs.existsSync(path.join(scriptsDir, 'win-inject-helper.js')), false);- assert.match(launcherSource, /assertStandardWindowsPrivilege/);- assert.match(watchdogSource, /assertStandardWindowsPrivilege/);- assert.match(daemonSource, /assertStandardWindowsPrivilege/);+ assert.match(launcherSource, /detectWindowsPrivilege/);+ assert.match(watchdogSource, /detectWindowsPrivilege/);+ assert.match(daemonSource, /detectWindowsPrivilege/);assert.match(daemonSource, /privilege:\s*DAEMON_PRIVILEGE/);assert.match(daemonSource, /pid:\s*process\.pid/);assert.match(launcherSource, /assertDaemonServiceIdentity/);- const privilegeProbe = launcherSource.indexOf('assertStandardWindowsPrivilege();');+ const privilegeProbe = launcherSource.indexOf('detectWindowsPrivilege();');const telemetryImport = launcherSource.indexOf('const { captureMessage');assert.ok(privilegeProbe >= 0 && telemetryImport > privilegeProbe);const privilegeFailure = launcherSource.slice(privilegeProbe, telemetryImport);@@ -164,6 +199,7 @@ test('Windows entry points fail closed and expose a standard daemon identity', (assert.match(watchdogSource, /if \(state\.kind === 'stale'\) \{[\s\S]*removePidFileIf\(state\.pid\)/);assert.match(launcherSource, /if \(watchdog\.kind === 'stale'\) \{[\s\S]*removeWatchdogPidIf\(watchdog\.pid\)/);assert.match(launcherSource, /queryNodeProcesses\(nodeBin, \[pid\]\)/);+ assert.match(launcherSource, /allowLowerPrivilege/);assert.match(watchdogSource, /ExecutablePath -ieq/);assert.doesNotMatch(launcherSource + daemonSource, /Start-Process[^\n]*-Verb\s+RunAs/i);assert.doesNotMatch(installerSource, /请以管理员身份运行/);diff --git a/test/windows-release-script.test.js b/test/windows-release-script.test.jsnew file mode 100644index 0000000..2f5d6a3--- /dev/null+++ b/test/windows-release-script.test.js@@ -0,0 +1,23 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');++const scriptPath = path.join(__dirname, '..', 'scripts', 'build-win-release.ps1');+const launcherPath = path.join(__dirname, '..', 'scripts', 'build-win-release.cmd');+const source = fs.readFileSync(scriptPath, 'utf8');+const launcher = fs.readFileSync(launcherPath, 'utf8');++test('Windows release script interactively builds both profiles for one version', () => {+ assert.match(source, /Read-Host\s+"[^"]*版本号/);+ assert.match(source, /\$Version -notmatch '\^\\d\+\\\.\\d\+\\\.\\d\+\$'/);+ assert.match(source, /foreach \(\$profile in @\('workbuddy-cn', 'workbuddy-ai'\)\)/);+ assert.match(source, /build-win-zip\.sh/);+ assert.match(source, /build-win-installer\.ps1/);+ assert.match(source, /WORKDADDY_BUILD_PROFILE/);+ assert.match(source, /-Version \$ReleaseVersion/);+ assert.match(launcher, /build-win-release\.ps1/);+ assert.match(launcher, /ExecutionPolicy Bypass/);+});