Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(windows): 修复 winget 升级入口丢失与版本识别滞后 #4548 (#4583)
DavidShenXD2379c2d24231
diff --git a/apps/desktop/cindy-updater/src-tauri/src/args.rs b/apps/desktop/cindy-updater/src-tauri/src/args.rsindex 423b0fcaf3..14d2a1dd2a 100644--- a/apps/desktop/cindy-updater/src-tauri/src/args.rs+++ b/apps/desktop/cindy-updater/src-tauri/src/args.rs@@ -19,6 +19,11 @@ pub struct CliArgs {#[arg(long = "exe-name")]pub exe_name: String,+ /// Metadata identity forwarded only when this updater elevates itself.+ /// Electron uses an environment variable so old updater binaries still work.+ #[arg(long = "install-key")]+ pub install_key: Option<String>,+/// PID of the main Electron process to wait for before swapping files.#[arg(long)]pub pid: u32,diff --git a/apps/desktop/cindy-updater/src-tauri/src/installation_version.rs b/apps/desktop/cindy-updater/src-tauri/src/installation_version.rsnew file mode 100644index 0000000000..355347c046--- /dev/null+++ b/apps/desktop/cindy-updater/src-tauri/src/installation_version.rs@@ -0,0 +1,62 @@+/// Update only Windows' installed-version metadata after a verified launch.+/// Embed the script so the elevated updater never executes a mutable .ps1 from+/// the installation directory. No new dependency or change to the apply result.+#[cfg(target_os = "windows")]+pub fn sync(exe: &std::path::Path, key: &str) {+ use std::os::windows::process::CommandExt;+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};++ const SCRIPT: &str = include_str!("../../../resources/windows-installation-version.ps1");+ // An elevated updater must not resolve powershell from its cwd or PATH.+ #[link(name = "kernel32")]+ extern "system" {+ fn GetSystemDirectoryW(buffer: *mut u16, size: u32) -> u32;+ }+ let mut system_dir = [0u16; 32768];+ // SAFETY: the buffer is writable and its declared length matches the array.+ let len = unsafe { GetSystemDirectoryW(system_dir.as_mut_ptr(), system_dir.len() as u32) } as usize;+ if len == 0 || len >= system_dir.len() {+ crate::logger::warn("[installer] system directory unavailable for metadata repair");+ return;+ }+ let powershell = std::path::PathBuf::from(String::from_utf16_lossy(&system_dir[..len]))+ .join("WindowsPowerShell").join("v1.0").join("powershell.exe");+ let result = Command::new(powershell)+ .args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT])+ .env("CINDY_VERSION_SYNC_KEY", key)+ .env("CINDY_VERSION_SYNC_EXE", exe)+ .env_remove("CINDY_VERSION_SYNC_EXPECTED")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .creation_flags(0x0800_0000) // CREATE_NO_WINDOW+ .spawn();+ let Ok(mut child) = result else {+ crate::logger::warn("[installer] version metadata helper unavailable");+ return;+ };+ let deadline = Instant::now() + Duration::from_secs(5);+ loop {+ match child.try_wait() {+ Ok(Some(status)) => {+ if !status.success() {+ crate::logger::warn("[installer] version metadata repair failed");+ }+ return;+ }+ Ok(None) if Instant::now() < deadline => {+ std::thread::sleep(Duration::from_millis(50));+ }+ _ => {+ let _ = child.kill();+ let _ = child.wait();+ crate::logger::warn("[installer] version metadata repair timed out");+ return;+ }+ }+ }+}++#[cfg(not(target_os = "windows"))]+pub fn sync(_exe: &std::path::Path, _key: &str) {}diff --git a/apps/desktop/cindy-updater/src-tauri/src/installer.rs b/apps/desktop/cindy-updater/src-tauri/src/installer.rsindex 7a5279ff73..7d0ecacade 100644--- a/apps/desktop/cindy-updater/src-tauri/src/installer.rs+++ b/apps/desktop/cindy-updater/src-tauri/src/installer.rs@@ -247,6 +247,11 @@ fn run_inner<F: FnMut(InstallerEvent)>("[installer] LAUNCH VERIFIED: {} is running",args.exe_name));+ // Best-effort metadata only, outside the file replacement/rollback+ // transaction. Reuse existing elevation for HKLM, never request it.+ if let Some(key) = installation_version_key(args) {+ crate::installation_version::sync(&args.app_dir.join(&args.exe_name), &key);+ }let _ = fs::remove_dir_all(&backup_dir);cleanup_staging();Ok(())@@ -903,10 +908,40 @@ fn build_elevation_arg_string(args: &CliArgs) -> String {out.push(' ');out.push_str("e_cmdline_arg(v));}+ // ShellExecute(runas) need not preserve the caller's environment. This is+ // self-reentry into the same binary, so the optional flag is supported.+ if let Some(key) = installation_version_key(args) {+ out.push_str(" --install-key ");+ out.push_str("e_cmdline_arg(&key));+ }out.push_str(" --elevated");out}+fn installation_version_key(args: &CliArgs) -> Option<String> {+ args.install_key.clone().or_else(|| std::env::var("CINDY_VERSION_SYNC_KEY").ok())+}++#[cfg(test)]+mod version_metadata_args_tests {+ use super::*;+ use clap::Parser;++ #[test]+ fn legacy_launchers_work_and_elevation_preserves_optional_install_key() {+ let mut args = CliArgs::try_parse_from([+ "updater", "--zip", "patch.zip", "--app-dir", "app", "--exe-name",+ "Cindy.exe", "--pid", "123", "--log", "update.log", "--lock", "lock",+ "--workdir", "temp",+ ]).unwrap();+ assert!(args.install_key.is_none());+ args.install_key = Some("5a59f1e9-8f21-5646-8eed-e6da4126bb5c".into());+ assert!(build_elevation_arg_string(&args).ends_with(+ "--install-key 5a59f1e9-8f21-5646-8eed-e6da4126bb5c --elevated"+ ));+ }+}+/// CommandLineToArgvW-compatible quoting. Required because ShellExecuteExW/// takes a single string for parameters; if a path contains spaces we have/// to quote it ourselves, and embedded quotes/backslashes have to follow thediff --git a/apps/desktop/cindy-updater/src-tauri/src/lib.rs b/apps/desktop/cindy-updater/src-tauri/src/lib.rsindex 34f260ee4f..ce18ea67a4 100644--- a/apps/desktop/cindy-updater/src-tauri/src/lib.rs+++ b/apps/desktop/cindy-updater/src-tauri/src/lib.rs@@ -1,5 +1,6 @@mod args;mod installer;+mod installation_version;pub(crate) mod logger;mod pid_wait;diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex e84571ad01..eac09f28f7 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -829,6 +829,7 @@ function extraResourcesForTarget(targetPlatform: string): string[] {if (windowsUpdaterRuntimeResource) {base.unshift(`resources/${UPDATER_EXE}`,+ 'resources/windows-installation-version.ps1',windowsUpdaterRuntimeResource,);}diff --git a/apps/desktop/resources/installer.nsh b/apps/desktop/resources/installer.nshindex 63d6922cea..2b7d4e6954 100644--- a/apps/desktop/resources/installer.nsh+++ b/apps/desktop/resources/installer.nsh@@ -7,6 +7,7 @@; 接受);dev 仍独立名,dev 安装器绝不误伤同机并存的正式安装。注册表键名; Windows 大小写不敏感,shell 键 "Cindy" 与历史写入的 "cindy" 是同一个键,; 行为零变化。+!include "winget-shortcuts.nsh"!include "installer-directory.nsh"!ifndef BUILD_UNINSTALLER@@ -34,6 +35,11 @@Goto check_running${EndIf}+ ${If} ${isUpdated}+ ; winget passes --updated. Preserve existing links across old uninstallers,+ ; which deleted them even when electron-builder passed --keep-shortcuts.+ !insertmacro cindyBackupUpgradeShortcuts+ ${Else}; 删旧快捷方式:老 .lnk 里 IconLocation 仍指向上一版 exe 的资源索引,; 新版 .ico 内多尺寸顺序/数量变化后那个索引会落到另一张图。; 让 NSIS 在后续步骤中重建 .lnk,新的 IconLocation 自然指向当前 exe 的索引 0。@@ -45,10 +51,14 @@; 同步清掉 PinnedTaskbar 里的副本(任务栏固定项也会缓存图标)Delete "$APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\${SHORTCUT_NAME}.lnk"+ ${EndIf}!macroend!endif!macro customInstall+ ${If} ${isUpdated}+ !insertmacro cindyRestoreUpgradeShortcuts+ ${EndIf}; 注册文件夹右键菜单 "通过 <区域名> 打开" (与 main/folderContextMenu.ts 写的是同一组键)。; 双重保险:installer 写一次让首装即可用, app 启动时的 registerFolderContextMenu(); 也会校验+修复, 覆盖 "升级后路径漂移" / "组策略清掉注册表" 等场景。@@ -95,11 +105,15 @@!macro customUnInstall!insertmacro cindyRemoveLoginItemOnUninstall+ ; Only --keep-shortcuts opts out: manual reinstall still uses its old cleanup+ ; path, although electron-builder also passes --updated to that uninstaller.+ ${IfNot} ${isKeepShortcuts}; 卸载时清理本产品自己的快捷方式(不碰并存的老 XDMaker / 另一区域安装)Delete "$DESKTOP\${SHORTCUT_NAME}.lnk"Delete "$SMPROGRAMS\${SHORTCUT_NAME}.lnk"Delete "$SMPROGRAMS\${PRODUCT_FILENAME}\${SHORTCUT_NAME}.lnk"Delete "$APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\${SHORTCUT_NAME}.lnk"+ ${EndIf}; 清理右键菜单注册表项 (子键 \command 必须先删 / 用 DeleteRegKey 整树删)。; 老版本 (未引入此功能) 这两条键不存在, DeleteRegKey 静默 no-op 不抛错。DeleteRegKey HKCU "Software\Classes\Directory\shell\${PRODUCT_FILENAME}"diff --git a/apps/desktop/resources/windows-installation-version.ps1 b/apps/desktop/resources/windows-installation-version.ps1new file mode 100644index 0000000000..c8f0fe54b8--- /dev/null+++ b/apps/desktop/resources/windows-installation-version.ps1@@ -0,0 +1,79 @@+# Metadata-only repair after a successful ZIP update. Shared by the updater+# (which may already be elevated) and the first launch after an older updater.+# Never create an install record, request elevation, or change UninstallString.+function Sync-CindyInstallationVersion {+ [CmdletBinding()]+ param(+ [string] $InstallKey,+ [string] $ExePath,+ [string] $Version,+ [scriptblock] $OpenBaseKey = { param($hive, $view)+ [Microsoft.Win32.RegistryKey]::OpenBaseKey($hive, $view)+ }+ )+ if ($InstallKey -notmatch '^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$' -or+ $Version -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$' -or+ $Version -match '^0\.0\.0($|[-+])' -or+ -not [IO.Path]::IsPathRooted($ExePath)) { return }++ $appDir = [IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($ExePath)).TrimEnd('\')+ $uninstaller = Join-Path $appDir ('Uninstall ' + [IO.Path]::GetFileName($ExePath))+ $installPath = 'Software\' + $InstallKey+ $uninstallPath = 'Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $InstallKey+ foreach ($hive in @('CurrentUser', 'LocalMachine')) {+ foreach ($view in @('Registry64', 'Registry32')) {+ $base = $null; $install = $null; $uninstall = $null+ try {+ $base = & $OpenBaseKey $hive $view+ $install = $base.OpenSubKey($installPath, $false)+ if ($null -eq $install) { continue }+ $location = [string] $install.GetValue('InstallLocation')+ if (-not [IO.Path]::IsPathRooted($location) -or+ -not [string]::Equals([IO.Path]::GetFullPath($location).TrimEnd('\'),+ $appDir, [StringComparison]::OrdinalIgnoreCase)) { continue }++ $uninstall = $base.OpenSubKey($uninstallPath, $false)+ if ($null -eq $uninstall) { continue }+ $oldVersion = [string] $uninstall.GetValue('DisplayVersion')+ $command = [string] $uninstall.GetValue('UninstallString')+ # NSIS writes a quoted uninstaller followed by its scope switch.+ # Matching both keys prevents repairing another installation or+ # an orphaned/portable copy merely sharing an app identity.+ if ($command -notmatch '^"([^"]+)"(?:\s|$)' -or+ -not [string]::Equals($Matches[1], $uninstaller, [StringComparison]::OrdinalIgnoreCase) -or+ [string]::IsNullOrEmpty($oldVersion) -or $oldVersion -eq $Version) { continue }+ $uninstall.Dispose()+ $uninstall = $base.OpenSubKey($uninstallPath, $true)+ if ($null -ne $uninstall -and+ $uninstall.GetValue('UninstallString') -eq $command -and+ $uninstall.GetValue('DisplayVersion') -eq $oldVersion -and+ $install.GetValue('InstallLocation') -eq $location) {+ $uninstall.SetValue('DisplayVersion', $Version, [Microsoft.Win32.RegistryValueKind]::String)+ }+ } catch {+ # HKLM may be read-only to the app. The already-elevated updater+ # can repair it; this metadata must never trigger another UAC.+ Write-Warning 'Cindy installation version metadata could not be synchronized.'+ } finally {+ if ($null -ne $uninstall) { $uninstall.Dispose() }+ if ($null -ne $install) { $install.Dispose() }+ if ($null -ne $base) { $base.Dispose() }+ }+ }+ }+}++if ($env:CINDY_VERSION_SYNC_KEY -and $env:CINDY_VERSION_SYNC_EXE) {+ try {+ $version = [Diagnostics.FileVersionInfo]::GetVersionInfo($env:CINDY_VERSION_SYNC_EXE).ProductVersion+ # A running old process must not publish its version for a newer exe.+ if (-not $env:CINDY_VERSION_SYNC_EXPECTED -or $env:CINDY_VERSION_SYNC_EXPECTED -eq $version) {+ $syncWarnings = @()+ Sync-CindyInstallationVersion $env:CINDY_VERSION_SYNC_KEY $env:CINDY_VERSION_SYNC_EXE $version -WarningVariable syncWarnings -WarningAction SilentlyContinue+ if ($syncWarnings.Count -gt 0) { exit 1 }+ }+ } catch {+ Write-Warning 'Cindy executable version could not be read.'+ exit 1+ }+}diff --git a/apps/desktop/resources/winget-shortcuts.nsh b/apps/desktop/resources/winget-shortcuts.nshnew file mode 100644index 0000000000..71bcee5986--- /dev/null+++ b/apps/desktop/resources/winget-shortcuts.nsh@@ -0,0 +1,64 @@+; Only invoked by --updated installs. $PLUGINSDIR is private to this installer+; attempt and NSIS cleans it on exit. Copy bytes, not freshly created links, so+; taskbar pin identity, arguments and AUMID survive an old uninstaller.+!include FileFunc.nsh+!macro cindyBackupLink SOURCE NAME+ ${If} ${FileExists} "${SOURCE}"+ ClearErrors+ CopyFiles /SILENT "${SOURCE}" "$PLUGINSDIR\cindy-shortcuts\${NAME}.lnk"+ ${If} ${Errors}+ ; Stop before the old uninstaller can destroy the only copy.+ DetailPrint "Could not preserve an existing shortcut; upgrade cancelled."+ SetErrorLevel 1+ Quit+ ${EndIf}+ ${EndIf}+!macroend++!macro cindyCheckShortcutRestore DESTINATION+ ${If} ${Errors}+ Pop $R0+ ; The app may already be replaced. Do not report a successful upgrade+ ; when an existing shortcut could not be restored.+ DetailPrint "Could not restore shortcut: ${DESTINATION}"+ SetErrorLevel 1+ Quit+ ${EndIf}+!macroend++!macro cindyRestoreLink DESTINATION NAME+ ${If} ${FileExists} "$PLUGINSDIR\cindy-shortcuts\${NAME}.lnk"+ ${AndIfNot} ${FileExists} "${DESTINATION}"+ Push $R0+ ${GetParent} "${DESTINATION}" $R0+ ClearErrors+ CreateDirectory "$R0"+ !insertmacro cindyCheckShortcutRestore "${DESTINATION}"+ CopyFiles /SILENT "$PLUGINSDIR\cindy-shortcuts\${NAME}.lnk" "${DESTINATION}"+ !insertmacro cindyCheckShortcutRestore "${DESTINATION}"+ Pop $R0+ ${EndIf}+!macroend++!macro cindyUpgradeLinks OPERATION+ !insertmacro ${OPERATION} "$DESKTOP\${SHORTCUT_NAME}.lnk" "desktop"+ !insertmacro ${OPERATION} "$SMPROGRAMS\${SHORTCUT_NAME}.lnk" "start-menu"+ !insertmacro ${OPERATION} "$SMPROGRAMS\${PRODUCT_FILENAME}\${SHORTCUT_NAME}.lnk" "start-menu-folder"+ ; Pins always belong to the current user, even in an /allusers install.+ SetShellVarContext current+ !insertmacro ${OPERATION} "$APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\${SHORTCUT_NAME}.lnk" "taskbar"+ ${If} $installMode == "all"+ SetShellVarContext all+ ${EndIf}+!macroend++!macro cindyBackupUpgradeShortcuts+ InitPluginsDir+ CreateDirectory "$PLUGINSDIR\cindy-shortcuts"+ !insertmacro cindyUpgradeLinks cindyBackupLink+!macroend++!macro cindyRestoreUpgradeShortcuts+ ; The per-link restore creates missing parent directories only for saved links.+ !insertmacro cindyUpgradeLinks cindyRestoreLink+!macroenddiff --git a/apps/desktop/scripts/test-windows-installation-version.ps1 b/apps/desktop/scripts/test-windows-installation-version.ps1new file mode 100644index 0000000000..e4859adc2d--- /dev/null+++ b/apps/desktop/scripts/test-windows-installation-version.ps1@@ -0,0 +1,127 @@+# Explicit Windows regression check. All registry objects are in-memory fakes;+# this never opens HKCU/HKLM or changes the developer's installed applications.+$ErrorActionPreference = 'Stop'+$env:CINDY_VERSION_SYNC_KEY = ''+$env:CINDY_VERSION_SYNC_EXE = ''+. (Join-Path $PSScriptRoot '../resources/windows-installation-version.ps1')++class VersionTestKey {+ [hashtable] $Values = @{}+ [hashtable] $Children = @{}+ [bool] $DenyWrite = $false+ [int] $Writes = 0+ [int] $Disposals = 0+ [object] GetValue([string] $name) { return $this.Values[$name] }+ [object] OpenSubKey([string] $name, [bool] $write) {+ $key = $this.Children[$name]+ if ($write -and $key.DenyWrite) { throw 'Access denied' }+ return $key+ }+ [void] SetValue([string] $name, [object] $value, [object] $kind) {+ if ($name -ne 'DisplayVersion') { throw 'Unexpected registry write' }+ if ($kind -ne [Microsoft.Win32.RegistryValueKind]::String) { throw 'Wrong value type' }+ $this.Values[$name] = $value+ $this.Writes+++ }+ [void] Dispose() { $this.Disposals++ }+}++$script:guid = '5a59f1e9-8f21-5646-8eed-e6da4126bb5c'+$script:installPath = 'Software\' + $script:guid+$script:uninstallPath = 'Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $script:guid+$script:roots = @{}+$script:opened = 0+$openBase = { param($hive, $view)+ $script:opened+++ return $script:roots["$hive/$view"]+}++function Reset-Keys {+ $script:opened = 0+ $script:roots = @{}+ foreach ($hive in @('CurrentUser', 'LocalMachine')) {+ foreach ($view in @('Registry64', 'Registry32')) {+ $root = [VersionTestKey]::new()+ $install = [VersionTestKey]::new()+ $install.Values.InstallLocation = 'C:\Apps\Cindy'+ $uninstall = [VersionTestKey]::new()+ $uninstall.Values = @{+ DisplayVersion = '0.1.79'+ UninstallString = '"C:\Apps\Cindy\Uninstall Cindy.exe" /currentuser'+ DisplayName = 'Cindy'+ }+ $root.Children[$script:installPath] = $install+ $root.Children[$script:uninstallPath] = $uninstall+ $script:roots["$hive/$view"] = $root+ }+ }+}++function Assert-Equal($actual, $expected, [string] $message) {+ if ($actual -cne $expected) { throw "$message (expected $expected, got $actual)" }+ $script:assertions+++}++function Invoke-Sync([string] $version = '0.1.80', [string] $key = $script:guid) {+ Sync-CindyInstallationVersion $key 'C:\Apps\Cindy\Cindy.exe' $version $openBase -WarningAction SilentlyContinue+}++$script:assertions = 0+Reset-Keys+Invoke-Sync+foreach ($root in $script:roots.Values) {+ $uninstall = $root.Children[$script:uninstallPath]+ Assert-Equal $uninstall.Values.DisplayVersion '0.1.80' 'Both scopes/views synchronize'+ Assert-Equal $uninstall.Values.UninstallString '"C:\Apps\Cindy\Uninstall Cindy.exe" /currentuser' 'Uninstall command unchanged'+ Assert-Equal $uninstall.Writes 1 'Only one metadata write'+ Assert-Equal $root.Disposals 1 'Base key closed'+}+Invoke-Sync+foreach ($root in $script:roots.Values) {+ Assert-Equal $root.Children[$script:uninstallPath].Writes 1 'Repeated repair is idempotent'+}++foreach ($version in @('', '0.0.0', '0.0.0-beta', '1.2', 'bad', '0x0x0', '1.2.3;evil')) {+ Reset-Keys+ Invoke-Sync $version+ Assert-Equal $script:opened 0 'Invalid/placeholder versions never open registry'+}+Reset-Keys+Invoke-Sync '0.1.80' '..\OtherApp'+Assert-Equal $script:opened 0 'Invalid identity never opens registry'++foreach ($scenario in @('other-directory', 'other-uninstaller', 'missing-install', 'missing-uninstall', 'empty-version', 'read-only', 'other-identity')) {+ Reset-Keys+ foreach ($root in $script:roots.Values) {+ switch ($scenario) {+ 'other-directory' { $root.Children[$script:installPath].Values.InstallLocation = 'C:\Other\Cindy' }+ 'other-uninstaller' { $root.Children[$script:uninstallPath].Values.UninstallString = '"C:\Other\Uninstall Cindy.exe" /currentuser' }+ 'missing-install' { $root.Children.Remove($script:installPath) }+ 'missing-uninstall' { $root.Children.Remove($script:uninstallPath) }+ 'empty-version' { $root.Children[$script:uninstallPath].Values.DisplayVersion = '' }+ 'read-only' { $root.Children[$script:uninstallPath].DenyWrite = $true }+ 'other-identity' {+ $root.Children['Software\other-app'] = $root.Children[$script:installPath]+ $root.Children.Remove($script:installPath)+ }+ }+ }+ Invoke-Sync+ foreach ($root in $script:roots.Values) {+ if ($root.Children.ContainsKey($script:uninstallPath)) {+ Assert-Equal $root.Children[$script:uninstallPath].Writes 0 "No collateral changes: $scenario"+ } else {+ Assert-Equal $root.Children.ContainsKey($script:uninstallPath) $false 'Never creates uninstall entries'+ }+ }+}++Reset-Keys+foreach ($root in $script:roots.Values) {+ $root.Children[$script:installPath].Values.InstallLocation = 'c:\APPS\CINDY\'+}+Invoke-Sync '0.1.80-beta.2'+foreach ($root in $script:roots.Values) {+ Assert-Equal $root.Children[$script:uninstallPath].Values.DisplayVersion '0.1.80-beta.2' 'Windows path comparison and prerelease version'+}+Write-Output "PASS: $script:assertions Windows metadata assertions (in-memory registry only)."diff --git a/apps/desktop/scripts/test-winget-shortcuts.mjs b/apps/desktop/scripts/test-winget-shortcuts.mjsnew file mode 100644index 0000000000..f00d26c70a--- /dev/null+++ b/apps/desktop/scripts/test-winget-shortcuts.mjs@@ -0,0 +1,150 @@+// Explicit Windows-only NSIS regression check. The runnable fixture only touches+// its own unique temp directory; production installer/uninstaller are compiled,+// never executed. No actual installed app, registry or pinned item is modified.+import assert from 'node:assert/strict';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync, spawnSync } from 'node:child_process';+import { createRequire } from 'node:module';++if (process.platform !== 'win32') throw new Error('Run this NSIS check on Windows.');+const require = createRequire(import.meta.url);+const { build, Platform, Arch } = require('app-builder-lib');+const { NSIS_PATH, NsisTargetOptions } = require('app-builder-lib/out/targets/nsis/nsisUtil');+const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-winget-shortcuts-'));+try {+ NsisTargetOptions.resolve({});+ const nsisDir = await NSIS_PATH();+ const makensis = path.join(nsisDir, 'Bin', 'makensis.exe');+ const fixtureExe = path.join(root, 'fixture.exe');+ const source = [+ 'Unicode true',+ 'RequestExecutionLevel user',+ 'SilentInstall silent',+ 'OutFile "' + fixtureExe + '"',+ '!include "LogicLib.nsh"',+ '!include "' + path.join(desktop, 'resources/winget-shortcuts.nsh') + '"',+ 'Section',+ ' InitPluginsDir',+ ' CreateDirectory "$PLUGINSDIR\\cindy-shortcuts"',+ ' !insertmacro cindyBackupLink "$EXEDIR\\desktop.lnk" "desktop"',+ ' !insertmacro cindyBackupLink "$EXEDIR\\menu\\start.lnk" "menu"',+ ' !insertmacro cindyBackupLink "$EXEDIR\\taskbar.lnk" "taskbar"',+ ' !insertmacro cindyBackupLink "$EXEDIR\\user-deleted.lnk" "deleted"',+ ' !insertmacro cindyBackupLink "$EXEDIR\\replacement.lnk" "replacement"',+ ' Delete "$EXEDIR\\desktop.lnk"',+ ' Delete "$EXEDIR\\menu\\start.lnk"',+ ' RMDir "$EXEDIR\\menu"',+ ' Delete "$EXEDIR\\taskbar.lnk"',+ ' FileOpen $0 "$EXEDIR\\replacement.lnk" w',+ ' FileWrite $0 "new link"',+ ' FileClose $0',+ ' !insertmacro cindyRestoreLink "$EXEDIR\\desktop.lnk" "desktop"',+ ' !insertmacro cindyRestoreLink "$EXEDIR\\menu\\start.lnk" "menu"',+ ' !insertmacro cindyRestoreLink "$EXEDIR\\taskbar.lnk" "taskbar"',+ ' !insertmacro cindyRestoreLink "$EXEDIR\\user-deleted.lnk" "deleted"',+ ' !insertmacro cindyRestoreLink "$EXEDIR\\replacement.lnk" "replacement"',+ 'SectionEnd',+ ].join(String.fromCharCode(10));+ const nsi = path.join(root, 'fixture.nsi');+ await fs.writeFile(nsi, source);+ await fs.mkdir(path.join(root, 'menu'));+ // Byte preservation is intentional: .lnk property stores must survive intact.+ const bytes = Buffer.from([0x4c, 0, 0, 0, 0xff, 0x12, 0x80]);+ for (const name of ['desktop.lnk', 'menu/start.lnk', 'taskbar.lnk', 'replacement.lnk', 'unrelated.lnk']) {+ await fs.writeFile(path.join(root, name), bytes);+ }+ execFileSync(makensis, ['/V2', '/INPUTCHARSET', 'UTF8', nsi], { windowsHide: true, env: { ...process.env, NSISDIR: nsisDir } });+ execFileSync(fixtureExe, [], { windowsHide: true, timeout: 30000 });+ for (const name of ['desktop.lnk', 'menu/start.lnk', 'taskbar.lnk', 'unrelated.lnk']) {+ assert.deepEqual(await fs.readFile(path.join(root, name)), bytes, name);+ }+ assert.equal(await fs.readFile(path.join(root, 'replacement.lnk'), 'utf8'), 'new link');+ await assert.rejects(fs.access(path.join(root, 'user-deleted.lnk')), { code: 'ENOENT' });+ console.log('PASS: old-uninstaller deletion, byte-preserving restore, missing parent, user-deleted and unrelated links.');++ // Exercise real NSIS failures within this fixture only. A file blocks parent+ // creation; a scoped ACL permits the directory but denies adding its link.+ const denied = path.join(root, 'denied');+ await fs.mkdir(denied);+ await fs.writeFile(path.join(root, 'blocked-parent'), 'not a directory');+ const identity = execFileSync('whoami.exe', ['/user', '/fo', 'csv', '/nh'], { encoding: 'utf8', windowsHide: true });+ const sid = identity.match(/S-1-[0-9-]+/)?.[0];+ assert.ok(sid, 'current Windows SID');+ execFileSync('icacls.exe', [denied, '/deny', `*${sid}:(WD)`], { windowsHide: true });+ try {+ for (const parent of ['blocked-parent', 'denied']) {+ const failureExe = path.join(root, `${parent}.exe`);+ const failureNsi = path.join(root, `${parent}.nsi`);+ const failureSource = [+ 'Unicode true',+ 'RequestExecutionLevel user',+ 'SilentInstall silent',+ 'OutFile "' + failureExe + '"',+ '!include "LogicLib.nsh"',+ '!include "' + path.join(desktop, 'resources/winget-shortcuts.nsh') + '"',+ 'Section',+ ' InitPluginsDir',+ ' CreateDirectory "$PLUGINSDIR\\cindy-shortcuts"',+ ' !insertmacro cindyBackupLink "$EXEDIR\\unrelated.lnk" "saved"',+ ...(parent === 'denied' ? [+ // Confirm this case reaches CopyFiles, not a CreateDirectory failure.+ ' ClearErrors',+ ' CreateDirectory "$EXEDIR\\denied"',+ ' ${If} ${Errors}',+ ' SetErrorLevel 22',+ ' Quit',+ ' ${EndIf}',+ ] : []),+ ` !insertmacro cindyRestoreLink "$EXEDIR\\${parent}\\link.lnk" "saved"`,+ ' FileOpen $0 "$EXEDIR\\unexpected-success" w',+ ' FileClose $0',+ 'SectionEnd',+ ].join(String.fromCharCode(10));+ await fs.writeFile(failureNsi, failureSource);+ execFileSync(makensis, ['/V2', '/INPUTCHARSET', 'UTF8', failureNsi], { windowsHide: true, env: { ...process.env, NSISDIR: nsisDir } });+ const result = spawnSync(failureExe, [], { windowsHide: true, timeout: 30000 });+ assert.ifError(result.error);+ assert.equal(result.status, 1, `${parent}: restore failure must exit nonzero`);+ await assert.rejects(fs.access(path.join(root, 'unexpected-success')), { code: 'ENOENT' });+ }+ } finally {+ execFileSync('icacls.exe', [denied, '/remove:d', `*${sid}`], { windowsHide: true });+ }+ console.log('PASS: parent creation and link copy failures exit 1 without reaching the success path.');++ const app = path.join(root, 'app');+ await fs.mkdir(path.join(app, 'resources'), { recursive: true });+ await fs.writeFile(path.join(app, 'Cindy.exe'), 'compile-only fixture');+ await fs.writeFile(path.join(root, 'package.json'), JSON.stringify({+ name: 'cindy-installer-fixture', version: '0.1.80', description: 'Compile-only fixture',+ author: 'Cindy tests',+ }));+ await build({+ projectDir: root,+ prepackaged: app,+ targets: Platform.WINDOWS.createTarget('nsis', Arch.x64),+ publish: 'never',+ config: {+ appId: 'com.xd.cindy', productName: 'Cindy', electronVersion: '40.0.0',+ directories: { output: path.join(root, 'out'), buildResources: path.join(desktop, 'resources') },+ win: { signAndEditExecutable: false },+ nsis: {+ // Match production: installer-directory.nsh supplies the directory page.+ oneClick: false, allowElevation: true, allowToChangeInstallationDirectory: false,+ createDesktopShortcut: 'always', createStartMenuShortcut: true,+ shortcutName: 'Cindy', runAfterFinish: false,+ include: path.join(desktop, 'resources/installer.nsh'),+ },+ },+ });+ console.log('PASS: production installer and uninstaller compile against pinned electron-builder.');+} finally {+ // Only this freshly allocated fixture directory is eligible for cleanup.+ assert.equal(path.dirname(root), path.resolve(os.tmpdir()));+ assert.ok(path.basename(root).startsWith('cindy-winget-shortcuts-'));+ await fs.rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });+}diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.tsindex 37e2b6cda3..79c7dc50d3 100644--- a/apps/desktop/src/main/__tests__/updateService.test.ts+++ b/apps/desktop/src/main/__tests__/updateService.test.ts@@ -32,6 +32,7 @@ const appGetPath = vi.fn((name: string) => {const fetchManifest = vi.fn();const getBaseUrl = vi.fn(() => CDN_EXTERNAL_BASE_URL);const isDev = vi.fn(() => false);+const syncWindowsVersionAfterUpdate = vi.fn(async () => undefined);const download = vi.fn();const readAutoUpdateSettings = vi.fn(() => ({ autoRelaunchOnIdle: true }));const spawnProcess = vi.fn(() => ({@@ -158,6 +159,11 @@ vi.mock('../windowsUpdaterPrerequisites', () => ({stageBundledWindowsUpdaterRuntime,}));+vi.mock('../windowsInstallationVersion', async (importOriginal) => ({+ ...await importOriginal<typeof import('../windowsInstallationVersion')>(),+ syncWindowsVersionAfterUpdate,+}));+vi.mock('../security/trustedAppRenderer', () => ({assertTrustedAppRendererEvent: vi.fn(),}));@@ -207,6 +213,11 @@ afterAll(() => {fs.rmSync(TEST_ROOT, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });});beforeEach(() => {+ // Own every startup/background timer so afterEach can cancel it before the+ // app.getPath mock starts pointing at the next test's isolated fixture.+ // stopUpdateService clears intervals but not the initial 10-second check.+ vi.useFakeTimers();+ syncWindowsVersionAfterUpdate.mockClear();browserWindowGetAllWindows.mockReset();browserWindowGetAllWindows.mockReturnValue([]);ipcHandlers.clear();@@ -282,6 +293,34 @@ afterEach(() => {});describe.sequential('updateService', () => {+describe('installation version repair scope', () => {+ it.each(['darwin', 'linux'] as const)('does not add metadata work to %s startup', async (platform) => {+ const service = await freshUpdateService(platform);+ service.initUpdateService();+ expect(syncWindowsVersionAfterUpdate).not.toHaveBeenCalled();+ service.stopUpdateService();+ });++ it('does not touch Windows development installations', async () => {+ const service = await freshUpdateService('win32');+ isDev.mockReturnValue(true);+ service.initUpdateService();+ expect(syncWindowsVersionAfterUpdate).not.toHaveBeenCalled();+ service.stopUpdateService();+ });++ it('checks only the current Windows install and its existing update receipt', async () => {+ const service = await freshUpdateService('win32');+ service.initUpdateService();+ expect(syncWindowsVersionAfterUpdate).toHaveBeenCalledOnce();+ expect(syncWindowsVersionAfterUpdate).toHaveBeenCalledWith(expect.objectContaining({+ platform: 'win32', packaged: true, version: appGetVersion(), exePath: TEST_EXE,+ patchInfoPath: path.join(TEST_USER_DATA, 'updates', 'patch-info.json'),+ }));+ service.stopUpdateService();+ });+});+describe('binary version checks after a user-requested update', () => {beforeEach(() => {readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });@@ -361,6 +400,9 @@ describe('binary version checks after a user-requested update', () => {await service.checkForUpdate(updateManifest());ipcListeners.get('update-relaunch')?.({}, 'dark');await vi.waitFor(() => { expect(childListeners.has('error')).toBe(true); });+ const [, updaterArgs, updaterOptions] = spawnProcess.mock.calls.at(-1)! as unknown as [string, string[], { env: Record<string, string> }];+ expect(updaterArgs).not.toContain('--install-key');+ expect(updaterOptions.env.CINDY_VERSION_SYNC_KEY).toMatch(/^[0-9a-f-]{36}$/);const markerPath = path.join(TEST_USER_DATA, 'agent-binary-update-once.json');expect(fs.existsSync(markerPath)).toBe(true);childListeners.get('error')?.(Object.assign(new Error('spawn denied'), { code: 'EACCES' }));diff --git a/apps/desktop/src/main/__tests__/windowsInstallationVersion.test.ts b/apps/desktop/src/main/__tests__/windowsInstallationVersion.test.tsnew file mode 100644index 0000000000..1fe172fe12--- /dev/null+++ b/apps/desktop/src/main/__tests__/windowsInstallationVersion.test.ts@@ -0,0 +1,98 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import path from 'node:path';++const readFileSync = vi.hoisted(() => vi.fn());+const readFile = vi.hoisted(() => vi.fn());+const execFile = vi.hoisted(() => vi.fn());+vi.mock('node:fs', () => ({ default: { readFileSync, promises: { readFile } } }));+vi.mock('node:child_process', () => ({ execFile }));++import { syncWindowsVersionAfterUpdate, windowsInstallKey } from '../windowsInstallationVersion';++// Windows paths, independent of the runner's OS. No registry or user files are+// accessed: the shared PowerShell implementation is tested with in-memory keys.+const options = {+ platform: 'win32' as NodeJS.Platform,+ packaged: true,+ version: '0.1.80',+ appId: 'com.xd.cindy',+ exePath: ['C:', 'Programs', 'Cindy', 'Cindy.exe'].join(String.fromCharCode(92)),+ resourcesPath: 'resources',+ patchInfoPath: 'patch-info.json',+ warn: vi.fn(),+};+afterEach(() => vi.resetAllMocks());++describe('Windows installed version metadata', () => {+ it('matches the released winget ProductCode and isolates other app identities', () => {+ expect(windowsInstallKey('com.xd.cindy')).toBe('5a59f1e9-8f21-5646-8eed-e6da4126bb5c');+ expect(new Set(['com.xd.cindy', 'com.xd.cindycn', 'com.xd.cindydev'].map(windowsInstallKey)).size).toBe(3);+ });++ it.each([+ { platform: 'darwin' as NodeJS.Platform },+ { platform: 'linux' as NodeJS.Platform },+ { packaged: false },+ { version: '0.0.0' },+ { version: '0.0.0-beta' },+ ])('does no I/O outside a released Windows installation: %j', async (override) => {+ await syncWindowsVersionAfterUpdate({ ...options, ...override });+ expect(readFileSync).not.toHaveBeenCalled();+ expect(execFile).not.toHaveBeenCalled();+ });++ it.each([+ null,+ {},+ { version: '0.1.80' },+ { version: '0.1.80', applyAttempts: 0 },+ { version: '0.1.80', applyAttempts: '1' },+ { version: '0.1.81', applyAttempts: 1 },+ { version: '0.1.79', applyAttempts: 1 },+ ])('leaves normal launches and unapplied/failed updates alone: %j', async (patch) => {+ readFileSync.mockReturnValueOnce(JSON.stringify(patch));+ await syncWindowsVersionAfterUpdate(options);+ expect(execFile).not.toHaveBeenCalled();+ });++ it('repairs after an old updater succeeds even though the ZIP has been removed', async () => {+ readFileSync.mockReturnValueOnce(JSON.stringify({ version: options.version, applyAttempts: 1 }));+ readFile.mockResolvedValueOnce('# trusted script');+ execFile.mockImplementation((_file, _args, _opts, callback) => callback(null, '', ''));+ await syncWindowsVersionAfterUpdate(options);+ expect(execFile).toHaveBeenCalledOnce();+ const [file, args, opts] = execFile.mock.calls[0]!;+ expect(file).toBe(path.win32.join(process.env.SystemRoot ?? ['C:', 'Windows'].join(String.fromCharCode(92)), 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'));+ expect(args.slice(0, 3)).toEqual(['-NoProfile', '-NonInteractive', '-EncodedCommand']);+ expect(Buffer.from(args[3], 'base64').toString('utf16le')).toBe('# trusted script');+ expect(opts).toMatchObject({ windowsHide: true, timeout: 5000, env: {+ CINDY_VERSION_SYNC_KEY: '5a59f1e9-8f21-5646-8eed-e6da4126bb5c',+ CINDY_VERSION_SYNC_EXE: options.exePath, CINDY_VERSION_SYNC_EXPECTED: options.version,+ } });+ expect(options.warn).not.toHaveBeenCalled();+ });++ it('keeps paths out of shell code, including spaces and metacharacters', async () => {+ readFileSync.mockReturnValueOnce(JSON.stringify({ version: options.version, applyAttempts: 1 }));+ readFile.mockResolvedValueOnce('# trusted script');+ execFile.mockImplementation((_file, _args, _opts, callback) => callback(null, '', ''));+ const exePath = "C:\\Cindy & 'test' $(ignored)\\Cindy.exe";+ await syncWindowsVersionAfterUpdate({ ...options, exePath });+ expect(execFile.mock.calls[0]![2].env.CINDY_VERSION_SYNC_EXE).toBe(exePath);+ expect(execFile.mock.calls[0]![1].join(' ')).not.toContain(exePath);+ });++ it('does not reject or change the update result when metadata repair fails', async () => {+ readFileSync.mockReturnValueOnce(JSON.stringify({ version: options.version, applyAttempts: 1 }));+ readFile.mockResolvedValueOnce('# script');+ execFile.mockImplementation((_file, _args, _opts, callback) => callback(new Error('timeout'), '', ''));+ await expect(syncWindowsVersionAfterUpdate(options)).resolves.toBeUndefined();+ expect(options.warn).toHaveBeenCalledOnce();+ });++ it('ignores a missing receipt without starting a repair process', async () => {+ readFileSync.mockImplementationOnce(() => { throw new Error('ENOENT'); });+ await syncWindowsVersionAfterUpdate(options);+ expect(execFile).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts b/apps/desktop/src/main/file-browser/__tests__/html-preview.test.tsindex 5ba2b230c6..5973ed74ec 100644--- a/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts@@ -54,10 +54,23 @@ describe('directory HTML preview', () => {await expect(copyPreviewFile(source, path.join(dir, 'short.html'), size - 1)).rejects.toThrow('PREVIEW_CHANGED',);- await fs.symlink(source, path.join(dir, 'link.html'));- await expect(- copyPreviewFile(path.join(dir, 'link.html'), path.join(dir, 'linked.html'), size),- ).rejects.toThrow();+ // Windows junctions need no file-symlink privilege. Both are rejected by+ // lstat before opening the target; POSIX keeps the file-symlink coverage.+ const link = path.join(dir, 'link.html');+ await fs.symlink(+ process.platform === 'win32' ? path.join(dir, 'dist') : source,+ link,+ process.platform === 'win32' ? 'junction' : 'file',+ );+ expect((await fs.lstat(link)).isSymbolicLink()).toBe(true);+ const open = vi.spyOn(fs, 'open');+ try {+ await expect(copyPreviewFile(link, path.join(dir, 'linked.html'), size))+ .rejects.toThrow('PREVIEW_CHANGED');+ expect(open).not.toHaveBeenCalled();+ } finally {+ open.mockRestore();+ }});it('serves requested resources and root-relative module assets through authenticated HTTP', async () => {const { dir, source, args } = await fixture();diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.tsindex a5e4642c24..80a5eca2d1 100644--- a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts@@ -70,6 +70,7 @@ it('cancels the shared executor only after the last consumer releases it', asynctransferSignal = signal!;await fs.writeFile(dest, 'old');await pause;+ if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');});const first = fetchRemoteFileToCache(id, executor, vi.fn(), firstController.signal);await vi.waitFor(() => expect(executor).toHaveBeenCalledOnce());@@ -80,8 +81,14 @@ it('cancels the shared executor only after the last consumer releases it', asyncsecondController.abort();await expect(second).rejects.toThrow('FILE_PEER_CANCELLED');expect(transferSignal.aborted).toBe(true);+ // Aborted consumers settle before the transfer's finally cleans staging.+ // Join the still-paused transfer without a signal to await that cleanup too.+ const drained = expect(fetchRemoteFileToCache(id, executor, vi.fn()))+ .rejects.toThrow('FILE_PEER_CANCELLED');release();- await expect(Promise.allSettled([first, second])).resolves.toHaveLength(2);+ await drained;+ expect(executor).toHaveBeenCalledOnce();+ expect(await fs.readdir(getRemoteFileCacheRoot())).toEqual([]);});it('does not return a cache hit or report progress when ownership changes during touch', async () => {diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.tsindex a38f0051b9..e39946fb44 100644--- a/apps/desktop/src/main/updateService.ts+++ b/apps/desktop/src/main/updateService.ts@@ -40,6 +40,8 @@ import type { Manifest } from './manifestService';import { download, DownloadError } from './downloader/index';import { ProgressNormalizer } from './updateProgressNormalizer';import { compareAppUpdateVersions } from './updateVersionPolicy';+import { CURRENT_APP_ID } from '../shared/brandRegion';+import { syncWindowsVersionAfterUpdate, windowsInstallKey } from './windowsInstallationVersion';import { writeStartupBinaryUpdateMarker } from './agent-binaries/startup-update';import { createLogger, maskPath } from './logger';@@ -1509,6 +1511,9 @@ function executeUpdateWindows(zipPath: string, theme: 'light' | 'dark'): void {detached: true,stdio: 'ignore',windowsHide: false,+ // Optional metadata, not a new CLI flag: older updater binaries ignore it+ // instead of rejecting the entire update. New updaters forward it on elevation.+ env: { ...process.env, CINDY_VERSION_SYNC_KEY: windowsInstallKey(CURRENT_APP_ID) },});const spawnTimeout = setTimeout(() => {@@ -2001,6 +2006,20 @@ async function executeRelaunchUnguarded(theme: 'light' | 'dark', checkForBinaryU// ── Public API ─────────────────────────────────────────────────────────────export function initUpdateService(): void {+ // Observe the successful old-updater receipt before existing cleanup removes+ // it. Async and metadata-only; no effect on download/apply/rollback decisions.+ if (process.platform === 'win32' && app.isPackaged && !isDev()) {+ void syncWindowsVersionAfterUpdate({+ platform: process.platform,+ packaged: true,+ version: app.getVersion(),+ appId: CURRENT_APP_ID,+ exePath: app.getPath('exe'),+ resourcesPath: process.resourcesPath,+ patchInfoPath: path.join(getUpdatesDir(), PATCH_INFO_FILE),+ warn: (message) => log.warn(message),+ });+ }// Best-effort cleanup of >7-day-old `cindy-update*`/`xdt-update*` leftovers in %TEMP%.// Counterpart to the Rust updater's own sweep — covers the case where the// user stays on the latest version and never triggers another updater run.diff --git a/apps/desktop/src/main/windowsInstallationVersion.ts b/apps/desktop/src/main/windowsInstallationVersion.tsnew file mode 100644index 0000000000..73e95f4f65--- /dev/null+++ b/apps/desktop/src/main/windowsInstallationVersion.ts@@ -0,0 +1,59 @@+import { createHash } from 'node:crypto';+import { execFile } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';++/** electron-builder 24's default NSIS GUID: UUID v5(appId, its fixed namespace). */+export function windowsInstallKey(appId: string): string {+ const namespace = Buffer.from('50e065bc313411e69bab38c9862bdaf3', 'hex');+ const bytes = createHash('sha1').update(namespace).update(appId).digest().subarray(0, 16);+ bytes[6] = (bytes[6]! & 0x0f) | 0x50;+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;+ const hex = bytes.toString('hex');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;+}++/** First launch after a ZIP applied by an old updater: no startup-wide repair. */+export async function syncWindowsVersionAfterUpdate(options: {+ platform: NodeJS.Platform;+ packaged: boolean;+ version: string;+ appId: string;+ exePath: string;+ resourcesPath: string;+ patchInfoPath: string;+ warn: (message: string) => void;+}): Promise<void> {+ if (options.platform !== 'win32' || !options.packaged || /^0\.0\.0(?:$|[-+])/.test(options.version)) return;+ try {+ // Read the receipt synchronously before startup's existing patch cleanup+ // can consume a same-version receipt. The file is tiny and this runs once.+ const patch = JSON.parse(fs.readFileSync(options.patchInfoPath, 'utf8')) as {+ version?: string; applyAttempts?: number;+ };+ // The Rust updater deletes the ZIP after success, but leaves patch-info.+ if (patch.version !== options.version || !(typeof patch.applyAttempts === 'number' && patch.applyAttempts > 0)) return;+ const script = await fs.promises.readFile(path.join(options.resourcesPath, 'windows-installation-version.ps1'), 'utf8');+ // Do not resolve executable code from the installation directory or PATH.+ const powershell = path.win32.join(process.env.SystemRoot ?? ['C:', 'Windows'].join(String.fromCharCode(92)), 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');+ await new Promise<void>((resolve) => {+ execFile(powershell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {+ windowsHide: true,+ timeout: 5000,+ maxBuffer: 64 * 1024,+ env: {+ ...process.env,+ CINDY_VERSION_SYNC_KEY: windowsInstallKey(options.appId),+ CINDY_VERSION_SYNC_EXE: options.exePath,+ CINDY_VERSION_SYNC_EXPECTED: options.version,+ },+ }, (error, stdout, stderr) => {+ if (error || stdout || stderr) options.warn('Windows installation version metadata could not be synchronized.');+ resolve();+ });+ });+ } catch {+ // Missing/invalid patch-info means this is not a completed ZIP update.+ // Metadata repair must never interfere with normal startup or updating.+ }+}diff --git a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.tsindex 8f1a7ee7a3..ca641b9ad7 100644--- a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts@@ -1346,14 +1346,29 @@ describe('路径边界与覆盖语义', () => {)).resolves.toEqual(Buffer.from('granted-bytes'));await fs.rm(granted);- await fs.symlink(other, granted);- await expect(readInputFileWithinLimit(- workdir,+ // Match the directory-link fixtures above on Windows: no developer mode+ // required, and the substituted link must be rejected before any open.+ const targetDirectory = path.join(outsideDir, 'target');+ await fs.mkdir(targetDirectory);+ await fs.symlink(+ process.platform === 'win32' ? targetDirectory : other,granted,- 1024,- (bytes) => new DocsPathError('FILE_TOO_LARGE', String(bytes), 'too large'),- { allowOutsideRoot: true },- )).rejects.toMatchObject({ code: 'PATH_NOT_ALLOWED' });+ process.platform === 'win32' ? 'junction' : 'file',+ );+ expect((await fs.lstat(granted)).isSymbolicLink()).toBe(true);+ const open = vi.spyOn(fs, 'open');+ try {+ await expect(readInputFileWithinLimit(+ workdir,+ granted,+ 1024,+ (bytes) => new DocsPathError('FILE_TOO_LARGE', String(bytes), 'too large'),+ { allowOutsideRoot: true },+ )).rejects.toMatchObject({ code: 'PATH_NOT_ALLOWED' });+ expect(open).not.toHaveBeenCalled();+ } finally {+ open.mockRestore();+ }});it('输入读取只接受与边界校验相同的已打开文件身份', async () => {