WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
修复问题
[email protected]8cd8abae60d4
diff --git a/release/macos/WorkDaddy-1.0.18.dmg b/release/macos/WorkDaddy-1.1.1.dmgsimilarity index 73%rename from release/macos/WorkDaddy-1.0.18.dmgrename to release/macos/WorkDaddy-1.1.1.dmgindex 1031187..d5d6e0a 100644Binary files a/release/macos/WorkDaddy-1.0.18.dmg and b/release/macos/WorkDaddy-1.1.1.dmg differdiff --git a/release/macos/WorkDaddy-AI-1.0.18.dmg b/release/macos/WorkDaddy-AI-1.1.1.dmgsimilarity index 74%rename from release/macos/WorkDaddy-AI-1.0.18.dmgrename to release/macos/WorkDaddy-AI-1.1.1.dmgindex 8e7ceb2..1399f57 100644Binary files a/release/macos/WorkDaddy-AI-1.0.18.dmg and b/release/macos/WorkDaddy-AI-1.1.1.dmg differdiff --git a/release/windows/WorkDaddy-AI-Setup-1.1.0.exe b/release/windows/WorkDaddy-AI-Setup-1.1.0.exedeleted file mode 100644index fabfddd..0000000Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.0.exe and /dev/null differdiff --git a/release/windows/WorkDaddy-AI-Setup-1.1.1.exe b/release/windows/WorkDaddy-AI-Setup-1.1.1.exeindex 949bc5b..e40505a 100644Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.1.exe 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.exedeleted file mode 100644index cf76b6f..0000000Binary files a/release/windows/WorkDaddy-Setup-1.1.0.exe and /dev/null differdiff --git a/release/windows/WorkDaddy-Setup-1.1.1.exe b/release/windows/WorkDaddy-Setup-1.1.1.exeindex 16e08c4..6d3a993 100644Binary files a/release/windows/WorkDaddy-Setup-1.1.1.exe and b/release/windows/WorkDaddy-Setup-1.1.1.exe differdiff --git a/scripts/build-win-installer.ps1 b/scripts/build-win-installer.ps1index b71b727..e3bc3bb 100644--- a/scripts/build-win-installer.ps1+++ b/scripts/build-win-installer.ps1@@ -65,8 +65,6 @@ try {if (-not (Test-Path -LiteralPath $prompt -PathType Leaf)) {throw 'The ZIP payload is missing 安装失败自主解决提示词.txt.'}- Copy-Item -LiteralPath $prompt -Destination (Join-Path $stageRoot 'troubleshooting.txt') -Force-$iss = Join-Path $scriptsRoot 'win\workdaddy.iss'$args = @("/DAppVersion=$version",diff --git a/scripts/build-win-release.ps1 b/scripts/build-win-release.ps1index 3cb4fab..262cabf 100644--- a/scripts/build-win-release.ps1+++ b/scripts/build-win-release.ps1@@ -1,4 +1,4 @@-[CmdletBinding()]+[CmdletBinding()]param([string]$Version = '',[string]$OutputDirectory = '',@@ -90,7 +90,7 @@ function Invoke-WindowsInstallerBuild {-Profile $Profile `-Version $ReleaseVersion `-OutputDirectory $OutputDirectory `- -IsccPath $Compiler+ -IsccPath $Compiler | Out-Hostif ($LASTEXITCODE -ne 0) {throw "$Profile Setup.exe 生成失败(退出码 $LASTEXITCODE)。"}diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 557c45a..7039cc7 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -198,7 +198,7 @@ const DATA_DIR = defaultDataDir();// 1.0.18:主题应用在页面刷新/切换期间自动重连 CDP,并补充失败诊断。// 1.1.0:Windows launcher 固定传递 profile UI 端口;显式端口冲突时不再递增到相邻 profile。const DAEMON_VERSION = '1.1.1';-const DAEMON_BUILD_ID = 'release-1.1.1-20260827-windows-privilege-path-fixes';+const DAEMON_BUILD_ID = 'release-1.1.1-20260827-windows-standard-launch-normalization';const HOST = '127.0.0.1';const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.appdiff --git a/scripts/install-win.ps1 b/scripts/install-win.ps1index 78e6892..4c88226 100644--- a/scripts/install-win.ps1+++ b/scripts/install-win.ps1@@ -36,6 +36,7 @@ $uiPort = if ($Profile -eq 'workbuddy-ai') { 47833 } else { 47832 }$env:WBSWITCH_PORT = [string]$uiPort$sentryReporter = Join-Path $SrcDir 'sentry-report.js'$nodeBin = $null+$preserveExistingLifecycle = $false# WorkBuddy 通常自带 Node;安装失败上报不依赖 npm 或 Electron。try {@@ -80,9 +81,30 @@ try {-ExpectedDaemonScript (Join-Path $AppDir 'scripts\daemon.js')Write-InstallLine ' 已停止并清理当前 profile 的旧守护进程。'} catch {- Write-InstallLine ('错误:无法安全停止当前 profile 的旧守护进程: ' + $_.Exception.Message)- Send-Sentry 'windows-install-stop-lifecycle' $_.Exception.Message 2- exit 2+ $stopError = $_.Exception.Message+ if (-not $isElevated) {+ try {+ $sourceDaemon = Get-Content -LiteralPath (Join-Path $SrcDir 'daemon.js') -Raw -Encoding UTF8 -ErrorAction Stop+ $versionMatch = [regex]::Match($sourceDaemon, "const DAEMON_VERSION = '([^']+)'")+ if (-not $versionMatch.Success) { throw '安装源 daemon.js 缺少版本号' }+ [void](Get-AuthenticatedWorkDaddyStatus `+ -DataDir $dataDir `+ -Port $uiPort `+ -ExpectedProfile $Profile `+ -ExpectedVersion $versionMatch.Groups[1].Value `+ -AllowVersionMismatch)+ $preserveExistingLifecycle = $true+ Write-InstallLine ' 检测到已验证的管理员权限旧服务:保留当前运行实例,并继续安装。'+ } catch {+ Write-InstallLine ('错误:安装被后台进程阻止。无法确认并停止当前 WorkDaddy;请先退出 WorkBuddy。详情: ' + $stopError)+ Send-Sentry 'windows-install-stop-lifecycle' $stopError 2+ exit 2+ }+ } else {+ Write-InstallLine ('错误:无法停止当前 WorkDaddy 后台进程。请先退出 WorkBuddy 后重试。详情: ' + $stopError)+ Send-Sentry 'windows-install-stop-lifecycle' $stopError 2+ exit 2+ }}# 1) 复制(排除开发/临时文件;node_modules/ws 随包带入)@@ -105,7 +127,9 @@ if ([StringComparer]::OrdinalIgnoreCase.Equals($sourceFull, $targetFull)) {Send-Sentry 'windows-install-launcher-lock' "无法释放 launcher.cmd 文件锁: $launcherToReplace" 2exit 2}- robocopy $SrcDir $targetScripts /E /XF *.log .DS_Store /XD win\probe /R:2 /W:1+ $copyArgs = @($SrcDir, $targetScripts, '/E', '/XF', '*.log', '.DS_Store', '/XD', (Join-Path $SrcDir 'win\probe'), '/R:2', '/W:1')+ if ($preserveExistingLifecycle) { $copyArgs += @('/XD', (Join-Path $SrcDir 'runtime\node')) }+ & robocopy @copyArgs$rc = $LASTEXITCODEif ($rc -ge 8) {Write-InstallLine "复制失败(robocopy=$rc)"diff --git a/scripts/prepare-win-install.ps1 b/scripts/prepare-win-install.ps1index 8bad292..df61523 100644--- a/scripts/prepare-win-install.ps1+++ b/scripts/prepare-win-install.ps1@@ -1,7 +1,8 @@param([Parameter(Mandatory = $true)][string]$BoundaryPath,[Parameter(Mandatory = $true)][string]$AppDir,- [ValidateSet('workbuddy-cn', 'workbuddy-ai')][string]$Profile = 'workbuddy-cn'+ [ValidateSet('workbuddy-cn', 'workbuddy-ai')][string]$Profile = 'workbuddy-cn',+ [Parameter(Mandatory = $true)][string]$ExpectedVersion)try {@@ -33,12 +34,34 @@ try {-ExpectedDaemonScript (Join-Path $AppDir 'scripts\daemon.js')exit 0} catch {+ $stopError = $_.Exception.Message+ if ($privilege -eq 'standard') {+ try {+ [void](Get-AuthenticatedWorkDaddyStatus `+ -DataDir $dataDir `+ -Port $uiPort `+ -ExpectedProfile $Profile `+ -ExpectedVersion $ExpectedVersion `+ -AllowVersionMismatch)+ [IO.File]::AppendAllText(+ $diagnosticFile,+ ('[' + [DateTime]::UtcNow.ToString('o') + '] preserved authenticated elevated lifecycle profile=' + $Profile ++ ' expectedVersion=' + $ExpectedVersion + [Environment]::NewLine),+ (New-Object Text.UTF8Encoding($false)))+ # Inno treats 10 as a verified compatibility path and skips only the+ # locked bundled runtime. No cross-integrity termination is attempted.+ exit 10+ } catch {+ $capabilityError = $_.Exception.Message+ }+ }try {[IO.File]::AppendAllText($diagnosticFile,- ('[' + [DateTime]::UtcNow.ToString('o') + '] failed profile=' + $Profile + ' error=' + $_.Exception.Message + [Environment]::NewLine),+ ('[' + [DateTime]::UtcNow.ToString('o') + '] failed profile=' + $Profile + ' error=' + $stopError ++ $(if ($capabilityError) { ' capability=' + $capabilityError } else { '' }) + [Environment]::NewLine),(New-Object Text.UTF8Encoding($false)))} catch {}- [Console]::Error.WriteLine('Cannot safely stop the existing WorkDaddy lifecycle: ' + $_.Exception.Message)+ [Console]::Error.WriteLine('Cannot safely stop the existing WorkDaddy lifecycle: ' + $stopError)exit 2}diff --git a/scripts/verify-win.cmd b/scripts/verify-win.cmdindex a4cc046..34d7399 100644--- a/scripts/verify-win.cmd+++ b/scripts/verify-win.cmd@@ -20,7 +20,7 @@ set "FAIL=0"rem ---- 1) 关键文件齐全 ----echo.echo [1/6] 检查关键文件...-for %%F in (daemon.js session-db.js lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 prepare-win-install.ps1 inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (+for %%F in (daemon.js session-db.js lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 windows-relaunch-standard.ps1 prepare-win-install.ps1 inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (if not exist "%SCRIPT_DIR%%%F" (echo 缺失: %%~Fset /a FAIL+=1@@ -75,12 +75,8 @@ echo JS 语法检查完成rem ---- 4) PS1 合法性(PowerShell 解析但不执行)----echo.echo [4/6] 校验 PS1 脚本语法...-for %%F in (windows-process-boundary.ps1 install-win.ps1 uninstall-win.ps1 apply-update.ps1) do (- powershell -NoProfile -ExecutionPolicy Bypass -Command "$e=$null; [void][System.Management.Automation.Language.Parser]::ParseFile('%SCRIPT_DIR%%%F',[ref]$null,[ref]$e); if($e){Write-Host (' 语法错误: ' + $e.Message); exit 1} else {Write-Host (' OK: ' + '%%~nF')}; exit 0" >nul 2>&1- if errorlevel 1 (- echo 语法错误: %%~F- set /a FAIL+=1- )+for %%F in (windows-process-boundary.ps1 windows-relaunch-standard.ps1 prepare-win-install.ps1 install-win.ps1 uninstall-win.ps1 apply-update.ps1) do (+ call :CHECK_PS1 "%SCRIPT_DIR%%%F" "%%~F")rem ---- 5) 自启清理状态与安装目录回写测试(读态 + 安装目录可写性探测)----@@ -122,3 +118,11 @@ echo ============================================================if not defined CI pauseif defined ORIGINAL_CODE_PAGE chcp %ORIGINAL_CODE_PAGE% >nulexit /b %VERIFY_EXIT%++:CHECK_PS1+powershell -NoProfile -ExecutionPolicy Bypass -Command "$tokens=$null; $errors=$null; [void][System.Management.Automation.Language.Parser]::ParseFile('%~1',[ref]$tokens,[ref]$errors); if($errors.Count -gt 0){exit 1}else{exit 0}" >nul 2>&1+if errorlevel 1 (+ echo 语法错误: %~2+ set /a FAIL+=1+)+exit /b 0diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex 4c67597..d9e7b9a 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -8,8 +8,8 @@* 3) 否则以自动选择的 CDP 端口启动 → 等端口 → 注入** 由 launcher.cmd 调用(cmd 负责兜底找 node),也可 node win-launcher.js 直接运行。- * 默认按普通用户运行;用户明确以管理员身份启动时,整条 launcher/daemon- * 链路继承 elevated 模式并在状态中校验,避免混用两个权限层级。+ * 默认按普通用户运行;用户明确以管理员身份启动时,先通过桌面 Shell+ * 重启为标准权限。真正关闭 UAC、没有过滤 token 时才继续当前权限。*/'use strict';@@ -20,6 +20,7 @@ const net = require('net');const http = require('http');const { spawn, spawnSync } = require('child_process');const {+ assertAuthenticatedDaemonCapability,assertDaemonServiceIdentity,assertDaemonTerminationIdentity,assertSameProcessIdentity,@@ -56,6 +57,8 @@ const WBS_BRAND = PROFILE.appName || 'WorkDaddy'; // 品牌显示名跟随 proficonst DATA_DIR =process.env.WBSWITCH_DATA_DIR ||profileDataDir(PROFILE);+const API_TOKEN_FILE = path.join(DATA_DIR, '.api-token');+const DESKTOP_RELAUNCH_ARG = '--desktop-shell-relaunch';const DEFAULT_UI_PORT = { 'workbuddy-cn': 47832, 'workbuddy-ai': 47833, 'codebuddy-cn': 47834, 'codebuddy-intl': 47835 }[PROFILE.id] || 47832;const UI_PORT = parseInt(process.env.WBSWITCH_PORT || String(DEFAULT_UI_PORT), 10);// watchdog/daemon inherit process.env. Persist the resolved profile port so an@@ -99,6 +102,35 @@ function log(...args) {// ---------- 小工具 ----------function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }+function readApiToken() {+ try {+ const token = fs.readFileSync(API_TOKEN_FILE, 'utf8').trim();+ return /^[a-f0-9]{64}$/i.test(token) ? token : '';+ } catch (_) { return ''; }+}++function localApiHeaders() {+ const token = readApiToken();+ return token ? { 'X-WorkDaddy-Token': token } : {};+}++function relaunchWithDesktopShell(nodeBin) {+ const helper = path.join(SCRIPTS_DIR, 'windows-relaunch-standard.ps1');+ if (!fs.existsSync(helper)) throw new Error('缺少标准权限重启脚本 windows-relaunch-standard.ps1');+ const powershell = path.join(+ process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'+ );+ const result = spawnSync(powershell, [+ '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',+ '-File', helper, '-NodePath', nodeBin, '-LauncherPath', __filename,+ ], { encoding: 'utf8', windowsHide: true, timeout: 10000 });+ if (result.error) throw result.error;+ if (result.status !== 0) {+ const detail = String(result.stderr || result.stdout || '').trim();+ throw new Error(`无法通过桌面 Shell 重新启动${detail ? ': ' + detail : ''}`);+ }+}+function runHiddenPowerShell(script) {if (process.platform !== 'win32') return;try {@@ -201,9 +233,9 @@ function isLocalPortAvailable(port) {});}-function httpGet(port, p) {+function httpGet(port, p, headers = {}) {return new Promise((resolve) => {- const req = http.get({ host: HOST, port, path: p, timeout: 1500 }, (res) => {+ const req = http.get({ host: HOST, port, path: p, headers, timeout: 1500 }, (res) => {let body = '';res.on('data', (c) => (body += c));res.on('end', () => resolve({ status: res.statusCode, body }));@@ -213,9 +245,9 @@ function httpGet(port, p) {});}-function httpPost(port, p, timeoutMs = INJECT_REQUEST_TIMEOUT_MS) {+function httpPost(port, p, timeoutMs = INJECT_REQUEST_TIMEOUT_MS, headers = {}) {return new Promise((resolve) => {- const req = http.request({ host: HOST, port, path: p, method: 'POST', timeout: timeoutMs }, (res) => {+ const req = http.request({ host: HOST, port, path: p, method: 'POST', headers, timeout: timeoutMs }, (res) => {let body = '';res.setEncoding('utf8');res.on('data', (chunk) => { body += chunk; if (body.length > 20000) body = body.slice(0, 20000); });@@ -679,12 +711,24 @@ function exactDaemonStatus(nodeBin, status, allowPrivilegeMismatch = false) {}async function readStatus() {- const response = await httpGet(UI_PORT, '/api/status');+ const response = await httpGet(UI_PORT, '/api/status', localApiHeaders());if (!response) return null;if (response.status !== 200) throw new Error(`daemon 状态接口返回 ${response.status}`);try { return JSON.parse(response.body); } catch (_) { throw new Error('daemon 状态接口返回无效 JSON'); }}+function authenticatedElevatedDaemonStatus(status) {+ const identity = readDaemonIdentity();+ return assertAuthenticatedDaemonCapability({+ status,+ expectedProfileId: PROFILE.id,+ expectedVersion: identity.version,+ expectedDataDir: DATA_DIR,+ listenerPids: listenerPids(UI_PORT),+ allowVersionMismatch: true,+ });+}+async function waitForExactDaemon(nodeBin, attempts) {for (let i = 0; i < attempts; i++) {await sleep(400);@@ -794,15 +838,12 @@ async function ensureDaemon(nodeBin) {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;+ // Windows intentionally hides an elevated process's executable and+ // command line from this standard process. The per-profile API token+ // provides a non-termination capability proof for safe reuse.+ authenticatedElevatedDaemonStatus(status);+ log('普通权限 launcher 复用已验证的 elevated 服务;不会跨权限结束进程');+ return true;} else {throw error;}@@ -1035,7 +1076,7 @@ async function injectNow() {// daemon 的 /api/inject 可能需要等待 renderer 完成首屏;客户端断开不代表 daemon 停止注入。let lastError = '注入请求无响应';for (let attempt = 1; attempt <= INJECT_MAX_ATTEMPTS; attempt += 1) {- const response = await httpPost(UI_PORT, '/api/inject');+ const response = await httpPost(UI_PORT, '/api/inject', INJECT_REQUEST_TIMEOUT_MS, localApiHeaders());if (!response) {lastError = '注入请求超时,daemon 仍可能在后台重试';} else {@@ -1084,12 +1125,18 @@ if (require.main === module) (async () => {await reportAndExit(1, '未找到 Node.js(WorkBuddy 托管运行时或 PATH)', 'windows-launcher-node');return;}+ if (process.platform === 'win32' && WINDOWS_PRIVILEGE === 'elevated') {+ if (!process.argv.includes(DESKTOP_RELAUNCH_ARG)) {+ relaunchWithDesktopShell(nodeBin);+ log('管理员入口已通过桌面 Shell 重新派发;当前 elevated launcher 退出');+ process.exit(0);+ }+ log('桌面 Shell 仍返回 elevated token(可能已关闭 UAC),继续使用当前系统权限');+ }await configureCdpPort();await ensureDaemon(nodeBin);- if (requireWorkBuddyClosedBeforeLaunch()) process.exit(0);-// 已在 CDP 模式 → 幂等注入if (await isWorkBuddyCdp()) {if (!(await injectNowOrPending())) process.exit(0);@@ -1098,6 +1145,8 @@ if (require.main === module) (async () => {process.exit(0);}+ if (requireWorkBuddyClosedBeforeLaunch()) process.exit(0);+// 未开 CDP → 需要重启 WorkBuddy 带调试端口const wb = findWorkBuddy();if (!wb) {diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.issindex 3394ad3..80ac7ec 100644--- a/scripts/win/workdaddy.iss+++ b/scripts/win/workdaddy.iss@@ -60,8 +60,9 @@ Name: "chinesesimplified"; MessagesFile: "ChineseSimplified.isl"[Files]Source: "{#StageRoot}\scripts\prepare-win-install.ps1"; Flags: dontcopySource: "{#StageRoot}\scripts\windows-process-boundary.ps1"; Flags: dontcopy-Source: "{#StageRoot}\scripts\*"; DestDir: "{app}\scripts"; Excludes: "prepare-win-install.ps1"; Flags: ignoreversion recursesubdirs createallsubdirs-Source: "{#StageRoot}\troubleshooting.txt"; DestDir: "{app}"; Flags: ignoreversion+Source: "{#StageRoot}\scripts\*"; DestDir: "{app}\scripts"; Excludes: "prepare-win-install.ps1,runtime\node\*"; Flags: ignoreversion recursesubdirs createallsubdirs+Source: "{#StageRoot}\scripts\runtime\node\*"; DestDir: "{app}\scripts\runtime\node"; Flags: ignoreversion recursesubdirs createallsubdirs; Check: ShouldReplaceRuntime+Source: "{#StageRoot}\安装失败自主解决提示词.txt"; DestDir: "{app}"; Flags: ignoreversion[Icons]Name: "{group}\{#ProductName}"; Filename: "{sys}\wscript.exe"; Parameters: "//nologo ""{app}\scripts\launcher-hidden.vbs"""; WorkingDir: "{app}\scripts"; IconFilename: "{app}\scripts\WorkDaddy.ico"@@ -77,6 +78,14 @@ Filename: "{#PowerShellPath}"; Parameters: "-NoProfile -WindowStyle Hidden -ExecType: filesandordirs; Name: "{app}"[Code]+var+ PreserveExistingLifecycle: Boolean;++function ShouldReplaceRuntime(): Boolean;+begin+ Result := not PreserveExistingLifecycle;+end;+function PrepareToInstall(var NeedsRestart: Boolean): String;varResultCode: Integer;@@ -91,15 +100,20 @@ beginParameters := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' +ExpandConstant('{tmp}\prepare-win-install.ps1') + '" -BoundaryPath "' +ExpandConstant('{tmp}\windows-process-boundary.ps1') + '" -AppDir "' +- ExpandConstant('{app}') + '" -Profile "{#ProfileId}"';+ ExpandConstant('{app}') + '" -Profile "{#ProfileId}" -ExpectedVersion "{#AppVersion}"';if not Exec(ExpandConstant('{#PowerShellPath}'), Parameters, '', SW_HIDE,ewWaitUntilTerminated, ResultCode) thenbeginResult := '无法启动安装前的 WorkDaddy 进程检查。';exit;end;- if ResultCode = 5 then- Result := '安装前检查无法确认 Windows 权限模式。请直接双击安装程序重试;如使用了企业安全策略,请联系管理员。'+ if ResultCode = 10 then+ begin+ PreserveExistingLifecycle := True;+ Result := '';+ end+ else if ResultCode = 5 then+ Result := '无法判断安装程序的权限。请关闭安全软件对 PowerShell 的拦截后,重新打开安装包。'else if ResultCode <> 0 then- Result := '无法安全停止现有 WorkDaddy 进程(退出码 ' + IntToStr(ResultCode) + ')。请完全退出客户端后重试。';+ Result := '安装被后台进程阻止:可能存在管理员权限运行的旧版 WorkDaddy,当前安装程序无法确认并停止它。请先退出 WorkBuddy;仍无法安装时,请右键以管理员身份运行本安装包一次完成迁移。';end;diff --git a/scripts/windows-process-boundary.js b/scripts/windows-process-boundary.jsindex dcb62ac..9354e15 100644--- a/scripts/windows-process-boundary.js+++ b/scripts/windows-process-boundary.js@@ -330,8 +330,42 @@ function assertDaemonServiceIdentity(options) {return process;}+// A standard process cannot read ExecutablePath/CommandLine for an elevated+// Node process. Reuse (never termination) may instead rely on the per-profile+// API capability token: authenticated /api/status exposes dataDir, which is+// omitted from public status responses. Bind that proof to the exact listener.+function assertAuthenticatedDaemonCapability(options) {+ const status = options && options.status;+ if (!status || typeof status !== 'object' || status.ok !== true) {+ throw new Error('authenticated daemon status is missing');+ }+ if (!status.profile || status.profile.id !== options.expectedProfileId) {+ throw new Error('authenticated daemon profile mismatch');+ }+ if (!options.allowVersionMismatch && status.version !== options.expectedVersion) {+ throw new Error('authenticated daemon version mismatch');+ }+ if (status.privilege !== 'elevated') {+ throw new Error('authenticated daemon is not elevated');+ }+ const pid = status.pid;+ if (!Number.isSafeInteger(pid) || pid <= 0) {+ throw new Error('authenticated daemon PID is invalid');+ }+ const listenerPids = Array.from(new Set((options.listenerPids || []).map(Number)));+ if (listenerPids.length !== 1 || listenerPids[0] !== pid) {+ throw new Error('authenticated daemon listener PID does not match status PID');+ }+ if (typeof status.dataDir !== 'string' || !status.dataDir.trim() ||+ !sameWindowsPath(status.dataDir, options.expectedDataDir)) {+ throw new Error('authenticated daemon data directory mismatch');+ }+ return status;+}+module.exports = {ALLOWED_WORKBUDDY_PROCESS_NAMES,+ assertAuthenticatedDaemonCapability,assertDaemonServiceIdentity,assertDaemonTerminationIdentity,assertSameProcessIdentity,diff --git a/scripts/windows-process-boundary.ps1 b/scripts/windows-process-boundary.ps1index 32c4480..8f0e20e 100644--- a/scripts/windows-process-boundary.ps1+++ b/scripts/windows-process-boundary.ps1@@ -310,6 +310,56 @@ function Get-UniqueListeningProcessId {return [int]$ids[0]}+function Get-AuthenticatedWorkDaddyStatus {+ param(+ [Parameter(Mandatory = $true)][string]$DataDir,+ [Parameter(Mandatory = $true)][int]$Port,+ [Parameter(Mandatory = $true)][string]$ExpectedProfile,+ [Parameter(Mandatory = $true)][string]$ExpectedVersion,+ [switch]$AllowVersionMismatch+ )+ $tokenFile = Join-Path $DataDir '.api-token'+ if (-not (Test-Path -LiteralPath $tokenFile -PathType Leaf)) {+ throw '当前 profile 缺少本地 API 身份凭证'+ }+ $token = (Get-Content -LiteralPath $tokenFile -Raw -ErrorAction Stop).Trim()+ if ($token -notmatch '^[A-Fa-f0-9]{64}$') { throw '当前 profile 的本地 API 身份凭证无效' }+ try {+ $response = Invoke-WebRequest `+ -UseBasicParsing `+ -Uri ("http://127.0.0.1:$Port/api/status") `+ -Headers @{ 'X-WorkDaddy-Token' = $token } `+ -TimeoutSec 3 `+ -ErrorAction Stop+ $status = $response.Content | ConvertFrom-Json -ErrorAction Stop+ } catch {+ throw ('无法通过本地身份凭证确认正在运行的 WorkDaddy: ' + $_.Exception.Message)+ }+ $statusPid = 0+ if ($null -eq $status -or $status.ok -ne $true -or+ -not [int]::TryParse([string]$status.pid, [ref]$statusPid) -or $statusPid -le 0) {+ throw '本地 WorkDaddy 状态中的 PID 无效'+ }+ if ([string]$status.profile.id -cne $ExpectedProfile) { throw '本地 WorkDaddy profile 不匹配' }+ if (-not $AllowVersionMismatch -and [string]$status.version -cne $ExpectedVersion) {+ throw '本地 WorkDaddy version 不匹配'+ }+ if ([string]$status.privilege -cne 'elevated') { throw '本地 WorkDaddy 不是管理员权限进程' }+ if ([string]::IsNullOrWhiteSpace([string]$status.dataDir)) {+ throw '本地 WorkDaddy 未接受当前 profile 身份凭证'+ }+ $expectedDataDir = [IO.Path]::GetFullPath($DataDir).TrimEnd([IO.Path]::DirectorySeparatorChar)+ $actualDataDir = [IO.Path]::GetFullPath([string]$status.dataDir).TrimEnd([IO.Path]::DirectorySeparatorChar)+ if (-not [StringComparer]::OrdinalIgnoreCase.Equals($expectedDataDir, $actualDataDir)) {+ throw '本地 WorkDaddy 数据目录不匹配'+ }+ $listenerPid = Get-UniqueListeningProcessId -Port $Port+ if ($null -eq $listenerPid -or $listenerPid -ne $statusPid) {+ throw '本地 WorkDaddy 状态 PID 与监听 PID 不匹配'+ }+ return $status+}+function Stop-VerifiedProcess {param([Parameter(Mandatory = $true)]$Process)$targetPid = [int]$Process.ProcessIddiff --git a/scripts/windows-relaunch-standard.ps1 b/scripts/windows-relaunch-standard.ps1new file mode 100644index 0000000..3447a1f--- /dev/null+++ b/scripts/windows-relaunch-standard.ps1@@ -0,0 +1,31 @@+param(+ [Parameter(Mandatory = $true)][string]$NodePath,+ [Parameter(Mandatory = $true)][string]$LauncherPath+)++$ErrorActionPreference = 'Stop'++function Quote-WindowsArgument {+ param([Parameter(Mandatory = $true)][string]$Value)+ if ($Value.IndexOfAny([char[]]@([char]0, [char]10, [char]13, [char]34)) -ge 0) {+ throw 'Invalid relaunch argument path.'+ }+ return [char]34 + $Value + [char]34+}++$node = [IO.Path]::GetFullPath($NodePath)+$launcher = [IO.Path]::GetFullPath($LauncherPath)+$scriptsRoot = [IO.Path]::GetFullPath($PSScriptRoot).TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar+if (-not (Test-Path -LiteralPath $node -PathType Leaf)) { throw 'Node runtime is missing.' }+if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) { throw 'Windows launcher is missing.' }+if (-not $launcher.StartsWith($scriptsRoot, [StringComparison]::OrdinalIgnoreCase)) {+ throw 'Windows launcher is outside the installed scripts directory.'+}++# Shell.Application delegates ShellExecute to the interactive Explorer shell.+# With normal UAC this yields the desktop user's standard token. If UAC is+# genuinely disabled, Explorer has no filtered token and the marker prevents a+# relaunch loop; the Node launcher then continues in the only available mode.+$shell = New-Object -ComObject Shell.Application+$arguments = '--experimental-sqlite ' + (Quote-WindowsArgument $launcher) + ' --desktop-shell-relaunch'+$shell.ShellExecute($node, $arguments, (Split-Path -Parent $launcher), 'open', 0)diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex b729f29..667ef5a 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -107,7 +107,7 @@ test('Windows install and update release a locked launcher before replacing it',assert.match(boundary, /Get-CimInstance\s+Win32_Process/);assert.match(boundary, /Test-ExactCmdLauncherCommandLine/);assert.doesNotMatch(boundary, /taskkill[^\r\n]*\/T\b/i);- assert.ok(install.indexOf('Release-VerifiedLauncherLock') < install.indexOf('robocopy $SrcDir $targetScripts'), 'install must release launcher before robocopy');+ assert.ok(install.indexOf('Release-VerifiedLauncherLock') < install.indexOf('& robocopy @copyArgs'), 'install must release launcher before robocopy');assert.match(update, /launcher\.cmd/);assert.ok(update.indexOf('Release-VerifiedLauncherLock') < update.indexOf('Move-Item -LiteralPath $AppDir'), 'update must release launcher before moving the old app');});@@ -481,7 +481,9 @@ test('Windows launcher searches app-data roots and versioned WorkBuddy installs'test('Windows release package includes the troubleshooting prompt as UTF-8', () => {const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-win-zip.sh'), 'utf8');+ const installer = fs.readFileSync(path.join(repoRoot, 'scripts', 'win', 'workdaddy.iss'), 'utf8');assert.match(build, /安装失败自主解决提示词\.txt/);+ assert.match(installer, /Source: "\{#StageRoot\}\\安装失败自主解决提示词\.txt"/);assert.match(build, /Python zipfile/);assert.match(build, /ZIP_DEFLATED/);});@@ -560,7 +562,7 @@ test('Windows release publishes Setup.exe only and removes temporary ZIP stagingassert.match(guide, /temporary staging/);});-test('Windows Setup stops a verified lifecycle before replacing bundled Node', () => {+test('Windows Setup stops a verified lifecycle or preserves an authenticated elevated runtime', () => {const installer = fs.readFileSync(path.join(repoRoot, 'scripts', 'win', 'workdaddy.iss'), 'utf8');const prepare = fs.readFileSync(path.join(repoRoot, 'scripts', 'prepare-win-install.ps1'), 'utf8');const verify = fs.readFileSync(path.join(repoRoot, 'scripts', 'verify-win.cmd'), 'utf8');@@ -569,9 +571,16 @@ 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, /Get-AuthenticatedWorkDaddyStatus/);+ assert.match(prepare, /-AllowVersionMismatch/);+ assert.match(prepare, /exit 10/);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(installer, /ResultCode = 10/);+ assert.match(installer, /ShouldReplaceRuntime/);+ assert.match(installer, /runtime\\node\\\*/);+ assert.match(installer, /管理员权限运行的旧版 WorkDaddy/);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/verify-win-exit.test.js b/test/verify-win-exit.test.jsindex 267acd2..7c55527 100644--- a/test/verify-win-exit.test.js+++ b/test/verify-win-exit.test.js@@ -58,7 +58,7 @@ test('Windows verifier returns success for a complete source package', { skip: pconst scriptsDir = path.join(dir, 'scripts');const required = ['daemon.js', 'session-db.js', 'lib.js', 'watchdog.js', 'win-launcher.js',- 'windows-process-boundary.js', 'windows-process-boundary.ps1', 'inject.js',+ 'windows-process-boundary.js', 'windows-process-boundary.ps1', 'windows-relaunch-standard.ps1', 'inject.js','theme-patches.js', 'launcher.cmd', 'launcher-hidden.vbs', 'install-win.cmd','install-win.ps1', 'prepare-win-install.ps1', 'uninstall-win.ps1', 'apply-update.ps1',path.join('win', 'setup.sed'), 'verify-win.cmd',diff --git a/test/windows-launcher-boundary-repair.test.js b/test/windows-launcher-boundary-repair.test.jsindex 34a630e..ff51353 100644--- a/test/windows-launcher-boundary-repair.test.js+++ b/test/windows-launcher-boundary-repair.test.js@@ -14,6 +14,7 @@ const installerSource = fs.readFileSync(path.join(root, 'scripts', 'win', 'workdconst chineseLanguageSource = fs.readFileSync(path.join(root, 'scripts', 'win', 'ChineseSimplified.isl'), 'utf8');const boundarySource = fs.readFileSync(path.join(root, 'scripts', 'windows-process-boundary.js'), 'utf8');const powershellSource = fs.readFileSync(path.join(root, 'scripts', 'windows-process-boundary.ps1'), 'utf8');+const standardRelaunchSource = fs.readFileSync(path.join(root, 'scripts', 'windows-relaunch-standard.ps1'), 'utf8');const boundary = require('../scripts/windows-process-boundary.js');const resolveWindows = (value) => path.win32.normalize(value);@@ -118,8 +119,8 @@ test('launcher enumerates exact lifecycle entries and never kills process trees'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, /普通权限 launcher 复用已验证的 elevated 服务/);+ assert.match(launcherSource, /assertAuthenticatedDaemonCapability/);assert.match(launcherSource, /assertSameProcessIdentity/);assert.match(launcherSource, /requireCurrentOwner:\s*true/);for (const source of [launcherSource, daemonSource, watchdogSource]) {@@ -129,6 +130,47 @@ test('launcher enumerates exact lifecycle entries and never kills process trees'}});+test('elevated launcher relaunches through the desktop shell before starting lifecycle processes', () => {+ assert.match(launcherSource, /windows-relaunch-standard\.ps1/);+ assert.match(launcherSource, /--desktop-shell-relaunch/);+ assert.ok(+ launcherSource.indexOf('relaunchWithDesktopShell') < launcherSource.indexOf('await ensureDaemon(nodeBin)'),+ 'privilege normalization must happen before the daemon lifecycle starts'+ );+ assert.match(standardRelaunchSource, /Shell\.Application/);+ assert.match(standardRelaunchSource, /ShellExecute/);+ assert.doesNotMatch(standardRelaunchSource, /runas/i);+});++test('authenticated daemon capability binds token-only status to profile, data directory, and listener PID', () => {+ const status = {+ ok: true,+ pid: 716,+ version: '1.1.1',+ buildId: 'old-build',+ privilege: 'elevated',+ dataDir: 'C:\\Users\\alice\\AppData\\Roaming\\WorkDaddy',+ profile: { id: 'workbuddy-cn' },+ };+ const input = {+ status,+ expectedProfileId: 'workbuddy-cn',+ expectedVersion: '1.1.1',+ expectedDataDir: status.dataDir,+ listenerPids: [716],+ };+ assert.equal(boundary.assertAuthenticatedDaemonCapability(input).pid, 716);+ assert.throws(() => boundary.assertAuthenticatedDaemonCapability({ ...input, listenerPids: [717] }), /listener|PID/i);+ assert.throws(() => boundary.assertAuthenticatedDaemonCapability({ ...input, status: { ...status, dataDir: 'C:\\Other' } }), /data|目录/i);+ assert.throws(() => boundary.assertAuthenticatedDaemonCapability({ ...input, status: { ...status, profile: { id: 'workbuddy-ai' } } }), /profile/i);+ assert.throws(() => boundary.assertAuthenticatedDaemonCapability({ ...input, status: { ...status, version: '1.1.0' } }), /version/i);+ assert.equal(boundary.assertAuthenticatedDaemonCapability({+ ...input,+ status: { ...status, version: '1.1.0' },+ allowVersionMismatch: true,+ }).version, '1.1.0');+});+test('launcher retries while daemon listener is ready before status', () => {assert.match(launcherSource, /if \(!status \|\| listeners\.length !== 1\) continue/);assert.doesNotMatch(launcherSource, /if \(!status && listeners\.length === 0\) continue/);@@ -273,6 +315,10 @@ test('Windows cold-start guards an already running WorkBuddy and sends a nativeassert.match(launcherSource, /NotifyIcon/);assert.match(launcherSource, /spawnSync\(powershell/);assert.match(launcherSource, /if \(requireWorkBuddyClosedBeforeLaunch\(\)\) process\.exit\(0\)/);+ assert.ok(+ launcherSource.indexOf('if (await isWorkBuddyCdp())') < launcherSource.indexOf('if (requireWorkBuddyClosedBeforeLaunch())'),+ 'an already-debuggable WorkBuddy must be injected before the cold-start guard'+ );assert.match(launcherSource, /showWindowsNotification\('WorkBuddy', '正在打开 WorkBuddy,请稍等…'\)/);});diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.jsindex cd6cbee..22cdf29 100644--- a/test/windows-privilege-boundary.test.js+++ b/test/windows-privilege-boundary.test.js@@ -208,7 +208,7 @@ test('Windows entry points detect and expose a matching daemon privilege mode',test('Windows installer stops the verified profile lifecycle before replacing or launching files', () => {const stopIndex = installerSource.indexOf('Stop-VerifiedWorkDaddyLifecycle');- const copyIndex = installerSource.indexOf('robocopy $SrcDir $targetScripts');+ const copyIndex = installerSource.indexOf('& robocopy @copyArgs');const launchIndex = installerSource.indexOf('# 4) 启动');assert.ok(stopIndex >= 0, 'installer must stop an existing verified lifecycle');assert.ok(stopIndex < copyIndex, 'lifecycle must stop before files are replaced');@@ -216,6 +216,8 @@ test('Windows installer stops the verified profile lifecycle before replacing orassert.match(installerSource, /\$uiPort\s*=\s*if \(\$Profile -eq 'workbuddy-ai'\) \{ 47833 \} else \{ 47832 \}/);assert.match(installerSource, /-ExpectedWatchdogScript \(Join-Path \$AppDir 'scripts\\watchdog\.js'\)/);assert.match(installerSource, /-ExpectedDaemonScript \(Join-Path \$AppDir 'scripts\\daemon\.js'\)/);+ assert.match(installerSource, /\$preserveExistingLifecycle/);+ assert.match(installerSource, /runtime\\node/);});test('PowerShell lifecycle scopes daemon discovery to a verified watchdog parent', () => {diff --git a/test/windows-release-script.test.js b/test/windows-release-script.test.jsindex 2f5d6a3..2e349eb 100644--- a/test/windows-release-script.test.js+++ b/test/windows-release-script.test.js@@ -7,15 +7,18 @@ 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 scriptBytes = fs.readFileSync(scriptPath);+const source = scriptBytes.toString('utf8');const launcher = fs.readFileSync(launcherPath, 'utf8');test('Windows release script interactively builds both profiles for one version', () => {+ assert.deepEqual([...scriptBytes.subarray(0, 3)], [0xef, 0xbb, 0xbf], 'Windows PowerShell 5.1 needs a UTF-8 BOM for Chinese prompts');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, /-IsccPath \$Compiler \| Out-Host/);assert.match(source, /WORKDADDY_BUILD_PROFILE/);assert.match(source, /-Version \$ReleaseVersion/);assert.match(launcher, /build-win-release\.ps1/);