Merge pull request #7970 from deepseek-harness/fix/windows-uninstall-registry

fix(desktop): clean Windows registrations and report uninstall failures
This commit is contained in:
winewill authored and GitHub committed 2026-11-19 15:30:11 +08:00
commit 6fcc447c7f
36 files changed
+1376 -64

No files matched your search

+4 -4
View File
@@ -18,8 +18,8 @@
en: 7414f87908fbffaf
zh: 8ff4fc1d83879c25
/deepseek-harness-desktop/terminal-command:
en: 5f2d25a1d8472647
zh: 2acb5c5d7d1917e2
en: 988bf8bb84cf7c9a
zh: 28cefc949c7f52ce
/deepseek-harness-desktop/closing-the-window-and-quitting:
en: bb35a022c37955c9
zh: ab2ef22d398d83a0
@@ -54,8 +54,8 @@
en: 7200a35dbed997c3
zh: 511d6961530757f1
/deepseek-harness-desktop/windows-installer-interface:
en: eb9d30bca4134f80
zh: bf201d18ae5ba697
en: 80f8f18b571864b6
zh: 45af1d593b7e1b64
/deepseek-harness-desktop/updates:
en: 8b0b9efeb83727ef
zh: 5ee95de48ceab392
+3 -3
View File
@@ -67,7 +67,7 @@ The application menu's **Manage dsh Command…** entry, immediately below **Chec
On macOS, installation creates `/usr/local/bin/dsh` and requests administrator authentication when the directory requires it. Shell startup files are unchanged. On Windows, the management dialog registers the command in the current user's PATH. A pre-existing command requires confirmation before switching; repairing Desktop's own selected command does not repeat that confirmation. The macOS link preserves and restores the displaced launcher; Windows preserves other PATH entries, including entries that predate registration. A command with higher PATH precedence is reported with its location. After moving the application, use Repair on macOS or Install from the new location on Windows. Remove leaves unrelated installations intact.
Command registration is optional after installing Desktop. Use **Manage dsh Command… → Remove** before uninstalling Desktop to remove its CLI registration; the application uninstaller does not remove it. Finish CLI commands before updating or uninstalling Desktop. The CLI runtime version follows the installed Desktop release. See [bundled command runtime](#bundled-command-runtime) for Desktop plugin commands and runtime limitations.
Command registration is optional after installing Desktop. Windows manual uninstall removes CLI registration owned by that installation; on macOS, use **Manage dsh Command… → Remove** before uninstalling Desktop. Finish CLI commands before updating or uninstalling Desktop. The CLI runtime version follows the installed Desktop release. See [bundled command runtime](#bundled-command-runtime) for Desktop plugin commands and runtime limitations.
<a id="closing-the-window-and-quitting"></a>
@@ -267,9 +267,9 @@ Windows packaging compiles an x86 Win32/GDI+ helper with Visual C++ Build Tools
Run `pnpm --dir apps/desktop run test:installer` from the repository root on an interactive Windows x64 desktop to build and exercise a small native test payload through the production installer configuration. Each run uses a unique product identity and sequentially exercises English-only and Chinese-only installer variants, selecting test labels from the displayed welcome button. Both variants install into private directories and uninstall after testing; screenshots and results remain under `.desktop-build/installer-tests/`. The checks include restart-notice process cleanup, upgrades to registered paths with trailing separators and rejection of drive roots. The renderer receives caption colors from the NSIS theme; pixel checks print into an off-screen bitmap and also run with the progress child hidden. Native rendering checks cover light/dark palettes at 100% and 200% scale, the painted 100% completion state, caption-button hover/pressed colors and release/cancellation, minimize/restore geometry, and GDI resource release; repaint timings are diagnostics in `render-results.log`, not CI performance limits. Run the generated `ui/render-test.exe <brand.bmp> <dpi> <light|dark> <hover-argb> <pressed-argb> [interactive-title]` with a title to inspect the real progress page without installing a payload. The optional `--signed` flag uses the [Windows EV configuration](windows-signing/README.md#signing-configuration) to sign test executables and the helper before embedding them; it does not enable an update feed.
The Windows uninstaller removes the Electron user-data directory (browser storage and caches under `%APPDATA%`, nested under the package scope), the `%APPDATA%` product directory, and the updater download cache under `%LOCALAPPDATA%` together with the application, then removes ordinary empty scope directories below `%APPDATA%`. The Harness home (`~/.dsh` or `DSH_HOME`: sessions, settings, credentials, plugins) is never touched, and a `DSH_HOME` published as a Windows environment variable additionally protects any target overlapping it. Silent uninstalls remove the same data; an uninstaller started with `--updated` or `/KEEP_APP_DATA`, as electron-builder does for in-place updates and for replacing an older installation from another directory, retains it. Removal runs through the native helper, which refuses protected Windows folders and paths overlapping the installation or the home, requires a fixed local drive, leaves a linked root or ancestor in place, unlinks reparse points without entering their targets, clears read-only attributes, and keeps deleting siblings after a locked file; residue never stops uninstallation and is not reported. Installation records `InstallLocation` on the Windows uninstall entry as standard inventory metadata; on Windows 11, Uninstall in the Start menu context menu opens the installed-apps list for every Win32 application, and only MSIX packages uninstall directly from there. The uninstaller declares DPI awareness and uses Microsoft YaHei UI for Chinese. This behavior is Windows-only.
The Windows uninstaller removes the Electron user-data directory (browser storage and caches under `%APPDATA%`, nested under the package scope), the `%APPDATA%` product directory, and the updater download cache under `%LOCALAPPDATA%` together with the application, then removes ordinary empty scope directories below `%APPDATA%`. The Harness home (`~/.dsh` or `DSH_HOME`: sessions, settings, credentials, plugins) is never touched, and a `DSH_HOME` published as a Windows environment variable additionally protects any target overlapping it. Home paths accept `~/`, `~\` and forward slashes, then require an absolute path on a fixed local drive. UNC shares, network mapped drives, removable drives and relative paths are not accepted for deletion-scope validation; validation failure stops before deletion and reports the original `DSH_HOME` value. This restriction also applies to cross-directory replacement. A cancelled or silent refusal for a different registered installation records the reason and both directories in the cleanup report. Silent uninstalls remove the same data; an uninstaller started with `--updated` or `/KEEP_APP_DATA`, as electron-builder does for in-place updates and for replacing an older installation from another directory, retains it. Removal runs through the native helper, which refuses protected Windows folders and paths overlapping the installation or the home, requires a fixed local drive, leaves a linked root or ancestor in place, unlinks reparse points without entering their targets, clears read-only attributes, and keeps deleting siblings after a locked file; auxiliary residue does not stop uninstallation and is included in the cleanup report. Installation records `InstallLocation` on the Windows uninstall entry as standard inventory metadata; on Windows 11, Uninstall in the Start menu context menu opens the installed-apps list for every Win32 application, and only MSIX packages uninstall directly from there. The uninstaller declares DPI awareness and uses Microsoft YaHei UI for Chinese. Manual and silent uninstall also remove the owned command PATH entry and its ownership values, and remove `dsh://` only when its command still names this installation. When command ownership is missing, an additional cleanup removes only PATH entries matching the CLI directory of this installation after confirming the installation directory is absent; existing directories and failed checks retain those entries with a cleanup report. Other command installations are preserved. `--updated` preserves these registrations; `/KEEP_APP_DATA` alone does not. Cross-directory replacement passes only `/KEEP_APP_DATA`, so the old command registration is removed; the command can be enabled again from the new installation. When the installation record points elsewhere, interactive uninstall asks for confirmation and silent uninstall stops. If the location is missing or another installation is registered, cleanup removes commands, protocol handlers, shortcuts and Windows uninstall entries that still point to the directory being removed. Shared user data and shell settings are retained. The main executable is removed first: failure retains the remaining files and uninstall entry, with retry and report-saving actions. Unverifiable directory scope stops before deletion; incomplete removal results stop subsequent cleanup. Registry or auxiliary-file failures allow uninstall to finish with a residual-items notice. Native dialogs measure approximately 40 Chinese characters with the current font and fall back to 240 DLU. Reports list failed or unverified paths, registry key/value names, operations and available error codes, without registry values or the complete PATH. Reports are retained under `%TEMP%/DeepSeek-Harness-uninstall-<pid>.txt` when writable; interactive dialogs also offer Save cleanup report, and a failed save allows another location. This behavior is Windows-only.
Use `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` to compile isolated English and Chinese fixtures with a per-run scoped package name. Omit `--compile-only` to run the native remover regression and the interactive, silent, `--updated`, `/KEEP_APP_DATA` and `DSH_HOME`-inside-Electron-data checks against seeded data. Compilation does not establish installed-uninstall behavior.
Use `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` to compile isolated fixtures for all eight installer languages with a per-run scoped package name. Omit `--compile-only` to run the native remover regression and the interactive, silent, `--updated`, `/KEEP_APP_DATA`, `DSH_HOME`-inside-Electron-data, busy-executable retry, registration-error continuation and installation-takeover checks against seeded data. Setup timeouts terminate and wait for the fixture process tree before cleanup; a separate regression covers success, nonzero exit and a timed-out parent with a live child. Compilation does not establish installed-uninstall behavior.
<a id="updates"></a>
+3 -3
View File
@@ -67,7 +67,7 @@ Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform
macOS 安装会创建 `/usr/local/bin/dsh`;目录权限需要时,系统会请求管理员认证,不会修改 shell 启动文件。Windows 管理对话框将命令注册到当前用户的 PATH。切换已有命令前会要求确认;修复当前已选中的 Desktop 命令不会重复要求切换确认。macOS 链接会保留并恢复被替换的启动器;Windows 会保留其他 PATH 条目,包括注册前就已存在的条目。若其他命令的 PATH 优先级更高,对话框会显示其位置。移动应用后,macOS 使用“修复”,Windows 从新位置使用“安装”。“移除”不会改动无关安装。
命令注册是安装 Desktop 后的可选操作。卸载 Desktop 前,请通过**管理 dsh 命令… → 移除**删除其 CLI 注册;应用卸载程序不会移除该注册。更新或卸载 Desktop 前请结束 CLI 命令。CLI 运行时版本随已安装的 Desktop 版本变化。Desktop 插件命令与运行时限制见[内置命令运行时](#bundled-command-runtime)。
命令注册是安装 Desktop 后的可选操作。Windows 手动卸载会移除属于该安装的 CLI 注册;macOS 卸载前请通过**管理 dsh 命令… → 移除**删除注册。更新或卸载 Desktop 前请结束 CLI 命令。CLI 运行时版本随已安装的 Desktop 版本变化。Desktop 插件命令与运行时限制见[内置命令运行时](#bundled-command-runtime)。
<a id="closing-the-window-and-quitting"></a>
@@ -267,9 +267,9 @@ Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI
在有交互式桌面的 Windows x64 上,从仓库根目录运行 `pnpm --dir apps/desktop run test:installer`,可将小型原生测试载荷接入正式安装配置并执行验证。每次运行使用独立产品身份,依次验证仅英文和仅中文的安装器变体,并根据实际显示的欢迎页按钮选择测试文案。两个变体均安装到私有目录并在测试后卸载;截图和结果保留在 `.desktop-build/installer-tests/` 下。检查包含重启提示窗的进程回收、末尾带分隔符的已登记路径升级,以及磁盘根目录拒绝。绘制器接收 NSIS 主题传入的标题栏颜色;像素检查绘制到离屏位图,并在隐藏进度子窗口时验证。原生绘制检查覆盖 100% 和 200% 缩放下的浅色/深色配色、绘制到 100% 的完成状态、标题栏按钮的悬停/按下颜色和松开触发与取消、最小化恢复后的窗口位置和尺寸,以及 GDI 资源释放;`render-results.log` 中的重绘耗时仅供诊断,不作为 CI 性能阈值。运行生成的 `ui/render-test.exe <brand.bmp> <dpi> <light|dark> <hover-argb> <pressed-argb> [interactive-title]` 并指定标题,可在不安装载荷的情况下查看真实进度页。可选的 `--signed` 标志使用[Windows EV 配置](windows-signing/README.zh.md#signing-configuration),在嵌入前对测试程序和辅助库签名;它不会启用更新源。
Windows 卸载程序会随应用一起删除 Electron 用户数据目录(`%APPDATA%` 下按包作用域嵌套的浏览器存储与缓存)、`%APPDATA%` 下的产品目录,以及 `%LOCALAPPDATA%` 下的更新下载缓存,随后移除 `%APPDATA%` 之下普通且已空的作用域目录。Harness 主目录(`~/.dsh` 或 `DSH_HOME`:会话、设置、凭据、插件)不会被触碰;以 Windows 环境变量发布的 `DSH_HOME` 还会保护所有与其重叠的目标。静默卸载删除相同的数据;以 `--updated` 或 `/KEEP_APP_DATA` 启动的卸载程序保留数据,electron-builder 在原地更新和从其他目录替换旧安装时正是这样启动它。删除通过原生辅助程序执行:它拒绝受保护的 Windows 目录以及与安装目录或主目录重叠的路径,要求固定的本地驱动器,链接的根目录或祖先目录原样保留,遇到重解析点只解除链接而不进入目标,清除只读属性,并在遇到被占用文件后继续删除其余兄弟项;残余不会中止卸载,也不会提示。安装时在 Windows 卸载注册项上记录 `InstallLocation` 作为标准的清单元数据;在 Windows 11 上,开始菜单右键菜单中的“卸载”对所有 Win32 应用都会打开已安装应用列表,只有 MSIX 包能从那里直接卸载。卸载程序声明 DPI 感知,中文使用微软雅黑 UI。此行为仅适用于 Windows。
Windows 卸载程序会随应用一起删除 Electron 用户数据目录(`%APPDATA%` 下按包作用域嵌套的浏览器存储与缓存)、`%APPDATA%` 下的产品目录,以及 `%LOCALAPPDATA%` 下的更新下载缓存,随后移除 `%APPDATA%` 之下普通且已空的作用域目录。Harness 主目录(`~/.dsh` 或 `DSH_HOME`:会话、设置、凭据、插件)不会被触碰;以 Windows 环境变量发布的 `DSH_HOME` 还会保护所有与其重叠的目标。主目录路径支持 `~/`、`~\` 和正斜杠,转换后仍要求固定本地驱动器上的绝对路径。删除范围校验不接受 UNC 共享、网络映射盘、移动盘和相对路径;校验失败时在删除前停止,并在报告中标明原始 `DSH_HOME` 值。此限制也适用于跨目录替换。因登记指向其他安装而取消或静默拒绝卸载时,清理报告会记录原因和两个目录。静默卸载删除相同的数据;以 `--updated` 或 `/KEEP_APP_DATA` 启动的卸载程序保留数据,electron-builder 在原地更新和从其他目录替换旧安装时正是这样启动它。删除通过原生辅助程序执行:它拒绝受保护的 Windows 目录以及与安装目录或主目录重叠的路径,要求固定的本地驱动器,链接的根目录或祖先目录原样保留,遇到重解析点只解除链接而不进入目标,清除只读属性,并在遇到被占用文件后继续删除其余兄弟项;辅助内容的残余不会中止卸载,并会记录到清理报告中。安装时在 Windows 卸载注册项上记录 `InstallLocation` 作为标准的清单元数据;在 Windows 11 上,开始菜单右键菜单中的“卸载”对所有 Win32 应用都会打开已安装应用列表,只有 MSIX 包能从那里直接卸载。卸载程序声明 DPI 感知,中文使用微软雅黑 UI。手动和静默卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。命令所有权缺失时,额外清理只移除匹配本安装 CLI 目录的 PATH 条目,并先确认安装目录已不存在;目录仍存在或检查失败时保留条目并生成清理报告。其他命令安装保持不变。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载请求确认,静默卸载停止。安装地址缺失或指向其他位置时,卸载会清理仍指向本目录的命令、协议、快捷方式和 Windows 卸载入口,保留共享用户数据和系统外壳设置。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-<pid>.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。
使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译独立的中英文夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 和 `DSH_HOME` 位于 Electron 数据内的检查。编译本身不能证明已安装卸载行为。
使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译八种安装语言的独立夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 、`DSH_HOME` 位于 Electron 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。安装超时会先终止并等待夹具进程树退出,再清理测试资源;独立回归覆盖成功、非零退出及带存活子进程的父进程超时。编译本身不能证明已安装卸载行为。
<a id="updates"></a>
+13 -1
View File
@@ -32,7 +32,19 @@
"INSTALLER_EXTRACT_COLLAPSE": "Details ausblenden",
"INSTALLER_EXTRACT_SAVED": "Der vollständige Bericht wurde unter %s gespeichert",
"INSTALLER_EXTRACT_UNSAVED": "Der vollständige Bericht konnte nicht gespeichert werden. Verwenden Sie „Fehlerdetails kopieren“, um sie beizubehalten.",
"INSTALLER_EXTRACT_COPIED": "Fehlerdetails wurden in die Zwischenablage kopiert."
"INSTALLER_EXTRACT_COPIED": "Fehlerdetails wurden in die Zwischenablage kopiert.",
"INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness ist an mehreren Orten installiert",
"INSTALLER_UNINSTALL_REGISTRATION": "Einige Elemente konnten nicht bereinigt werden. Speichern Sie den Bericht für weitere Informationen.",
"INSTALLER_UNINSTALL_REGISTERED": "Registrierter Installationsort:",
"INSTALLER_UNINSTALL_SCOPE": "Auch Befehle, Verknüpfungen und Einträge, die auf dieses Verzeichnis zeigen, werden entfernt:",
"INSTALLER_UNINSTALL_CONTINUE": "Deinstallationsordner weiter bereinigen",
"INSTALLER_UNINSTALL_SAVE": "Bereinigungsbericht speichern…",
"INSTALLER_UNINSTALL_SAVE_FAILED": "Der Bericht konnte nicht gespeichert werden. Wählen Sie einen anderen Speicherort.",
"INSTALLER_UNINSTALL_INCOMPLETE": "Deinstallation nicht abgeschlossen",
"INSTALLER_UNINSTALL_UNSAFE": "Der Löschbereich konnte nicht bestätigt werden. Es wurde nichts gelöscht.",
"INSTALLER_UNINSTALL_UNKNOWN": "Ein Bereinigungsvorgang lieferte kein vollständiges Ergebnis. Weitere Schritte wurden gestoppt.",
"INSTALLER_UNINSTALL_BLOCKED": "Diese Datei konnte nicht gelöscht werden. Schließen Sie Programme, die sie möglicherweise verwenden, prüfen Sie die Zugriffsrechte und versuchen Sie es erneut.",
"INSTALLER_UNINSTALL_COMPLETE": "Deinstallation abgeschlossen"
},
"uninstaller": {
"welcome": "Willkommen",
+13 -1
View File
@@ -32,7 +32,19 @@
"INSTALLER_EXTRACT_COLLAPSE": "Hide details",
"INSTALLER_EXTRACT_SAVED": "The full report was saved to %s",
"INSTALLER_EXTRACT_UNSAVED": "The full report could not be saved. Use Copy error details to keep it.",
"INSTALLER_EXTRACT_COPIED": "Error details were copied to the clipboard."
"INSTALLER_EXTRACT_COPIED": "Error details were copied to the clipboard.",
"INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness is installed in multiple locations",
"INSTALLER_UNINSTALL_REGISTRATION": "Some items could not be cleaned up. Save the report for details.",
"INSTALLER_UNINSTALL_REGISTERED": "Registered installation location:",
"INSTALLER_UNINSTALL_SCOPE": "Continuing removes this directory and commands, shortcuts and registrations pointing to it:",
"INSTALLER_UNINSTALL_CONTINUE": "Continue cleaning uninstall directory",
"INSTALLER_UNINSTALL_SAVE": "Save cleanup report…",
"INSTALLER_UNINSTALL_SAVE_FAILED": "The report could not be saved. Choose another location.",
"INSTALLER_UNINSTALL_INCOMPLETE": "Uninstall did not finish",
"INSTALLER_UNINSTALL_UNSAFE": "The removal scope could not be verified. No deletion was started.",
"INSTALLER_UNINSTALL_UNKNOWN": "A cleanup operation did not return a complete result. Further cleanup was stopped.",
"INSTALLER_UNINSTALL_BLOCKED": "This file could not be deleted. Close programs that may be using it, check access permissions, and retry.",
"INSTALLER_UNINSTALL_COMPLETE": "Uninstall completed"
},
"uninstaller": {
"welcome": "Welcome",
+13 -1
View File
@@ -32,7 +32,19 @@
"INSTALLER_EXTRACT_COLLAPSE": "Ocultar detalles",
"INSTALLER_EXTRACT_SAVED": "El informe completo se guardó en %s.",
"INSTALLER_EXTRACT_UNSAVED": "No se pudo guardar el informe completo. Utilice Copiar detalles del error para conservarlo.",
"INSTALLER_EXTRACT_COPIED": "Los detalles del error se copiaron al portapapeles."
"INSTALLER_EXTRACT_COPIED": "Los detalles del error se copiaron al portapapeles.",
"INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness está instalado en varias ubicaciones",
"INSTALLER_UNINSTALL_REGISTRATION": "No se pudieron limpiar algunos elementos. Guarda el informe para ver los detalles.",
"INSTALLER_UNINSTALL_REGISTERED": "Ubicación de instalación registrada:",
"INSTALLER_UNINSTALL_SCOPE": "Se eliminarán este directorio y los comandos, accesos directos y registros que apunten a él:",
"INSTALLER_UNINSTALL_CONTINUE": "Continuar limpiando el directorio de desinstalación",
"INSTALLER_UNINSTALL_SAVE": "Guardar informe de limpieza…",
"INSTALLER_UNINSTALL_SAVE_FAILED": "No se pudo guardar el informe. Elige otra ubicación.",
"INSTALLER_UNINSTALL_INCOMPLETE": "La desinstalación no se completó",
"INSTALLER_UNINSTALL_UNSAFE": "No se pudo verificar el alcance de la eliminación. No se inició la eliminación.",
"INSTALLER_UNINSTALL_UNKNOWN": "Una operación de limpieza no devolvió un resultado completo. Se detuvo la limpieza posterior.",
"INSTALLER_UNINSTALL_BLOCKED": "No se pudo eliminar este archivo. Cierra los programas que puedan estar usándolo, comprueba los permisos y vuelve a intentarlo.",
"INSTALLER_UNINSTALL_COMPLETE": "Desinstalación completada"
},
"uninstaller": {
"welcome": "Bienvenido",
+13 -1
View File
@@ -32,7 +32,19 @@
"INSTALLER_EXTRACT_COLLAPSE": "Masquer les détails",
"INSTALLER_EXTRACT_SAVED": "Le rapport complet a été enregistré dans %s",
"INSTALLER_EXTRACT_UNSAVED": "Le rapport complet n'a pas pu être enregistré. Utilisez Copier les détails de l'erreur pour le conserver.",
"INSTALLER_EXTRACT_COPIED": "Les détails de l'erreur ont été copiés dans le presse-papiers."
"INSTALLER_EXTRACT_COPIED": "Les détails de l'erreur ont été copiés dans le presse-papiers.",
"INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness est installé à plusieurs emplacements",
"INSTALLER_UNINSTALL_REGISTRATION": "Certains éléments n’ont pas pu être nettoyés. Enregistrez le rapport pour consulter les détails.",
"INSTALLER_UNINSTALL_REGISTERED": "Emplacement enregistré :",
"INSTALLER_UNINSTALL_SCOPE": "Ce dossier et les commandes, raccourcis et inscriptions qui y renvoient seront supprimés :",
"INSTALLER_UNINSTALL_CONTINUE": "Continuer le nettoyage du dossier de désinstallation",
"INSTALLER_UNINSTALL_SAVE": "Enregistrer le rapport de nettoyage…",
"INSTALLER_UNINSTALL_SAVE_FAILED": "Le rapport n’a pas pu être enregistré. Choisissez un autre emplacement.",
"INSTALLER_UNINSTALL_INCOMPLETE": "La désinstallation n’est pas terminée",
"INSTALLER_UNINSTALL_UNSAFE": "Le périmètre de suppression n’a pas pu être vérifié. Aucune suppression n’a commencé.",
"INSTALLER_UNINSTALL_UNKNOWN": "Une opération de nettoyage n’a pas renvoyé de résultat complet. Les opérations suivantes ont été arrêtées.",
"INSTALLER_UNINSTALL_BLOCKED": "Ce fichier n’a pas pu être supprimé. Fermez les programmes susceptibles de l’utiliser, vérifiez les droits d’accès et réessayez.",
"INSTALLER_UNINSTALL_COMPLETE": "Désinstallation terminée"
},
"uninstaller": {
"welcome": "Bienvenue",
+13 -1
View File
@@ -32,7 +32,19 @@
"INSTALLER_EXTRACT_COLLAPSE": "詳細を非表示",
"INSTALLER_EXTRACT_SAVED": "完全なレポートを %s に保存しました",
"INSTALLER_EXTRACT_UNSAVED": "完全なレポートを保存できませんでした。「エラーの詳細をコピー」で保存してください。",
"INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。"
"INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。",
"INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness が複数の場所にインストールされています",
"INSTALLER_UNINSTALL_REGISTRATION": "一部の項目を削除できませんでした。詳細はレポートを保存して確認できます。",
"INSTALLER_UNINSTALL_REGISTERED": "登録されているインストール先:",
"INSTALLER_UNINSTALL_SCOPE": "続行すると、次のフォルダーと、それを参照するコマンド、ショートカット、登録情報を削除します:",
"INSTALLER_UNINSTALL_CONTINUE": "アンインストール先の削除を続行",
"INSTALLER_UNINSTALL_SAVE": "削除レポートを保存…",
"INSTALLER_UNINSTALL_SAVE_FAILED": "レポートを保存できませんでした。別の保存先を選んでください。",
"INSTALLER_UNINSTALL_INCOMPLETE": "アンインストールは完了していません",
"INSTALLER_UNINSTALL_UNSAFE": "削除範囲を確認できないため、削除を開始しませんでした。",
"INSTALLER_UNINSTALL_UNKNOWN": "削除処理の完全な結果が得られないため、後続の処理を停止しました。",
"INSTALLER_UNINSTALL_BLOCKED": "このファイルを削除できません。使用している可能性のあるプログラムを閉じ、アクセス権を確認して再試行してください。",
"INSTALLER_UNINSTALL_COMPLETE": "アンインストールが完了しました"
},
"uninstaller": {
"welcome": "アンインストール ウィザードへようこそ",
+13 -1
View File
@@ -32,7 +32,19 @@
"INSTALLER_EXTRACT_COLLAPSE": "Ocultar detalhes",
"INSTALLER_EXTRACT_SAVED": "O relatório completo foi salvo em %s",
"INSTALLER_EXTRACT_UNSAVED": "Não foi possível salvar o relatório completo. Use Copiar detalhes do erro para mantê-lo.",
"INSTALLER_EXTRACT_COPIED": "Os detalhes do erro foram copiados para a área de transferência."
"INSTALLER_EXTRACT_COPIED": "Os detalhes do erro foram copiados para a área de transferência.",
"INSTALLER_UNINSTALL_OWNER": "O DeepSeek Harness está instalado em vários locais",
"INSTALLER_UNINSTALL_REGISTRATION": "Não foi possível limpar alguns itens. Salve o relatório para ver os detalhes.",
"INSTALLER_UNINSTALL_REGISTERED": "Local de instalação registrado:",
"INSTALLER_UNINSTALL_SCOPE": "Continuar remove este diretório e os comandos, atalhos e registros que apontam para ele:",
"INSTALLER_UNINSTALL_CONTINUE": "Continuar limpando o diretório de desinstalação",
"INSTALLER_UNINSTALL_SAVE": "Salvar relatório de limpeza…",
"INSTALLER_UNINSTALL_SAVE_FAILED": "Não foi possível salvar o relatório. Escolha outro local.",
"INSTALLER_UNINSTALL_INCOMPLETE": "A desinstalação não foi concluída",
"INSTALLER_UNINSTALL_UNSAFE": "Não foi possível verificar o escopo da exclusão. Nenhuma exclusão foi iniciada.",
"INSTALLER_UNINSTALL_UNKNOWN": "Uma operação de limpeza não retornou um resultado completo. As etapas seguintes foram interrompidas.",
"INSTALLER_UNINSTALL_BLOCKED": "Não foi possível excluir este arquivo. Feche programas que possam estar usando-o, verifique as permissões e tente novamente.",
"INSTALLER_UNINSTALL_COMPLETE": "Desinstalação concluída"
},
"uninstaller": {
"welcome": "Bem-vindo",
+13 -1
View File
@@ -32,7 +32,19 @@
"INSTALLER_EXTRACT_COLLAPSE": "Скрыть детали",
"INSTALLER_EXTRACT_SAVED": "Полный отчет сохранен в %s.",
"INSTALLER_EXTRACT_UNSAVED": "Полный отчет не удалось сохранить. Используйте Скопировать сведения об ошибке, чтобы сохранить их.",
"INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена."
"INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена.",
"INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness установлен в нескольких местах",
"INSTALLER_UNINSTALL_REGISTRATION": "Некоторые элементы не удалось очистить. Сохраните отчёт для просмотра подробностей.",
"INSTALLER_UNINSTALL_REGISTERED": "Зарегистрированное расположение:",
"INSTALLER_UNINSTALL_SCOPE": "Будут удалены этот каталог и указывающие на него команды, ярлыки и записи:",
"INSTALLER_UNINSTALL_CONTINUE": "Продолжить очистку каталога удаления",
"INSTALLER_UNINSTALL_SAVE": "Сохранить отчёт об очистке…",
"INSTALLER_UNINSTALL_SAVE_FAILED": "Не удалось сохранить отчёт. Выберите другое расположение.",
"INSTALLER_UNINSTALL_INCOMPLETE": "Удаление не завершено",
"INSTALLER_UNINSTALL_UNSAFE": "Не удалось проверить область удаления. Удаление не начато.",
"INSTALLER_UNINSTALL_UNKNOWN": "Операция очистки не вернула полный результат. Дальнейшая очистка остановлена.",
"INSTALLER_UNINSTALL_BLOCKED": "Не удалось удалить этот файл. Закройте программы, которые могут его использовать, проверьте права доступа и повторите попытку.",
"INSTALLER_UNINSTALL_COMPLETE": "Удаление завершено"
},
"uninstaller": {
"welcome": "Вас приветствует мастер удаления",
+13 -1
View File
@@ -32,7 +32,19 @@
"INSTALLER_EXTRACT_COLLAPSE": "隐藏详情",
"INSTALLER_EXTRACT_SAVED": "完整错误报告已保存到 %s",
"INSTALLER_EXTRACT_UNSAVED": "无法保存完整错误报告,请使用“复制错误信息”保留。",
"INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。"
"INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。",
"INSTALLER_UNINSTALL_OWNER": "当前设备在多个位置安装了 DeepSeek Harness",
"INSTALLER_UNINSTALL_REGISTRATION": "部分内容未能清理成功。你可以保存清理报告,查看具体项目和原因。",
"INSTALLER_UNINSTALL_REGISTERED": "系统登记的安装位置:",
"INSTALLER_UNINSTALL_SCOPE": "选择继续,将清理以下目录,以及仍指向它的命令、快捷方式和系统登记:",
"INSTALLER_UNINSTALL_CONTINUE": "继续清理卸载目录",
"INSTALLER_UNINSTALL_SAVE": "保存清理报告…",
"INSTALLER_UNINSTALL_SAVE_FAILED": "报告未能保存,请重新选择保存位置。",
"INSTALLER_UNINSTALL_INCOMPLETE": "卸载未完成",
"INSTALLER_UNINSTALL_UNSAFE": "无法确认删除范围,本次操作未开始删除。",
"INSTALLER_UNINSTALL_UNKNOWN": "清理操作未返回完整结果,后续清理已停止。",
"INSTALLER_UNINSTALL_BLOCKED": "无法删除以下文件。请关闭可能使用该文件的程序,检查访问权限后重试。",
"INSTALLER_UNINSTALL_COMPLETE": "卸载已完成"
},
"uninstaller": {
"welcome": "欢迎",
+39 -10
View File
@@ -5,6 +5,12 @@
#include <vector>
namespace uninstall_data {
struct Failure { std::wstring path; DWORD error; };
using Failures = std::vector<Failure>;
inline DWORD Record(Failures* failures, const std::wstring& path, DWORD error) {
if (error && failures) failures->push_back({path, error});
return error;
}
struct Handles {
std::vector<HANDLE> values;
Handles() = default;
@@ -39,6 +45,29 @@ inline bool Normalize(LPCWSTR input, std::wstring& result) {
return true;
}
// DSH_HOME accepts Node's tilde and separator spellings; relative roots remain
// unverifiable because the application's working directory is not available here.
inline bool NormalizeHome(LPCWSTR input, std::wstring& result) {
std::wstring value = input ? input : L"";
if (value.find_first_not_of(L" \t\r\n") == std::wstring::npos) value = L"~/.dsh";
if (value == L"~" || value.compare(0, 2, L"~/") == 0 || value.compare(0, 2, L"~\\") == 0) {
WCHAR buffer[32768];
DWORD length = GetEnvironmentVariableW(L"USERPROFILE", buffer, ARRAYSIZE(buffer));
std::wstring profile;
if (length && length < ARRAYSIZE(buffer)) profile.assign(buffer, length);
else {
if (length) return false;
PWSTR folder = nullptr;
if (FAILED(SHGetKnownFolderPath(FOLDERID_Profile, KF_FLAG_DONT_VERIFY, nullptr, &folder))) return false;
profile = folder;
CoTaskMemFree(folder);
}
value = profile + (value.size() > 1 ? L"\\" + value.substr(2) : L"");
}
for (auto& character : value) if (character == L'/') character = L'\\';
return Normalize(value.c_str(), result);
}
// Listing access takes part in share checks, so the open handle refuses the DELETE access a rename or removal needs.
inline DWORD Pin(const std::wstring& path, Handles& handles) {
HANDLE handle = CreateFileW((L"\\\\?\\" + path).c_str(), FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES,
@@ -61,49 +90,49 @@ inline DWORD Unlink(const std::wstring& extended, DWORD attributes) {
}
// Every sibling is attempted; the first error is returned after the whole tree has been visited.
inline DWORD RemoveTree(const std::wstring& path) {
inline DWORD RemoveTree(const std::wstring& path, Failures* failures = nullptr) {
const std::wstring extended = L"\\\\?\\" + path;
DWORD attributes = GetFileAttributesW(extended.c_str());
if (attributes == INVALID_FILE_ATTRIBUTES) {
DWORD error = GetLastError();
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? ERROR_SUCCESS : error;
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? ERROR_SUCCESS : Record(failures, path, error);
}
DWORD first = ERROR_SUCCESS;
if ((attributes & FILE_ATTRIBUTE_DIRECTORY) && !(attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
Handles pinned;
DWORD error = Pin(path, pinned);
if (error) return error;
if (error) return Record(failures, path, error);
WIN32_FIND_DATAW entry{};
HANDLE search = FindFirstFileW((extended + L"\\*").c_str(), &entry);
if (search == INVALID_HANDLE_VALUE) {
error = GetLastError();
if (error != ERROR_FILE_NOT_FOUND) return error;
if (error != ERROR_FILE_NOT_FOUND) return Record(failures, path, error);
} else {
do {
if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0) continue;
error = RemoveTree(path + L"\\" + entry.cFileName);
error = RemoveTree(path + L"\\" + entry.cFileName, failures);
if (error && !first) first = error;
} while (FindNextFileW(search, &entry));
error = GetLastError();
FindClose(search);
if (error != ERROR_NO_MORE_FILES && !first) first = error;
if (error != ERROR_NO_MORE_FILES && !first) first = Record(failures, path, error);
}
}
DWORD error = Unlink(extended, attributes);
DWORD error = Record(failures, path, Unlink(extended, attributes));
return first ? first : error;
}
// Never select a shell folder, its ancestor, Windows/Program Files descendants,
// a path overlapping the installation, or a path overlapping the protected root
// (the configured Harness home). Linked descendants are unlinked only.
inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot) {
inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot, Failures* failures = nullptr) {
std::wstring path, install;
if (!Normalize(input, path) || !Normalize(installation, install)) return ERROR_INVALID_NAME;
if (Contains(path, install) || Contains(install, path)) return ERROR_ACCESS_DENIED;
if (protectedRoot && *protectedRoot) {
std::wstring home;
// An unusable protected root cannot establish separation from retained data.
if (!Normalize(protectedRoot, home)) return ERROR_INVALID_NAME;
if (!NormalizeHome(protectedRoot, home)) return ERROR_INVALID_NAME;
if (Contains(path, home) || Contains(home, path)) return ERROR_ACCESS_DENIED;
}
struct ComScope {
@@ -146,7 +175,7 @@ inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot)
if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) return ERROR_SUCCESS;
if (error) return error;
}
return RemoveTree(path);
return RemoveTree(path, failures);
}
// Remove the ordinary, empty directories between a removed path and its stop ancestor.
+306
View File
@@ -0,0 +1,306 @@
// Manual uninstall diagnostics and native dialogs. The NSIS caller owns one session until process exit.
#pragma once
#include <commdlg.h>
#include "uninstall-data.h"
#include "extract-report.h"
namespace uninstall_report {
struct Session {
std::wstring text = L"DeepSeek Harness uninstall report\r\n";
std::wstring path;
bool issues = false;
bool mainBlocked = false;
uninstall_data::Handles pinned;
};
inline std::wstring Error(DWORD error) {
WCHAR buffer[2048]{};
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error, 0, buffer, ARRAYSIZE(buffer), nullptr);
return std::to_wstring(error) + L" " + buffer;
}
inline void Add(Session& session, LPCWSTR operation, LPCWSTR target, DWORD error) {
session.issues = true;
session.text += std::wstring(L"\r\n[failed] ") + operation + L"\r\nTarget: " + target + L"\r\nWin32: " + Error(error) + L"\r\n";
}
inline void Collect(Session& session, const uninstall_data::Failures& failures) {
for (const auto& failure : failures) Add(session, L"Remove file/directory", failure.path.c_str(), failure.error);
}
// Width is measured with the dialog font; measurement failure keeps the approved 240-DLU fallback.
inline UINT Width(HWND parent) {
NONCLIENTMETRICSW metrics{};
metrics.cbSize = sizeof(metrics);
if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(metrics), &metrics, 0)) return 240;
HFONT font = parent ? reinterpret_cast<HFONT>(SendMessageW(parent, WM_GETFONT, 0, 0)) : nullptr;
const bool owned = !font;
if (owned) font = CreateFontIndirectW(&metrics.lfMessageFont);
HDC dc = GetDC(parent);
UINT width = 240;
if (font && dc) {
HGDIOBJ previous = SelectObject(dc, font);
SIZE alphabet{}, characters{};
const std::wstring sample(40, L'\x5b57');
if (GetTextExtentPoint32W(dc, L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &alphabet)
&& GetTextExtentPoint32W(dc, sample.c_str(), 40, &characters)) {
const int base = (alphabet.cx / 26 + 1) / 2;
if (base > 0 && characters.cx > 0) {
width = static_cast<UINT>(MulDiv(characters.cx, 4, base) + 24);
MONITORINFO monitor{sizeof(monitor)};
if (GetMonitorInfoW(MonitorFromWindow(parent, MONITOR_DEFAULTTONEAREST), &monitor)) {
const int available = monitor.rcWork.right - monitor.rcWork.left - MulDiv(48, GetDeviceCaps(dc, LOGPIXELSX), 96);
if (available > 0) width = std::min(width, static_cast<UINT>(MulDiv(available, 4, base)));
}
}
}
SelectObject(dc, previous);
}
if (dc) ReleaseDC(parent, dc);
if (owned && font) DeleteObject(font);
return width;
}
inline bool Save(HWND parent, Session& session, LPCWSTR caption, LPCWSTR failed) {
for (;;) {
WCHAR filename[32768] = L"DeepSeek-Harness-uninstall-report.txt";
OPENFILENAMEW picker{};
picker.lStructSize = sizeof(picker);
picker.hwndOwner = parent;
picker.lpstrFilter = L"Text (*.txt)\0*.txt\0\0";
picker.lpstrFile = filename;
picker.nMaxFile = ARRAYSIZE(filename);
picker.lpstrDefExt = L"txt";
picker.lpstrTitle = caption;
picker.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR;
if (!GetSaveFileNameW(&picker)) {
const DWORD error = CommDlgExtendedError();
if (!error) return false;
Add(session, L"Open save dialog", L"report", error);
} else if (extract_report::WriteUtf8(filename, session.text)) {
return true;
} else {
Add(session, L"Save report", filename, GetLastError());
}
extract_report::WriteUtf8(session.path.c_str(), session.text);
const std::wstring message = std::wstring(failed) + L"\r\n\r\n" + session.path;
if (MessageBoxW(parent, message.c_str(), caption, MB_RETRYCANCEL | MB_ICONWARNING) != IDRETRY) return false;
}
}
// TaskDialog elides long paths even with soft break opportunities. Insert measured line breaks;
// the report keeps the exact path, and no private TaskDialog controls are resized or subclassed.
inline std::wstring WrapPaths(HWND parent, const std::wstring& text) {
NONCLIENTMETRICSW metrics{};
metrics.cbSize = sizeof(metrics);
HFONT font = nullptr;
if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(metrics), &metrics, 0)) font = CreateFontIndirectW(&metrics.lfMessageFont);
HDC dc = GetDC(parent);
HGDIOBJ previous = font && dc ? SelectObject(dc, font) : nullptr;
SIZE alphabet{};
int pixels = 0;
if (font && dc && GetTextExtentPoint32W(dc, L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &alphabet))
pixels = MulDiv(static_cast<int>(Width(parent)) - 32, (alphabet.cx / 26 + 1) / 2, 4);
std::wstring result;
for (size_t start = 0; start < text.size();) {
const size_t newline = text.find(L'\n', start);
const size_t end = newline == std::wstring::npos ? text.size() : newline;
const std::wstring line = text.substr(start, end - start);
if (line.find(L":\\") == std::wstring::npos) result += line;
else {
for (size_t offset = 0; offset < line.size();) {
size_t count = 0, separator = 0;
while (offset + count < line.size()) {
SIZE size{};
const bool measured = pixels > 0 && GetTextExtentPoint32W(dc, line.c_str() + offset, static_cast<int>(count + 1), &size);
if (count && (measured ? size.cx > pixels : count >= 24)) break;
if (line[offset + count] == L'\\') separator = count + 1;
++count;
}
if (offset + count < line.size() && separator) count = separator;
if (count > 1 && offset + count < line.size() && IS_HIGH_SURROGATE(line[offset + count - 1])) --count;
result.append(line, offset, count);
offset += count;
if (offset < line.size()) result += L"\r\n";
}
}
if (newline != std::wstring::npos) result += L'\n';
start = end + 1;
}
if (previous) SelectObject(dc, previous);
if (dc) ReleaseDC(parent, dc);
if (font) DeleteObject(font);
return result;
}
// mode 1 confirms old-directory cleanup; mode 2 allows retry; other modes only close/save.
inline int Show(HWND parent, Session& session, int mode, LPCWSTR title, LPCWSTR heading,
LPCWSTR body, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) {
const bool persisted = extract_report::WriteUtf8(session.path.c_str(), session.text);
const std::wstring content = WrapPaths(parent, std::wstring(body) + (mode != 1 && persisted ? L"\r\n\r\n" + session.path : L""));
using TaskDialogFn = HRESULT(WINAPI*)(const TASKDIALOGCONFIG*, int*, int*, BOOL*);
HMODULE library = LoadLibraryW(L"comctl32.dll");
auto dialog = library ? reinterpret_cast<TaskDialogFn>(GetProcAddress(library, "TaskDialogIndirect")) : nullptr;
int pressed = IDCANCEL;
for (;;) {
TASKDIALOG_BUTTON buttons[] = {{1001, primary}, {1002, save}};
TASKDIALOGCONFIG config{};
config.cbSize = sizeof(config);
config.hwndParent = parent;
config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW;
config.dwCommonButtons = mode == 1 ? TDCBF_CANCEL_BUTTON : TDCBF_CLOSE_BUTTON;
if (mode == 2) config.dwCommonButtons |= TDCBF_RETRY_BUTTON;
config.pszWindowTitle = title;
config.pszMainInstruction = heading;
config.pszContent = content.c_str();
config.cButtons = 1;
config.pButtons = mode == 1 ? buttons : buttons + 1;
config.nDefaultButton = mode == 1 ? IDCANCEL : IDCLOSE;
config.cxWidth = Width(parent);
const HRESULT result = dialog ? dialog(&config, &pressed, nullptr, nullptr) : E_NOTIMPL;
if (FAILED(result)) {
// Failing to create confirmation UI must never grant deletion permission.
if (mode == 1) { MessageBoxW(parent, body, heading, MB_OK | MB_ICONWARNING); pressed = IDCANCEL; }
else {
pressed = MessageBoxW(parent, content.c_str(), heading, mode == 2 ? MB_RETRYCANCEL : MB_OK);
if (pressed != IDRETRY && MessageBoxW(parent, save, title, MB_YESNO | MB_DEFBUTTON2) == IDYES)
Save(parent, session, save, failed);
}
break;
}
if (pressed != 1002) break;
Save(parent, session, save, failed);
}
if (library) FreeLibrary(library);
return pressed;
}
// Pin every ancestor and reject shell roots/ancestors before any payload removal.
inline DWORD Prepare(Session& session, LPCWSTR directory, LPCWSTR protectedRoot, bool& homeFailure) {
std::wstring path;
if (!uninstall_data::Normalize(directory, path)) return ERROR_INVALID_NAME;
if (protectedRoot && *protectedRoot) {
homeFailure = true;
std::wstring home;
if (!uninstall_data::NormalizeHome(protectedRoot, home)) return ERROR_INVALID_NAME;
if (uninstall_data::Contains(path, home) || uninstall_data::Contains(home, path)) return ERROR_ACCESS_DENIED;
homeFailure = false;
}
const KNOWNFOLDERID* folders[] = {&FOLDERID_Profile, &FOLDERID_RoamingAppData, &FOLDERID_LocalAppData,
&FOLDERID_Desktop, &FOLDERID_Documents, &FOLDERID_Downloads, &FOLDERID_Pictures, &FOLDERID_Music,
&FOLDERID_Videos, &FOLDERID_Public, &FOLDERID_ProgramData, &FOLDERID_Windows, &FOLDERID_ProgramFiles, &FOLDERID_ProgramFilesX86};
WCHAR nativePrograms[32768];
DWORD bytes = sizeof(nativePrograms);
if (RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", L"ProgramFilesDir",
RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY, nullptr, nativePrograms, &bytes) != ERROR_SUCCESS) return ERROR_ACCESS_DENIED;
if (uninstall_data::Contains(path, nativePrograms)) return ERROR_ACCESS_DENIED;
for (const auto* id : folders) {
PWSTR value = nullptr;
const HRESULT result = SHGetKnownFolderPath(*id, KF_FLAG_DONT_VERIFY, nullptr, &value);
if (FAILED(result)) return ERROR_ACCESS_DENIED;
const bool unsafe = uninstall_data::Contains(path, value)
|| (id == &FOLDERID_Windows && uninstall_data::Contains(value, path));
CoTaskMemFree(value);
if (unsafe) return ERROR_ACCESS_DENIED;
}
for (size_t end = path.find(L'\\', 3);; end = path.find(L'\\', end + 1)) {
const DWORD error = uninstall_data::Pin(end == std::wstring::npos ? path : path.substr(0, end), session.pinned);
if (error) return error;
if (end == std::wstring::npos) break;
}
return ERROR_SUCCESS;
}
// The executable goes first. A failure leaves every other file, including the retry uninstaller, in place.
inline DWORD Payload(Session& session, LPCWSTR directory, LPCWSTR executable, LPCWSTR uninstaller) {
if (session.mainBlocked) {
session.text += L"\r\nRetrying main executable removal; preceding failure is historical.\r\n";
session.issues = false;
session.mainBlocked = false;
}
const std::wstring main = std::wstring(directory) + L"\\" + executable;
const DWORD attributes = GetFileAttributesW((L"\\\\?\\" + main).c_str());
DWORD error = ERROR_SUCCESS;
if (attributes == INVALID_FILE_ATTRIBUTES) {
error = GetLastError();
if (error == ERROR_FILE_NOT_FOUND) error = ERROR_SUCCESS;
} else if (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) error = ERROR_ACCESS_DENIED;
else error = uninstall_data::Unlink(L"\\\\?\\" + main, attributes);
if (error) { session.mainBlocked = true; Add(session, L"Remove main executable; remaining cleanup not executed", main.c_str(), error); return error; }
WIN32_FIND_DATAW entry{};
HANDLE search = FindFirstFileW((std::wstring(L"\\\\?\\") + directory + L"\\*").c_str(), &entry);
if (search == INVALID_HANDLE_VALUE) { error = GetLastError(); Add(session, L"Enumerate payload; result incomplete", directory, error); return error; }
uninstall_data::Failures failures;
do {
if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0 || _wcsicmp(entry.cFileName, uninstaller) == 0) continue;
uninstall_data::RemoveTree(std::wstring(directory) + L"\\" + entry.cFileName, &failures);
} while (FindNextFileW(search, &entry));
error = GetLastError();
FindClose(search);
Collect(session, failures);
if (error != ERROR_NO_MORE_FILES) { Add(session, L"Enumerate payload; result incomplete", directory, error); return error; }
return ERROR_SUCCESS;
}
}
extern "C" __declspec(dllexport) uninstall_report::Session* __cdecl UninstallBegin(LPCWSTR path) {
// Session storage and callbacks must outlive System plug-in calls.
HMODULE module = nullptr;
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
reinterpret_cast<LPCWSTR>(&UninstallBegin), &module)) return nullptr;
auto* session = new (std::nothrow) uninstall_report::Session;
if (session) session->path = path;
return session;
}
extern "C" __declspec(dllexport) DWORD __cdecl UninstallPrepare(uninstall_report::Session* session, LPCWSTR path, LPCWSTR home) {
bool homeFailure = false;
const DWORD error = uninstall_report::Prepare(*session, path, home, homeFailure);
if (error) uninstall_report::Add(*session, homeFailure ? L"Validate DSH_HOME; no deletion started" : L"Validate removal scope; no deletion started", homeFailure ? home : path, error);
return error;
}
extern "C" __declspec(dllexport) DWORD __cdecl UninstallPayload(uninstall_report::Session* session, LPCWSTR path, LPCWSTR executable, LPCWSTR uninstaller) {
const DWORD error = uninstall_report::Payload(*session, path, executable, uninstaller);
return !error ? 0 : session->mainBlocked ? 1 : 2;
}
extern "C" __declspec(dllexport) void __cdecl UninstallData(uninstall_report::Session* session, LPCWSTR path, LPCWSTR installation, LPCWSTR home) {
uninstall_data::Failures failures;
const DWORD error = uninstall_data::Remove(path, installation, home, &failures);
if (error && failures.empty()) uninstall_report::Add(*session, L"Remove data directory", path, error);
uninstall_report::Collect(*session, failures);
}
extern "C" __declspec(dllexport) void __cdecl UninstallNote(uninstall_report::Session* session, LPCWSTR text) {
session->issues = true;
session->text += std::wstring(L"\r\n") + text + L"\r\n";
}
extern "C" __declspec(dllexport) int __cdecl UninstallShow(uninstall_report::Session* session, HWND parent, int mode,
LPCWSTR title, LPCWSTR heading, LPCWSTR body, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) {
return uninstall_report::Show(parent, *session, mode, title, heading, body, primary, save, failed);
}
extern "C" __declspec(dllexport) int __cdecl UninstallFinish(uninstall_report::Session* session, LPCWSTR directory, LPCWSTR uninstaller) {
const std::wstring file = std::wstring(directory) + L"\\" + uninstaller;
const DWORD attributes = GetFileAttributesW((L"\\\\?\\" + file).c_str());
if (attributes != INVALID_FILE_ATTRIBUTES) {
const DWORD error = uninstall_data::Unlink(L"\\\\?\\" + file, attributes);
if (error) uninstall_report::Add(*session, L"Remove uninstaller", file.c_str(), error);
} else {
const DWORD error = GetLastError();
if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND)
uninstall_report::Add(*session, L"Inspect uninstaller", file.c_str(), error);
}
for (HANDLE handle : session->pinned.values) CloseHandle(handle);
session->pinned.values.clear();
if (!RemoveDirectoryW((std::wstring(L"\\\\?\\") + directory).c_str())) {
const DWORD error = GetLastError();
if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND) uninstall_report::Add(*session, L"Remove installation directory", directory, error);
}
session->text += L"\r\nPayload removal completed. Failed or unverified items are listed above.\r\n";
if (session->issues || GetFileAttributesW(session->path.c_str()) != INVALID_FILE_ATTRIBUTES) extract_report::WriteUtf8(session->path.c_str(), session->text);
return session->issues ? 1 : 0;
}
extern "C" __declspec(dllexport) void __cdecl UninstallPersist(uninstall_report::Session* session) {
extract_report::WriteUtf8(session->path.c_str(), session->text);
}
extern "C" __declspec(dllexport) void __cdecl UninstallImport(uninstall_report::Session* session, LPCWSTR path) {
const std::wstring report = extract_report::ReadOutput(path);
if (!report.empty()) { session->issues = true; session->text += L"\r\n" + report; }
}
extern "C" __declspec(dllexport) int __cdecl UninstallShowOwner(uninstall_report::Session* session, HWND parent,
LPCWSTR title, LPCWSTR heading, LPCWSTR registered, LPCWSTR directory, LPCWSTR registeredLabel,
LPCWSTR scopeLabel, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) {
const std::wstring body = std::wstring(registeredLabel) + L"\r\n" + registered + L"\r\n\r\n"
+ scopeLabel + L"\r\n" + directory;
return uninstall_report::Show(parent, *session, 1, title, heading, body.c_str(), primary, save, failed);
}
+164 -2
View File
@@ -2,15 +2,121 @@
!include FileFunc.nsh
Var UnTarget
Var UnHome
Var UnSession
Var UnDirectoryOnly
Var UnReportPath
Var UnHeading
Var UnBody
Var UnMode
Var UnResult
Var UnRegistered
Var UnRegistrationArguments
Var UnRegistrationEligible
Var UnCleanupResult
Function un.ShowCleanup
System::Call '$PLUGINSDIR\window-frame.dll::UninstallPersist(p $UnSession) ?c'
StrCpy $UnResult 0
${IfNot} ${Silent}
${If} $UnMode == 1
System::Call '$PLUGINSDIR\window-frame.dll::UninstallShowOwner(p $UnSession, p $HWNDPARENT, w "$(^SetupCaption)", w "$UnHeading", w "$UnRegistered", w "$INSTDIR", w "$(INSTALLER_UNINSTALL_REGISTERED)", w "$(INSTALLER_UNINSTALL_SCOPE)", w "$(INSTALLER_UNINSTALL_CONTINUE)", w "$(INSTALLER_UNINSTALL_SAVE)", w "$(INSTALLER_UNINSTALL_SAVE_FAILED)") i.r0 ?c'
${Else}
System::Call '$PLUGINSDIR\window-frame.dll::UninstallShow(p $UnSession, p $HWNDPARENT, i $UnMode, w "$(^SetupCaption)", w "$UnHeading", w "$UnBody", w "$(INSTALLER_UNINSTALL_CONTINUE)", w "$(INSTALLER_UNINSTALL_SAVE)", w "$(INSTALLER_UNINSTALL_SAVE_FAILED)") i.r0 ?c'
${EndIf}
StrCpy $UnResult $0
${EndIf}
FunctionEnd
Function un.BeginCleanup
${If} ${isUpdated}
Return
${EndIf}
InitPluginsDir
File "/oname=$PLUGINSDIR\window-frame.dll" "${INSTALLER_BUILD_DIR}\window-frame.dll"
System::Call 'kernel32::GetCurrentProcessId() i.r0'
StrCpy $UnReportPath "$TEMP\DeepSeek-Harness-uninstall-$0.txt"
System::Call '$PLUGINSDIR\window-frame.dll::UninstallBegin(w "$UnReportPath") p.r0 ?c'
StrCpy $UnSession $0
${If} $UnSession == 0
MessageBox MB_OK|MB_ICONEXCLAMATION "$(INSTALLER_UI_ERROR)" /SD IDOK
SetErrorLevel 2
Quit
${EndIf}
ReadEnvStr $UnHome DSH_HOME
System::Call '$PLUGINSDIR\window-frame.dll::UninstallPrepare(p $UnSession, w "$INSTDIR", w "$UnHome") i.r0 ?c'
${If} $0 != 0
StrCpy $UnMode 4
StrCpy $UnHeading "$(INSTALLER_UNINSTALL_INCOMPLETE)"
StrCpy $UnBody "$(INSTALLER_UNINSTALL_UNSAFE)$\r$\n$INSTDIR"
Call un.ShowCleanup
SetErrorLevel 2
Quit
${EndIf}
ReadRegStr $UnRegistered SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation
${If} $UnRegistered != ""
GetFullPathName $UnRegistered "$UnRegistered\."
GetFullPathName $0 "$INSTDIR\."
${If} $UnRegistered != $0
StrCpy $UnMode 1
StrCpy $UnHeading "$(INSTALLER_UNINSTALL_OWNER)"
Call un.ShowCleanup
${If} $UnResult != 1001
System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "Removal not confirmed; no deletion started. Registered installation: $UnRegistered. Uninstall directory: $INSTDIR.") ?c'
System::Call '$PLUGINSDIR\window-frame.dll::UninstallPersist(p $UnSession) ?c'
SetErrorLevel 2
Quit
${EndIf}
StrCpy $UnDirectoryOnly 1
${EndIf}
${EndIf}
SetOutPath $TEMP
cleanupRetry:
System::Call '$PLUGINSDIR\window-frame.dll::UninstallPayload(p $UnSession, w "$INSTDIR", w "${APP_EXECUTABLE_FILENAME}", w "${UNINSTALL_FILENAME}") i.r0 ?c'
${If} $0 != 0
StrCpy $UnMode 4
StrCpy $UnHeading "$(INSTALLER_UNINSTALL_INCOMPLETE)"
StrCpy $UnBody "$(INSTALLER_UNINSTALL_UNKNOWN)$\r$\n$INSTDIR"
${If} $0 == 1
StrCpy $UnMode 2
StrCpy $UnBody "$(INSTALLER_UNINSTALL_BLOCKED)$\r$\n$INSTDIR\${APP_EXECUTABLE_FILENAME}"
${EndIf}
Call un.ShowCleanup
${If} $UnResult == 4
Goto cleanupRetry
${EndIf}
SetErrorLevel 2
Quit
${EndIf}
FunctionEnd
Function un.FinishCleanup
${If} ${isUpdated}
Return
${EndIf}
System::Call '$PLUGINSDIR\window-frame.dll::UninstallFinish(p $UnSession, w "$INSTDIR", w "${UNINSTALL_FILENAME}") i.r0 ?c'
StrCpy $UnCleanupResult $0
${If} $UnRegistrationEligible == 1
StrCpy $UnRegistrationArguments "-UnownedOnly"
Call un.RunRegistrationCleanup
${EndIf}
${If} $UnCleanupResult != 0
DetailPrint $UnReportPath
StrCpy $UnMode 3
StrCpy $UnHeading "$(INSTALLER_UNINSTALL_COMPLETE)"
StrCpy $UnBody "$(INSTALLER_UNINSTALL_REGISTRATION)"
Call un.ShowCleanup
${EndIf}
FunctionEnd
; The helper refuses unsafe roots, the installation and the Harness home, and never descends into reparse points;
; a locked file leaves residue and never fails the uninstall. customCheckAppRunning extracts window-frame.dll first.
; failed auxiliary removals are recorded while other siblings continue.
Function un.RemoveData
System::Call '$PLUGINSDIR\window-frame.dll::UninstallRemoveData(w "$UnTarget", w "$INSTDIR", w "$UnHome") ?c'
System::Call '$PLUGINSDIR\window-frame.dll::UninstallData(p $UnSession, w "$UnTarget", w "$INSTDIR", w "$UnHome") ?c'
FunctionEnd
Function un.CleanData
${If} ${isUpdated}
${OrIf} $UnDirectoryOnly == 1
Return
${EndIf}
; The installer runs an older uninstaller with /KEEP_APP_DATA when replacing it from another directory.
@@ -34,3 +140,59 @@ Function un.CleanData
StrCpy $UnTarget "$LOCALAPPDATA\${DSH_UPDATER_CACHE_NAME}"
Call un.RemoveData
FunctionEnd
; Upgrade replacement retains integrations; KEEP_APP_DATA controls only user data.
!define /ifndef DSH_COMMAND_ENVIRONMENT_KEY "Environment"
!define /ifndef DSH_COMMAND_OWNER_KEY "Software\DeepSeekHarness\Command"
!define /ifndef DSH_PROTOCOL_KEY "Software\Classes\dsh"
!define /ifndef DSH_COMMAND_MUTEX "default"
Function un.CleanRegistration
${If} ${isUpdated}
Return
${EndIf}
ReadRegStr $0 SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation
${If} $0 == ""
; Preserve shared state and check each Windows entry against its own target.
StrCpy $UnDirectoryOnly 1
${Else}
GetFullPathName $0 "$0\."
GetFullPathName $1 "$INSTDIR\."
${If} $0 != $1
StrCpy $UnDirectoryOnly 1
${EndIf}
${EndIf}
Delete "$PLUGINSDIR\unowned-path"
StrCpy $UnRegistrationArguments ""
${If} $UnDirectoryOnly == 1
StrCpy $UnRegistrationArguments '-DesktopLink "$oldDesktopLink" -StartMenuLink "$oldStartMenuLink" -UninstallKey "${UNINSTALL_REGISTRY_KEY}" -UninstallerName "${UNINSTALL_FILENAME}"'
!ifdef UNINSTALL_REGISTRY_KEY_2
StrCpy $UnRegistrationArguments '$UnRegistrationArguments -LegacyUninstallKey "${UNINSTALL_REGISTRY_KEY_2}"'
!endif
${EndIf}
Call un.RunRegistrationCleanup
IfFileExists "$PLUGINSDIR\unowned-path" 0 +2
StrCpy $UnRegistrationEligible 1
FunctionEnd
Function un.RunRegistrationCleanup
InitPluginsDir
File /oname=$PLUGINSDIR\command-path.ps1 "${__FILEDIR__}\..\scripts\command-path.ps1"
File /oname=$PLUGINSDIR\uninstall-registration.ps1 "${__FILEDIR__}\..\scripts\uninstall-registration.ps1"
Delete "$PLUGINSDIR\registration-report.txt"
nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\uninstall-registration.ps1" -Directory "$INSTDIR" -ExecutableName "${APP_EXECUTABLE_FILENAME}" -EnvironmentKey "${DSH_COMMAND_ENVIRONMENT_KEY}" -OwnerKey "${DSH_COMMAND_OWNER_KEY}" -ProtocolKey "${DSH_PROTOCOL_KEY}" -ReportPath "$PLUGINSDIR\registration-report.txt" -MutexName "${DSH_COMMAND_MUTEX}" -UnownedMarker "$PLUGINSDIR\unowned-path" $UnRegistrationArguments'
Pop $0
Pop $1
System::Call '$PLUGINSDIR\window-frame.dll::UninstallImport(p $UnSession, w "$PLUGINSDIR\registration-report.txt") ?c'
${If} $0 != 0
StrCpy $UnCleanupResult 1
DetailPrint $1
${If} $UnDirectoryOnly == 1
${AndIf} $UnRegistrationArguments != "-UnownedOnly"
System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "[unverified] Registration cleanup targets: HKCU\${UNINSTALL_REGISTRY_KEY}; $oldDesktopLink; $oldStartMenuLink") ?c'
!ifdef UNINSTALL_REGISTRY_KEY_2
System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "[unverified] Registration cleanup target: HKCU\${UNINSTALL_REGISTRY_KEY_2}") ?c'
!endif
${EndIf}
System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "Registration cleanup failed or did not return a result. Exit: $0. Targets: HKCU\${DSH_COMMAND_ENVIRONMENT_KEY} [Path]; HKCU\${DSH_COMMAND_OWNER_KEY}; HKCU\${DSH_PROTOCOL_KEY}. Unverified registrations may remain.") ?c'
${EndIf}
FunctionEnd
+1
View File
@@ -33,6 +33,7 @@ static HRESULT ApplyInstallerDwmFrame(HWND window) {
#include "extract-report.h"
#include "directory-report.h"
#include "uninstall-data.h"
#include "uninstall-report.h"
using namespace Gdiplus;
+2 -2
View File
@@ -45,8 +45,8 @@
en: b42f103358d0dfd7
zh: a534164ad9eb00da
/desktop-packaging/runtime-file-selection-and-installation-checks:
en: da4669b98c79ee48
zh: d007e87f13ff54d3
en: 1d153e4ba7528414
zh: cdf15fb80099ce17
/desktop-packaging/desktop-runtime-preparation:
en: 84be38ab3136fff7
zh: bb4ed12ee0e1dfa0
+1 -1
View File
@@ -262,7 +262,7 @@ Windows release qualification also runs [directory and replacement checks](../sc
pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis -SevenZip $SevenZip -PluginDir $PluginDir -FrameLibrary apps/desktop/.desktop-build/targets/win-x64/installer-ui/window-frame.dll
```
The Windows installer checks for a running application at startup and after destination selection, before extracting the new version beside the installation directory. It checks again before replacing directories through same-volume renames. A running application blocks installation; update launches allow up to ten seconds for it to exit. Same-path upgrades preserve the old directory until promotion succeeds; extraction failure leaves it intact, and promotion failure attempts to restore it. The installer removes the old backup before launch. Forced termination or power loss can leave `.new-*` or `.old-*` directories; installation-location and scope migrations retain electron-builder's old-uninstaller flow.
The Windows installer checks for a running application at startup and after destination selection, before extracting the new version beside the installation directory. It checks again before replacing directories through same-volume renames. A running application blocks installation; update launches allow up to ten seconds for it to exit. Same-path upgrades preserve the old directory until promotion succeeds; extraction failure leaves it intact, and promotion failure attempts to restore it. The installer removes the old backup before launch. Forced termination or power loss can leave `.new-*` or `.old-*` directories; installation-location and scope migrations retain electron-builder's old-uninstaller flow, using extended paths for both file moves and rollback.
Directory renames, empty-destination removal, and restoration retry Windows errors 5, 32, and 33 up to ten attempts, with 250 ms increasing delays (11.25 seconds of total waiting per operation). Other errors stop immediately. A replacement failure reports the Windows error, affected paths, and restoration outcome in `directory-failure-<timestamp>.log` beside extraction reports. If restoration fails, the installer removes unlocked staging files and preserves the backup. After reporting that failure, exit cleanup does not retry restoration. Keep the backup path named in the report and contact support before reinstalling. Silent installs save the same diagnostic without a dialog.
+1 -1
View File
@@ -262,7 +262,7 @@ Windows 发布验收还需在 Desktop 构建后手动运行[目录和替换检
pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis -SevenZip $SevenZip -PluginDir $PluginDir -FrameLibrary apps/desktop/.desktop-build/targets/win-x64/installer-ui/window-frame.dll
```
Windows 安装器在启动时和选定目标目录后检查应用是否正在运行,通过检查后才将新版本解压到安装目录旁边。通过同卷目录改名替换前,安装器会再次检查。运行中的应用会阻止安装;更新启动允许等待应用退出,最长十秒。同路径升级在替换成功前保留旧目录;解压失败时旧版不变,替换失败时尝试恢复旧目录。安装器在启动前清理旧版备份。强制结束安装器或断电可能留下 `.new-*` 或 `.old-*` 目录;不同安装位置或安装范围迁移仍使用 electron-builder 的旧卸载器流程。
Windows 安装器在启动时和选定目标目录后检查应用是否正在运行,通过检查后才将新版本解压到安装目录旁边。通过同卷目录改名替换前,安装器会再次检查。运行中的应用会阻止安装;更新启动允许等待应用退出,最长十秒。同路径升级在替换成功前保留旧目录;解压失败时旧版不变,替换失败时尝试恢复旧目录。安装器在启动前清理旧版备份。强制结束安装器或断电可能留下 `.new-*` 或 `.old-*` 目录;不同安装位置或安装范围迁移仍使用 electron-builder 的旧卸载器流程,文件移动与失败恢复均使用扩展路径。
目录改名、空目标目录删除和旧版恢复遇到 Windows 错误 5、32 或 33 时最多尝试十次,每次等待递增 250 毫秒(每个操作合计等待 11.25 秒)。其他错误立即停止。替换失败时,安装器将 Windows 错误、相关路径和恢复结果写入解压报告旁的 `directory-failure-<时间戳>.log`。如果恢复失败,安装器会清理未被占用的暂存文件并保留备份。上报此失败后,退出清理不再重试恢复。请保留报告所列的备份目录,并在重新安装前联系支持人员。静默安装保存相同的诊断,不显示弹窗。
+19 -1
View File
@@ -1,6 +1,7 @@
<# Per-user PATH ownership. The worker owns its mutex through registry publication. #>
function Invoke-DshCommandPath {
param([hashtable]$Request, [string]$EnvironmentKey, [string]$OwnerKey, [string]$MachinePath, [string]$MutexName)
param([hashtable]$Request, [string]$EnvironmentKey, [string]$OwnerKey, [string]$MachinePath, [string]$MutexName,
[string]$RemovedInstallation)
$ErrorActionPreference = 'Stop'
function Fail([string]$Code, [string]$Message) {
$error = [InvalidOperationException]::new($Message)
@@ -50,6 +51,23 @@ function Invoke-DshCommandPath {
$current = Comparable $directory
$old = if ($owned) { Comparable ([string]$owned) } else { $null }
$kept = $parts
# Unowned PATH cleanup is restricted to the exact CLI directory of an absent installation.
if ($RemovedInstallation -and $Request.operation -eq 'remove' -and -not $old) {
if (-not [IO.Path]::IsPathRooted($RemovedInstallation) -or
$current -ne (Comparable (Join-Path $RemovedInstallation 'resources\runtime\cli\bin'))) {
Fail 'EINVAL' 'The command directory does not belong to the removed installation.'
}
$matches = @($parts | Where-Object { (Comparable $_) -eq $current })
if ($matches.Count) {
$absent = $false
try { [void][IO.File]::GetAttributes($RemovedInstallation) } catch {
$cause = $_.Exception.GetBaseException()
if (($cause.HResult -band 0xffff) -in @(2, 3)) { $absent = $true } else { throw }
}
if (-not $absent) { Fail 'EEXIST' 'The installation directory remains; unowned PATH entries were retained.' }
$kept = @($parts | Where-Object { (Comparable $_) -ne $current })
}
}
if ($old -and ($Request.operation -eq 'install' -or ($Request.operation -eq 'remove' -and $old -eq $current))) {
$ownedMatches = @($parts | Where-Object { $_ -ceq $owned }).Count
if ($ownedMatches -gt $retained) {
+9
View File
@@ -94,6 +94,8 @@ ManifestDPIAware true
!macroend
!macro customUnInstall
Call un.BeginCleanup
Call un.CleanRegistration
Call un.CleanData
!macroend
@@ -172,6 +174,10 @@ ManifestDPIAware true
!macroend
!macro customCheckAppRunning
!ifdef BUILD_UNINSTALLER
; Manual uninstall reports deletion errors with retry and a saveable report.
${If} ${isUpdated}
!endif
!ifdef BUILD_UNINSTALLER
InitPluginsDir
File "/oname=$PLUGINSDIR\window-frame.dll" "${INSTALLER_BUILD_DIR}\window-frame.dll"
@@ -200,6 +206,9 @@ ManifestDPIAware true
SetErrorLevel 2
Quit
${EndIf}
!ifdef BUILD_UNINSTALLER
${EndIf}
!endif
!macroend
!macro customInstallerDirectoryFailed
@@ -1,4 +1,4 @@
<# Compile the x86 DWM helper and raster assets embedded in the NSIS installer. #>
<# Compile the x86 DWM helper and raster assets embedded in the NSIS installer. #>
[CmdletBinding()]
param([string]$OutputDirectory, [switch]$TestProgress, [switch]$CompileProgressOnly)
$ErrorActionPreference = 'Stop'
@@ -14,7 +14,7 @@ $visualStudio = & $vswhere -latest -products '*' -requires Microsoft.VisualStudi
if (-not $visualStudio) { throw 'Visual Studio C++ Build Tools are missing.' }
$vcvars = Join-Path $visualStudio 'VC/Auxiliary/Build/vcvars32.bat'
$compileScript = Join-Path $output 'compile-frame.cmd'
$compileLines = @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /LD /MT /O1 /W4 /WX /EHsc "{0}" /Fo"{1}" /link /OUT:"{2}" /IMPLIB:"{3}" user32.lib gdi32.lib comctl32.lib dwmapi.lib gdiplus.lib ole32.lib shell32.lib uuid.lib advapi32.lib' -f $source, (Join-Path $output 'window-frame.obj'), $library, (Join-Path $output 'window-frame.lib')))
$compileLines = @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /LD /MT /O1 /W4 /WX /EHsc "{0}" /Fo"{1}" /link /OUT:"{2}" /IMPLIB:"{3}" user32.lib gdi32.lib comdlg32.lib comctl32.lib dwmapi.lib gdiplus.lib ole32.lib shell32.lib uuid.lib advapi32.lib' -f $source, (Join-Path $output 'window-frame.obj'), $library, (Join-Path $output 'window-frame.lib')))
[IO.File]::WriteAllLines($compileScript, $compileLines, [Text.Encoding]::Default)
& $env:ComSpec /d /c $compileScript
if ($LASTEXITCODE -ne 0) { throw 'Native installer helper compilation failed.' }
@@ -23,7 +23,7 @@ if ($TestProgress -or $CompileProgressOnly) {
# UAC installer detection demands elevation from unmanifested executables named after installation.
$cleanupExecutable = Join-Path $output 'data-cleanup-test.exe'
$cleanupScript = Join-Path $output 'compile-data-cleanup-test.cmd'
[IO.File]::WriteAllLines($cleanupScript, @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /MT /W4 /WX /EHsc "{0}" /Fo"{1}" /Fe"{2}" /link shell32.lib ole32.lib uuid.lib advapi32.lib' -f $cleanupSource, (Join-Path $output 'data-cleanup-test.obj'), $cleanupExecutable)), [Text.Encoding]::Default)
[IO.File]::WriteAllLines($cleanupScript, @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /MT /W4 /WX /EHsc "{0}" /Fo"{1}" /Fe"{2}" /link "{3}" shell32.lib ole32.lib uuid.lib advapi32.lib' -f $cleanupSource, (Join-Path $output 'data-cleanup-test.obj'), $cleanupExecutable, (Join-Path $output 'window-frame.lib'))), [Text.Encoding]::Default)
& $env:ComSpec /d /c $cleanupScript
if ($LASTEXITCODE -ne 0) { throw 'Uninstall data test compilation failed.' }
if ($TestProgress) {
@@ -55,6 +55,8 @@ try {
})
const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs')
const childOptions = { env: scrubWindowsSigningEnvironment(process.env), windowsHide: true, maxBuffer: 8 * 1024 * 1024 }
await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
join(appRoot, 'tests', 'windows-installer-process-test.ps1'), '-OutputDirectory', output], childOptions)
await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
join(appRoot, 'scripts', 'prepare-windows-installer.ps1'), '-OutputDirectory', join(output, 'ui'), '-CompileProgressOnly'], childOptions)
const progressTest = join(output, 'ui', 'progress-test.exe')
@@ -131,11 +133,12 @@ SectionEnd
const strings = join(languageOutput, 'strings.nsh')
await writeFile(strings, renderInstallerStrings([locale]), 'utf8')
const include = join(languageOutput, 'include.nsh')
await writeFile(include, `!define INSTALLER_BUILD_DIR "${join(output, 'ui')}"\n!define INSTALLER_STRINGS_FILE "${strings}"\n!include "${join(appRoot, 'scripts', 'installer.nsh')}"\n`)
await writeFile(include, `!define DSH_COMMAND_MUTEX "Local\\DSHUninstallTests-${guid}"\n!define DSH_COMMAND_ENVIRONMENT_KEY "Software\\DSHUninstallTests\\${guid}\\CommandEnvironment"\n!define DSH_COMMAND_OWNER_KEY "Software\\DSHUninstallTests\\${guid}\\CommandOwner"\n!define DSH_PROTOCOL_KEY "Software\\Classes\\dsh-test-${guid}"\n!define INSTALLER_BUILD_DIR "${join(output, 'ui')}"\n!define INSTALLER_STRINGS_FILE "${strings}"\n!include "${join(appRoot, 'scripts', 'installer.nsh')}"\n`)
await build({ projectDir: appRoot, prepackaged: payload, targets: Platform.WINDOWS.createTarget(['nsis'], Arch.x64), publish: 'never',
config: { ...config, productName, extraMetadata: { ...config.extraMetadata, name: packageName },
artifactName: 'installer-test.exe', directories: { output: languageOutput },
nsis: { ...config.nsis, guid, include, installerLanguages: [language] }, beforeBuild: undefined, afterPack: undefined, afterSign: undefined, artifactBuildCompleted: undefined },
nsis: { ...config.nsis, guid, include, installerSidebar: join(output, 'ui', 'uninstaller-sidebar.bmp'),
uninstallerSidebar: join(output, 'ui', 'uninstaller-sidebar.bmp'), installerLanguages: [language] }, beforeBuild: undefined, afterPack: undefined, afterSign: undefined, artifactBuildCompleted: undefined },
})
if (process.argv.includes('--compile-only')) continue
const result = await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
@@ -0,0 +1,87 @@
<# Remove only owned registrations; independently failed operations leave a diagnostic report. #>
param([Parameter(Mandatory)][string]$Directory,
[string]$ExecutableName = 'DeepSeek Harness.exe',
[Parameter(Mandatory)][string]$EnvironmentKey,
[Parameter(Mandatory)][string]$OwnerKey,
[Parameter(Mandatory)][string]$ProtocolKey,
[Parameter(Mandatory)][string]$ReportPath,
[string]$MutexName,
[switch]$UnownedOnly,
[string]$UnownedMarker,
[string]$DesktopLink,
[string]$StartMenuLink,
[string]$UninstallKey,
[string]$LegacyUninstallKey,
[string]$UninstallerName)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'command-path.ps1')
$failures = [Collections.Generic.List[string]]::new()
try {
if (-not $MutexName -or $MutexName -eq 'default') {
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$MutexName = 'Global\DeepSeekHarness.Command.' + $sid
}
$options = @{ EnvironmentKey=$EnvironmentKey; OwnerKey=$OwnerKey; MachinePath=''; MutexName=$MutexName }
$command = Join-Path $Directory 'resources\runtime\cli\bin'
$state = Invoke-DshCommandPath -Request @{operation='inspect'; directory=$command} @options
if ($UnownedOnly) {
if (-not $state.ownedDirectory) {
[void](Invoke-DshCommandPath -Request @{operation='remove'; directory=$command; expected=$state.fingerprint} @options -RemovedInstallation $Directory)
Send-DshCommandEnvironmentChange
}
} elseif ($state.managed) {
[void](Invoke-DshCommandPath -Request @{operation='remove'; directory=$command; expected=$state.fingerprint} @options)
Send-DshCommandEnvironmentChange
} elseif (-not $state.ownedDirectory -and $UnownedMarker) {
[IO.File]::WriteAllText($UnownedMarker, '')
}
} catch {
$failures.Add("[unverified] Remove owned command registration`r`nHKCU\$EnvironmentKey [Path]`r`nHKCU\$OwnerKey`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)")
}
if (-not $UnownedOnly) { try {
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($ProtocolKey + '\shell\open\command')
try { $registered = if ($key) { $key.GetValue('') } else { $null } }
finally { if ($key) { $key.Dispose() } }
$expected = '"' + (Join-Path $Directory $ExecutableName) + '" "%1"'
if ($registered -eq $expected) {
[Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($ProtocolKey, $false)
}
} catch {
$failures.Add("[unverified] Remove protocol registration`r`nHKCU\$ProtocolKey`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)")
} }
foreach ($uninstallEntry in @($UninstallKey, $LegacyUninstallKey)) {
if (-not $uninstallEntry) { continue }
try {
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($uninstallEntry)
try { $registered = if ($key) { $key.GetValue('UninstallString') } else { $null } }
finally { if ($key) { $key.Dispose() } }
if ($null -eq $registered) { continue }
if ($registered -isnot [string]) { throw 'UninstallString is not a string' }
# Only the command emitted by the per-user installer is eligible for removal.
if ($registered -match '^\s*"([^"]+)"\s+/currentuser\s*$') {
$target = [IO.Path]::GetFullPath($Matches[1])
$expected = [IO.Path]::GetFullPath((Join-Path $Directory $UninstallerName))
if ($target -eq $expected) {
[Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($uninstallEntry, $false)
}
}
} catch {
$failures.Add("[unverified] Inspect or remove uninstall entry`r`nHKCU\$uninstallEntry [UninstallString]`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)")
}
}
foreach ($link in @($DesktopLink, $StartMenuLink)) {
if (-not $link) { continue }
try {
if ([IO.Path]::GetExtension($link) -ne '.lnk' -or -not (Test-Path -LiteralPath $link -PathType Leaf)) { continue }
$shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($link)
if ($shortcut.TargetPath -eq (Join-Path $Directory $ExecutableName)) {
[IO.File]::Delete($link)
}
} catch {
$failures.Add("[unverified] Remove shortcut: $link`r`nReason: $($_.Exception.Message)")
}
}
if ($failures.Count) {
[IO.File]::WriteAllText($ReportPath, ($failures -join "`r`n`r`n"), [Text.UTF8Encoding]::new($true))
exit 1
}
@@ -15,9 +15,16 @@ export function directoryInstallSection(source: string): string
export function directoryInstallerExits(source: string): string
/**
* Keep user-data removal in the native helper, which refuses unsafe roots and never follows links.
* Preserve data but clean old registrations when replacing another installation directory.
* @param source Pinned NSIS installUtil.nsh contents.
* @returns Helper reserving --updated for replacement at the same path.
*/
export function directoryInstallUtil(source: string): string
/**
* Retain the original uninstall directory and bypass shared cleanup for directory-only removal.
* @param source - Pinned upstream uninstaller source.
* @returns Uninstaller with long-path application removal and no upstream RMDir data removal.
* @returns Uninstaller with long-path removal, native data cleanup, and upgrade rollback; updated-mode ownership mismatches exit with code 2.
*/
export function directoryUninstaller(source: string): string
@@ -52,6 +52,17 @@ export function directoryInstallerExits(source) {
return source.replaceAll(/^(\s*)Quit\s*$/gm, '$1!ifndef BUILD_UNINSTALLER\n$1Call dshCleanupDirectories\n$1!endif\n$1Quit')
}
/**
* Preserve data but clean old registrations when replacing another installation directory.
* @param {string} source - Pinned NSIS installUtil.nsh contents.
* @returns {string} Helper reserving --updated for replacement at the same path.
*/
export function directoryInstallUtil(source) {
return replaceOnce(source.replaceAll('\r\n', '\n'),
' # always pass --updated flag - to ensure that if DELETE_APP_DATA_ON_UNINSTALL is defined, user data will be not removed\n StrCpy $0 "$0 --updated"',
' # /KEEP_APP_DATA retains data during relocation; old path registrations must be removed.\n ${if} $installationDir == $INSTDIR\n StrCpy $0 "$0 --updated"\n ${endif}')
}
/** Install the build-only NSIS adapter without replacing electron-builder's signed bootstrap path. */
export function installWindowsDirectoryInstaller() {
// The package entry initializes the platform classes before their mutually dependent leaves.
@@ -74,7 +85,8 @@ export function installWindowsDirectoryInstaller() {
let adapted = replaceOnce(source, '!include "installSection.nsh"', `!include "${section}"`)
for (const helper of ['allowOnlyOneInstallerInstance.nsh', 'installUtil.nsh']) {
const path = join(directory, helper)
await writeFile(path, directoryInstallerExits(await readFile(join(templates, 'include', helper), 'utf8')))
const original = await readFile(join(templates, 'include', helper), 'utf8')
await writeFile(path, directoryInstallerExits(helper === 'installUtil.nsh' ? directoryInstallUtil(original) : original))
adapted = replaceOnce(adapted, `!include "${helper}"`, `!include "${path}"`)
}
const uninstaller = join(directory, 'uninstaller.nsh')
@@ -85,14 +97,40 @@ export function installWindowsDirectoryInstaller() {
}
/**
* Keep user-data removal in the native helper, which refuses unsafe roots and never follows links.
* Retain the original uninstall directory and bypass shared cleanup for directory-only removal.
* @param {string} source - Pinned upstream uninstaller source.
* @returns {string} Uninstaller with long-path application removal and no upstream RMDir data removal.
* @returns {string} Uninstaller with long-path removal, native data cleanup, and upgrade rollback; updated-mode ownership mismatches exit with code 2.
*/
export function directoryUninstaller(source) {
const normalized = source.replaceAll('\r\n', '\n')
let normalized = source.replaceAll('\r\n', '\n')
normalized = normalized.replaceAll('"$INSTDIR$R0', '"\\\\?\\$INSTDIR$R0')
.replaceAll('"$PLUGINSDIR\\old-install', '"\\\\?\\$PLUGINSDIR\\old-install')
normalized = replaceOnce(normalized, 'Function un.onInit\n', 'Var dshUninstallDirectory\nFunction un.onInit\n StrCpy $dshUninstallDirectory $INSTDIR\n')
normalized = replaceOnce(normalized, ' !insertmacro initMultiUser', ` !insertmacro initMultiUser
StrCpy $INSTDIR $dshUninstallDirectory
\${If} \${isUpdated}
ReadRegStr $R0 SHELL_CONTEXT "\${INSTALL_REGISTRY_KEY}" InstallLocation
GetFullPathName $R0 "$R0\\."
GetFullPathName $R1 "$INSTDIR\\."
\${If} $R0 != $R1
SetErrorLevel 2
Quit
\${EndIf}
\${EndIf}`)
const payloadStart = normalized.indexOf(' # delete the installed files\n')
const payloadEnd = normalized.indexOf(' ${ifNot} ${isKeepShortcuts}', payloadStart)
if (payloadStart < 0 || payloadEnd < 0) throw new Error('NSIS uninstaller payload template changed')
normalized = normalized.slice(0, payloadStart) + ' ${If} ${isUpdated}\n'
+ normalized.slice(payloadStart, payloadEnd) + ' ${EndIf}\n'
+ ' ${If} $UnDirectoryOnly == 1\n Goto dshUninstallFinished\n ${EndIf}\n'
+ normalized.slice(payloadEnd)
normalized = replaceOnce(normalized, ' !ifdef ONE_CLICK\n !insertmacro quitSuccess',
'dshUninstallFinished:\n Call un.FinishCleanup\n !ifdef ONE_CLICK\n !insertmacro quitSuccess')
const start = normalized.indexOf(' Var /GLOBAL isDeleteAppData\n')
const end = normalized.indexOf(' DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"', start)
if (start < 0 || end < 0) throw new Error('NSIS uninstaller data removal template changed')
return replaceOnce(normalized.slice(0, start) + normalized.slice(end), 'RMDir /r $INSTDIR', 'RMDir /r "\\\\?\\$INSTDIR"')
normalized = normalized.slice(0, start) + normalized.slice(end)
normalized = normalized.replaceAll(/^(\s*)(DeleteRegKey SHELL_CONTEXT "[^"]+"|Delete "\$old(?:Desktop|StartMenu)Link")$/gm, (_, indent, operation) =>
`${indent}ClearErrors\n${indent}${operation}\n${indent}\${If} \${Errors}\n${indent} \${IfNot} \${isUpdated}\n${indent} System::Call '$PLUGINSDIR\\window-frame.dll::UninstallNote(p $UnSession, w "[unverified] ${operation.replaceAll('"', '')}") ?c'\n${indent} \${EndIf}\n${indent}\${EndIf}`)
return replaceOnce(normalized, 'RMDir /r $INSTDIR', 'RMDir /r "\\\\?\\$INSTDIR"')
}
+2
View File
@@ -2,6 +2,7 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
@@ -15,6 +16,7 @@ it.skipIf(process.platform !== 'win32')('preserves unrelated PATH entries and re
const result = await promisify(execFile)(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File',
join(import.meta.dirname, 'fixtures', 'command-path.ps1'),
'-Electron', createRequire(import.meta.url)('electron') as string,
'-Worker', join(import.meta.dirname, '..', 'scripts', 'command-path.ps1'), '-Root', root,
], { timeout: 60000, windowsHide: true })
expect(result.stdout).toContain('WINDOWS_COMMAND_PATH_OK')
@@ -1,3 +1,23 @@
{
"cases": ["interactive", "silent", "upgrade", "replaced", "home-inside"]
"cases": [
"interactive",
"silent",
"unowned",
"missing-location",
"missing-location-short",
"missing-location-foreign",
"owned-retained",
"upgrade",
"replaced",
"home-inside",
"home-slash",
"home-tilde",
"home-slash-inside",
"registration-error",
"main-locked",
"self-copy",
"auxiliary-locked",
"unsafe-root",
"save-report"
]
}
+55 -1
View File
@@ -1,4 +1,4 @@
param([string]$Worker, [string]$Root)
param([string]$Worker, [string]$Root, [Parameter(Mandatory)][string]$Electron)
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
. $Worker
@@ -92,7 +92,61 @@ try {
Require ((UserPath) -eq ($desktop + ';' + $invalidPath)) 'a notification failure changed the committed PATH'
[void](Apply 'remove' $desktop)
Require ((UserPath) -eq $invalidPath) 'removal changed invalid user PATH entries'
# Uninstalling A must preserve independently registered B integrations.
$app = Join-Path $Root 'Uninstall A'
$bin = Join-Path $app 'resources\runtime\cli\bin'
New-Item -ItemType Directory -Force $bin | Out-Null
[IO.File]::WriteAllText((Join-Path $bin 'dsh.cmd'), 'fixture')
[void](Apply 'install' $other)
$protocolKey = $keyRoot + '\Protocol'
$foreignCommand = '"' + (Join-Path $other 'DeepSeek Harness.exe') + '" "%1"'
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command')
try { $key.SetValue('', $foreignCommand) } finally { $key.Dispose() }
$helper = Join-Path (Split-Path $Worker) 'uninstall-registration.ps1'
& powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath (Join-Path $Root 'uninstall-report.txt') -MutexName $options.MutexName
Require ($LASTEXITCODE -eq 0) 'foreign integration cleanup failed'
Require ((State $other).managed) 'uninstall removed foreign command ownership'
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($protocolKey + '\shell\open\command')
try { Require ($key.GetValue('') -eq $foreignCommand) 'uninstall removed foreign protocol' } finally { $key.Dispose() }
[void](Apply 'install' $bin)
$scheme = 'dsh-command-test-' + $identity
$protocolKey = 'Software\Classes\' + $scheme
$launcher = Join-Path $PSScriptRoot 'register-test-protocol.cjs'
$exe = Join-Path $app 'DeepSeek Harness.exe'
$registration = Start-Process $Electron -ArgumentList @(('"' + $launcher + '"'), ('"--user-data-dir=' + $Root + '\profile"'), $scheme, ('"' + $exe + '"')) -PassThru -WindowStyle Hidden
try {
if (-not $registration.WaitForExit(20000)) { $registration.Kill(); $registration.WaitForExit(); throw 'Electron protocol registration timed out' }
Require ($registration.ExitCode -eq 0) 'Electron could not register the test protocol'
} finally { $registration.Dispose() }
Require (Test-Path -LiteralPath ('HKCU:\' + $protocolKey + '\shell\open\command')) 'Electron did not write the protocol command'
& powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath (Join-Path $Root 'uninstall-report.txt') -MutexName $options.MutexName
Require ($LASTEXITCODE -eq 0) 'owned integration cleanup failed'
Require (-not (State $bin).managed) 'uninstall retained command ownership'
Require (-not (Test-Path -LiteralPath ('HKCU:\' + $protocolKey))) 'uninstall retained protocol'
# Missing ownership does not authorize removal while any of the installation remains.
$orphanPath = $bin + ';"' + $bin.ToUpperInvariant() + '\";C:\Windows;' + $other
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true)
try { $key.SetValue('Path', $orphanPath, [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Dispose() }
$report = Join-Path $Root 'unowned-report.txt'
& powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath $report -MutexName $options.MutexName -UnownedOnly
Require ($LASTEXITCODE -eq 1) 'unowned cleanup accepted an existing installation'
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey)
try { Require ($key.GetValue('Path') -eq $orphanPath) 'unowned cleanup changed PATH before directory removal' } finally { $key.Dispose() }
Require ([IO.File]::ReadAllText($report).Contains('installation directory remains')) 'unowned refusal lacks a report'
[IO.Directory]::Delete($app, $true)
& powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath $report -MutexName $options.MutexName -UnownedOnly
Require ($LASTEXITCODE -eq 0) 'unowned cleanup failed after directory removal'
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey)
try {
Require ($key.GetValue('Path') -eq ('C:\Windows;' + $other)) 'unowned cleanup failed to preserve other PATH entries'
Require ($key.GetValueKind('Path') -eq [Microsoft.Win32.RegistryValueKind]::ExpandString) 'unowned cleanup changed PATH type'
} finally { $key.Dispose() }
[void](Apply 'install' $other)
$foreignState = State $other
& powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath $report -MutexName $options.MutexName -UnownedOnly
Require ($LASTEXITCODE -eq 0 -and (State $other).fingerprint -eq $foreignState.fingerprint) 'unowned cleanup changed a new owner'
'WINDOWS_COMMAND_PATH_OK'
} finally {
[Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree(('Software\Classes\dsh-command-test-' + $identity), $false)
[Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($keyRoot, $false)
}
@@ -0,0 +1,4 @@
/** Register an isolated protocol through the Electron version used by Desktop. */
const { app } = require('electron')
const [scheme, executable] = process.argv.slice(-2)
app.whenReady().then(() => app.exit(app.setAsDefaultProtocolClient(scheme, executable) ? 0 : 1))
+1 -1
View File
@@ -24,7 +24,7 @@ it('generates Japanese NSIS strings from the same files that select packaged lan
expect(source).toContain('LangString INSTALLER_NATIVE_PROGRESS ${LANG_JAPANESE} "インストールを準備しています… %d%%"')
expect(source).toContain('!ifdef LANG_JAPANESE\n')
expect(source.match(/^LangString INSTALLER_UPDATE_WAIT /gmu)).toHaveLength(8)
expect(source.match(/^LangString /gmu)).toHaveLength(256)
expect(source.match(/^LangString /gmu)).toHaveLength(locales.reduce((count, locale) => count + Object.keys(locale.strings).length, 0))
const japanese = locales.filter(locale => locale.id === 'ja_JP')
expect(renderInstallerStrings(japanese)).not.toContain('${LANG_ENGLISH}')
})
@@ -3,22 +3,43 @@ import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
import { expect, it } from 'vitest'
import { directoryInstallerExits, directoryInstallSection, directoryUninstaller } from '../scripts/windows-directory-installer.mjs'
import { directoryInstallerExits, directoryInstallSection, directoryInstallUtil, directoryUninstaller } from '../scripts/windows-directory-installer.mjs'
const require = createRequire(import.meta.url)
const section = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')),
'templates/nsis/installSection.nsh'), 'utf8')
it('retains data without preserving obsolete registrations when uninstalling another directory', () => {
const source = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')), 'templates/nsis/include/installUtil.nsh'), 'utf8')
const adapted = directoryInstallUtil(source)
expect(adapted).toContain('${if} $installationDir == $INSTDIR\n StrCpy $0 "$0 --updated"\n ${endif}')
expect(adapted).toContain('"$uninstallerFileNameTemp" /S /KEEP_APP_DATA $0 _?=$installationDir')
expect(adapted).toContain('"$uninstallerFileName" /S /KEEP_APP_DATA $0 _?=$installationDir')
expect(directoryInstallUtil(source.replaceAll('\n', '\r\n'))).toBe(adapted)
expect(() => directoryInstallUtil(source.replace('StrCpy $0 "$0 --updated"', ''))).toThrow('template changed')
expect(() => directoryInstallUtil(source + source)).toThrow('template changed')
})
it('keeps data cleanup out of the upstream template while retaining application removal and registration cleanup', () => {
const source = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')), 'templates/nsis/uninstaller.nsh'), 'utf8')
const adapted = directoryUninstaller(source)
expect(adapted).not.toContain('--delete-app-data')
expect(adapted).toContain('Goto dshUninstallFinished')
expect(adapted.indexOf('Goto dshUninstallFinished')).toBeLessThan(adapted.indexOf('WinShell::UninstAppUserModelId'))
expect(adapted).toContain('Call un.FinishCleanup')
expect(adapted).toContain('UninstallNote')
expect(adapted).not.toContain('RMDir /r "$APPDATA')
expect(adapted).toContain('!insertmacro customUnInstall')
expect(adapted.indexOf('!insertmacro customUnInstall')).toBeLessThan(adapted.indexOf('DeleteRegKey SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}"'))
expect(adapted).toContain('DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"')
expect(adapted).toContain('DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY_2}"')
expect(directoryUninstaller(source.replaceAll('\n', '\r\n'))).toBe(adapted)
expect(adapted).toContain('RMDir /r "\\\\?\\$INSTDIR"')
expect(adapted).toContain('Rename "\\\\?\\$INSTDIR$R0\\$R2" "\\\\?\\$PLUGINSDIR\\old-install$R0\\$R2"')
expect(adapted).toContain('Rename "\\\\?\\$PLUGINSDIR\\old-install$R0\\$R2" "\\\\?\\$INSTDIR$R0\\$R2"')
expect(adapted).not.toContain('"$INSTDIR$R0')
expect(adapted).not.toContain('"$PLUGINSDIR\\old-install')
expect(() => directoryUninstaller(source.replace(' # delete the installed files\n', ''))).toThrow('template changed')
expect(() => directoryUninstaller(source.replace(' Var /GLOBAL isDeleteAppData\n', ''))).toThrow('template changed')
expect(() => directoryUninstaller(source.replace(' DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"', ''))).toThrow('template changed')
})
@@ -0,0 +1,49 @@
<# Exercise timeout cleanup with a real child that would otherwise outlive setup. #>
[CmdletBinding()]
param([Parameter(Mandatory)][string]$OutputDirectory)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'windows-installer-process.ps1')
$fixtureBase = [IO.Path]::GetFullPath($OutputDirectory).TrimEnd('\')
$root = Join-Path $fixtureBase ('process-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $root | Out-Null
$ready = Join-Path $root 'child.pid'
$marker = Join-Path $root 'late-write.txt'
$parent = $null
$child = $null
try {
foreach ($exitCode in @(0, 7)) {
$fixture = Start-Process powershell.exe -ArgumentList "-NoProfile -Command exit $exitCode" -WindowStyle Hidden -PassThru
$failure = $null
try { Wait-InstallerProcess $fixture } catch { $failure = $_.Exception.Message } finally { $fixture.Dispose() }
if ($exitCode -eq 0 -and $failure) { throw $failure }
if ($exitCode -eq 7 -and $failure -ne 'Setup failed: 7') { throw "Lost setup exit status: $failure" }
}
$childCode = "Start-Sleep -Seconds 60; [IO.File]::WriteAllText('$($marker.Replace("'", "''"))', 'unexpected')"
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($childCode))
$readyLiteral = $ready.Replace("'", "''")
$parentCode = "`$child = Start-Process powershell.exe -ArgumentList '-NoProfile -EncodedCommand $encoded' -WindowStyle Hidden -PassThru; [IO.File]::WriteAllText('$readyLiteral.tmp', [string]`$child.Id); [IO.File]::Move('$readyLiteral.tmp', '$readyLiteral'); `$child.WaitForExit()"
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($parentCode))
$parent = Start-Process powershell.exe -ArgumentList "-NoProfile -EncodedCommand $encoded" -WindowStyle Hidden -PassThru
$timer = [Diagnostics.Stopwatch]::StartNew()
while (-not (Test-Path -LiteralPath $ready)) {
if ($parent.HasExited -or $timer.Elapsed.TotalSeconds -gt 30) { throw 'Process fixture did not become ready' }
Start-Sleep -Milliseconds 25
}
$child = [Diagnostics.Process]::GetProcessById([int][IO.File]::ReadAllText($ready))
# Observe termination through an independently opened process handle.
$observedParent = [Diagnostics.Process]::GetProcessById($parent.Id)
try {
$failure = $null
try { Wait-InstallerProcess $parent -TimeoutMilliseconds 100 } catch { $failure = $_.Exception.Message }
if ($failure -ne 'Setup timed out') { throw "Unexpected timeout result: $failure" }
if (-not $observedParent.WaitForExit(10000) -or -not $child.WaitForExit(10000)) { throw 'Timed-out setup left a live process' }
if (Test-Path -LiteralPath $marker) { throw 'Timed-out setup continued writing' }
} finally { $observedParent.Dispose() }
Write-Output 'passed: setup success, failure, timeout and child termination'
} finally {
foreach ($fixture in @($parent, $child)) {
if ($fixture) { Stop-InstallerProcess $fixture; $fixture.Dispose() }
}
if ([IO.Path]::GetDirectoryName($root) -ne $fixtureBase) { throw 'Unexpected process fixture cleanup path' }
Remove-Item -LiteralPath $root -Recurse -Force
}
@@ -0,0 +1,22 @@
<# Reap timed-out fixture processes before their registry and filesystem cleanup. #>
function Stop-InstallerProcess([Diagnostics.Process]$Process) {
if ($Process.HasExited) { return }
$previousPreference = $ErrorActionPreference
try {
# A process can exit between HasExited and taskkill; inspect that race after capturing stderr.
$ErrorActionPreference = 'Continue'
$termination = & "$env:SystemRoot\System32\taskkill.exe" /PID $Process.Id /T /F 2>&1
$terminationCode = $LASTEXITCODE
} finally { $ErrorActionPreference = $previousPreference }
if ($terminationCode -ne 0 -and -not $Process.HasExited) { throw "Cannot terminate fixture process $($Process.Id): $termination" }
if (-not $Process.WaitForExit(30000)) { throw "Fixture process $($Process.Id) remained after termination" }
}
function Wait-InstallerProcess([Diagnostics.Process]$Process, [int]$TimeoutMilliseconds = 30000) {
try {
if (-not $Process.WaitForExit($TimeoutMilliseconds)) { throw 'Setup timed out' }
if ($Process.ExitCode -ne 0) { throw "Setup failed: $($Process.ExitCode)" }
} finally {
Stop-InstallerProcess $Process
}
}
@@ -65,6 +65,26 @@ public static class InstallerCapture {
return incomplete;
}
[DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW")] static extern IntPtr ReadControlText(IntPtr window, uint message, IntPtr count, StringBuilder text);
public static string ControlText(IntPtr window) {
var text = new StringBuilder(32768);
ReadControlText(window, 0xD, new IntPtr(text.Capacity), text);
return text.ToString();
}
public static IntPtr FindWindowTitle(int process, string expected) {
IntPtr result = IntPtr.Zero;
EnumWindows(delegate(IntPtr window, IntPtr data) {
uint owner;
GetWindowThreadProcessId(window, out owner);
var title = new StringBuilder(256);
GetWindowText(window, title, title.Capacity);
if (owner == process && IsWindowVisible(window) && title.ToString() == expected) result = window;
return result == IntPtr.Zero;
}, IntPtr.Zero);
return result;
}
public static IntPtr FindClass(IntPtr parent, string name) {
IntPtr result = IntPtr.Zero;
EnumChildWindows(parent, delegate(IntPtr child, IntPtr unused) {
@@ -6,6 +6,13 @@
#include <cassert>
#include "../installer/uninstall-data.h"
extern "C" __declspec(dllimport) void* __cdecl UninstallBegin(LPCWSTR);
extern "C" __declspec(dllimport) DWORD __cdecl UninstallPrepare(void*, LPCWSTR, LPCWSTR);
extern "C" __declspec(dllimport) DWORD __cdecl UninstallPayload(void*, LPCWSTR, LPCWSTR, LPCWSTR);
extern "C" __declspec(dllimport) int __cdecl UninstallFinish(void*, LPCWSTR, LPCWSTR);
extern "C" __declspec(dllimport) void __cdecl UninstallPersist(void*);
static void File(const std::wstring& path, DWORD attributes = FILE_ATTRIBUTE_NORMAL) {
HANDLE file = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, attributes, nullptr);
assert(file != INVALID_HANDLE_VALUE);
@@ -46,8 +53,18 @@ int wmain(int argc, wchar_t** argv) {
assert(uninstall_data::Remove(cache.c_str(), installation.c_str(), data.c_str()) == ERROR_ACCESS_DENIED);
assert(uninstall_data::Remove(data.c_str(), installation.c_str(), cache.c_str()) == ERROR_ACCESS_DENIED);
assert(uninstall_data::Remove(cache.c_str(), installation.c_str(), L"relative\\home") == ERROR_INVALID_NAME);
std::wstring slashHome = cache;
for (auto& character : slashHome) if (character == L'\\') character = L'/';
assert(uninstall_data::Remove(data.c_str(), installation.c_str(), slashHome.c_str()) == ERROR_ACCESS_DENIED);
assert(Exists(cache + L"\\CURRENT"));
// Unsupported protection roots stop before deleting any contents, even if they name a shared descendant.
for (auto home : {L"\\\\server\\share", L"\\\\server\\share\\home", L"\\\\?\\UNC\\server\\share"}) {
assert(uninstall_data::Remove(data.c_str(), installation.c_str(), home) == ERROR_INVALID_NAME);
assert(Exists(cache + L"\\CURRENT"));
assert(Exists(data + L"\\Local State"));
}
// A pinned directory cannot be renamed or replaced while the helper holds it.
{
uninstall_data::Handles pinned;
@@ -86,6 +103,81 @@ int wmain(int argc, wchar_t** argv) {
// A protected root elsewhere does not block removal.
assert(uninstall_data::Remove(data.c_str(), installation.c_str(), (root + L"\\elsewhere").c_str()) == ERROR_SUCCESS);
assert(!Exists(data));
// Exercise the shipped helper: a busy executable keeps the retry entry; auxiliary residue is reportable.
const std::wstring report = root + L"\\report.txt";
void* session = UninstallBegin(report.c_str());
assert(session);
assert(UninstallPrepare(session, installation.c_str(), nullptr) == ERROR_SUCCESS);
File(installation + L"\\app.exe");
File(installation + L"\\uninstall.exe");
File(installation + L"\\aux.log");
HANDLE mainFile = CreateFileW((installation + L"\\app.exe").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
assert(mainFile != INVALID_HANDLE_VALUE);
assert(UninstallPayload(session, installation.c_str(), L"app.exe", L"uninstall.exe") == 1);
assert(Exists(installation + L"\\uninstall.exe"));
assert(Exists(installation + L"\\aux.log"));
CloseHandle(mainFile);
HANDLE auxiliary = CreateFileW((installation + L"\\aux.log").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
assert(auxiliary != INVALID_HANDLE_VALUE);
assert(UninstallPayload(session, installation.c_str(), L"app.exe", L"uninstall.exe") == 0);
assert(!Exists(installation + L"\\app.exe"));
assert(UninstallFinish(session, installation.c_str(), L"uninstall.exe") == 1);
assert(!Exists(installation + L"\\uninstall.exe"));
assert(Exists(installation + L"\\aux.log"));
HANDLE reportFile = CreateFileW(report.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
assert(reportFile != INVALID_HANDLE_VALUE);
char contents[16384]{};
DWORD length;
assert(ReadFile(reportFile, contents, sizeof(contents) - 1, &length, nullptr));
CloseHandle(reportFile);
assert(strstr(contents, "aux.log"));
assert(strstr(contents, "32"));
CloseHandle(auxiliary);
assert(DeleteFileW((installation + L"\\aux.log").c_str()));
assert(DeleteFileW(report.c_str()));
assert(RemoveDirectoryW(installation.c_str()));
for (auto home : {L"C:/HarnessHome", L"~/.dsh", L"~\\.dsh", L" \t "}) {
assert(CreateDirectoryW(installation.c_str(), nullptr));
void* alternate = UninstallBegin(report.c_str());
assert(alternate);
assert(UninstallPrepare(alternate, installation.c_str(), home) == ERROR_SUCCESS);
assert(UninstallFinish(alternate, installation.c_str(), L"uninstall.exe") == 0);
assert(!Exists(installation));
}
assert(CreateDirectoryW(installation.c_str(), nullptr));
void* protectedSession = UninstallBegin(report.c_str());
std::wstring slashInstall = installation;
for (auto& character : slashInstall) if (character == L'\\') character = L'/';
assert(UninstallPrepare(protectedSession, installation.c_str(), slashInstall.c_str()) == ERROR_ACCESS_DENIED);
assert(UninstallPrepare(protectedSession, installation.c_str(), L"relative/home") == ERROR_INVALID_NAME);
UninstallPersist(protectedSession);
reportFile = CreateFileW(report.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
assert(reportFile != INVALID_HANDLE_VALUE);
ZeroMemory(contents, sizeof(contents));
assert(ReadFile(reportFile, contents, sizeof(contents) - 1, &length, nullptr));
CloseHandle(reportFile);
assert(strstr(contents, "Validate DSH_HOME"));
assert(strstr(contents, "relative/home"));
assert(DeleteFileW(report.c_str()));
assert(RemoveDirectoryW(installation.c_str()));
std::vector<std::wstring> longDirectories;
std::wstring longDirectory = root;
while (longDirectory.size() < 280) {
longDirectory += L"\\" + std::wstring(60, L'x');
assert(CreateDirectoryW((L"\\\\?\\" + longDirectory).c_str(), nullptr));
longDirectories.push_back(longDirectory);
}
const std::wstring longUninstaller = L"\\\\?\\" + longDirectory + L"\\uninstall.exe";
File(longUninstaller);
void* longSession = UninstallBegin(report.c_str());
assert(UninstallPrepare(longSession, longDirectory.c_str(), nullptr) == ERROR_SUCCESS);
assert(UninstallFinish(longSession, longDirectory.c_str(), L"uninstall.exe") == 0);
assert(!Exists(longUninstaller));
assert(!Exists(L"\\\\?\\" + longDirectory));
longDirectories.pop_back();
for (auto it = longDirectories.rbegin(); it != longDirectories.rend(); ++it)
assert(RemoveDirectoryW((L"\\\\?\\" + *it).c_str()));
assert(RemoveDirectoryW(root.c_str()));
}
+285 -13
View File
@@ -1,4 +1,4 @@
<# Production uninstaller checks with isolated application identity and seeded data. #>
<# Production uninstaller checks with isolated application identity and seeded data. #>
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Installer, [Parameter(Mandatory)][string]$ProductName,
[Parameter(Mandatory)][string]$RegistryKey, [Parameter(Mandatory)][string]$OutputDirectory,
@@ -7,6 +7,7 @@ $ErrorActionPreference = 'Stop'
$copy = (Get-Content (Join-Path $PSScriptRoot "../installer/locales/$Language.json") -Encoding UTF8 -Raw | ConvertFrom-Json).uninstaller
$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
. (Join-Path $PSScriptRoot 'windows-installer-ui.ps1')
. (Join-Path $PSScriptRoot 'windows-installer-process.ps1')
[InstallerCapture]::Initialize()
$expected = Get-Content (Join-Path $PSScriptRoot 'expected/windows-uninstall.json') -Raw | ConvertFrom-Json
$roaming = [Environment]::GetFolderPath('ApplicationData')
@@ -20,7 +21,14 @@ $scopePath = Join-Path $roaming $PackageName.Split('/')[0]
$userDataPath = Join-Path $roaming ($PackageName -replace '/', '\')
$cachePath = Join-Path $local (($PackageName -replace '[/\\?<>:*|"]', '').ToLowerInvariant() + '-updater')
$uninstaller = Join-Path $OutputDirectory 'uninstall-copy.exe'
$environmentKey = "Software\DSHUninstallTests\$RegistryKey\CommandEnvironment"
$ownerKey = "Software\DSHUninstallTests\$RegistryKey\CommandOwner"
$protocolKey = "Software\Classes\dsh-test-$RegistryKey"
$process = $null
$setup = $null
$held = $null
$originalHome = [Environment]::GetEnvironmentVariable('DSH_HOME', 'Process')
$strings = (Get-Content (Join-Path $PSScriptRoot "../installer/locales/$Language.json") -Encoding UTF8 -Raw | ConvertFrom-Json).strings
function Wait-Text([string]$Text) {
$timer = [Diagnostics.Stopwatch]::StartNew()
do {
@@ -46,12 +54,14 @@ function Wait-Exit {
try {
foreach ($mode in $expected.cases) {
$setup = Start-Process -FilePath $Installer -ArgumentList ('/S /D=' + $installPath) -PassThru -WindowStyle Hidden
try {
if (-not $setup.WaitForExit(30000)) { $setup.Kill(); $setup.WaitForExit(); throw 'Setup timed out' }
if ($setup.ExitCode -ne 0) { throw "Setup failed: $($setup.ExitCode)" }
} finally { $setup.Dispose() }
Wait-InstallerProcess $setup
$setup.Dispose(); $setup = $null
$entry = Get-ItemProperty ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey)
if ($entry.InstallLocation.TrimEnd('\') -ne $installPath) { throw 'Uninstall entry lacks InstallLocation' }
$deepAsset = Join-Path $installPath (('nested-' * 20) + '\' + ('asset-' * 15) + '.txt')
if ($deepAsset.Length -le 260) { throw 'Uninstall fixture must exceed MAX_PATH' }
[IO.Directory]::CreateDirectory('\\?\' + [IO.Path]::GetDirectoryName($deepAsset)) | Out-Null
[IO.File]::WriteAllText(('\\?\' + $deepAsset), 'long path payload')
foreach ($path in @($homePath, $productDataPath, $userDataPath, $cachePath, $externalPath)) { New-Item -ItemType Directory -Force -Path $path | Out-Null }
[IO.File]::WriteAllText((Join-Path $externalPath 'keep.txt'), 'outside data root')
if (-not (Test-Path -LiteralPath (Join-Path $userDataPath 'linked-project'))) {
@@ -62,38 +72,300 @@ try {
[IO.File]::WriteAllText((Join-Path $userDataPath 'Local State'), 'chromium profile')
[IO.File]::WriteAllText((Join-Path $cachePath 'download.txt'), 'update')
Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force
$missingLocation = $mode -in @('missing-location', 'missing-location-short', 'missing-location-foreign')
$foreign = $mode -eq 'missing-location-foreign'
if ($missingLocation) { Remove-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation }
$arpKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey
if ($mode -eq 'missing-location') {
$originalCommand = (Get-ItemProperty $arpKey).UninstallString
$alternateCommand = $originalCommand.Replace($installPath + '\', $installPath + '\.\')
if ($alternateCommand -ceq $originalCommand -or -not $alternateCommand.Contains($installPath + '\.\')) { throw 'Equivalent-path fixture did not rewrite the uninstall command' }
Set-ItemProperty $arpKey UninstallString $alternateCommand
}
if ($mode -eq 'missing-location-short') {
$uninstallFile = Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')
$shortFile = (New-Object -ComObject Scripting.FileSystemObject).GetFile($uninstallFile).ShortPath
if ($shortFile -ceq $uninstallFile) { throw 'Short-name fixture has no alternate name' }
Set-ItemProperty $arpKey UninstallString ('"' + $shortFile + '" /currentuser')
}
$desktopLink = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) ($ProductName + '.lnk')
$startLink = Join-Path ([Environment]::GetFolderPath('Programs')) ($ProductName + '.lnk')
if ($missingLocation) {
if (-not (Test-Path -LiteralPath $startLink) -or (New-Object -ComObject WScript.Shell).CreateShortcut($startLink).TargetPath -ne (Join-Path $installPath ($ProductName + '.exe'))) { throw 'Missing A Start menu fixture' }
$shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($desktopLink)
$shortcut.TargetPath = Join-Path $installPath ($ProductName + '.exe')
$shortcut.Save()
if (-not (Test-Path -LiteralPath $desktopLink) -or -not (Test-Path -LiteralPath $arpKey)) { throw 'Missing A uninstall fixtures' }
}
$integrationRoot = if ($foreign) { $externalPath } else { $installPath }
$commandDirectory = Join-Path $integrationRoot 'resources\runtime\cli\bin'
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($environmentKey)
try { $key.SetValue('Path', $commandDirectory + ';C:\Windows', [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Dispose() }
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ownerKey)
try { $key.SetValue('Directory', $commandDirectory); $key.SetValue('RetainedEntries', 0) } finally { $key.Dispose() }
if ($mode -eq 'unowned') {
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($ownerKey, $true)
try { $key.DeleteValue('Directory'); $key.DeleteValue('RetainedEntries') } finally { $key.Dispose() }
}
if ($mode -eq 'owned-retained') {
Set-ItemProperty -LiteralPath ('HKCU:\' + $ownerKey) -Name RetainedEntries -Value 1
Set-ItemProperty -LiteralPath ('HKCU:\' + $environmentKey) -Name Path -Value ($commandDirectory + ';' + $commandDirectory + ';C:\Windows')
}
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command')
try { $key.SetValue('', '"' + (Join-Path $integrationRoot ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() }
$launchUninstaller = $uninstaller
$arguments = '_?=' + $installPath
if ($mode -in @('silent', 'home-inside')) { $arguments = '/S ' + $arguments }
if ($mode -in @('silent', 'missing-location', 'missing-location-short', 'missing-location-foreign', 'unowned', 'owned-retained', 'home-inside', 'home-slash', 'home-tilde', 'home-slash-inside', 'registration-error', 'main-locked', 'auxiliary-locked', 'unsafe-root')) { $arguments = '/S ' + $arguments }
# electron-builder's installUtil.nsh runs an older uninstaller with exactly these flags when replacing it.
if ($mode -eq 'upgrade') { $arguments = '/S /KEEP_APP_DATA --updated /currentuser ' + $arguments }
if ($mode -eq 'upgrade') {
Set-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation -Value ($installPath + '\')
$arguments = '/S /KEEP_APP_DATA --updated /currentuser ' + $arguments }
if ($mode -eq 'replaced') { $arguments = '/S /KEEP_APP_DATA /currentuser ' + $arguments }
if ($mode -eq 'self-copy') {
$launchUninstaller = Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')
$arguments = '/S /KEEP_APP_DATA'
}
if ($mode -eq 'home-inside') { $env:DSH_HOME = Join-Path $userDataPath 'home' } else { Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue }
$process = Start-Process -FilePath $uninstaller -ArgumentList $arguments -PassThru -WindowStyle ($(if ($mode -eq 'interactive') { 'Normal' } else { 'Hidden' }))
if ($mode -eq 'interactive') {
if ($mode -eq 'home-slash') { $env:DSH_HOME = $homePath.Replace('\', '/') }
if ($mode -eq 'home-tilde') {
if (-not $homePath.StartsWith($env:USERPROFILE + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Tilde fixture must be inside USERPROFILE' }
$env:DSH_HOME = '~/' + $homePath.Substring($env:USERPROFILE.Length + 1).Replace('\', '/')
}
if ($mode -eq 'home-slash-inside') { $env:DSH_HOME = (Join-Path $userDataPath 'home').Replace('\', '/') }
if ($mode -in @('registration-error', 'save-report')) {
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true)
try { $key.SetValue('Path', 42, [Microsoft.Win32.RegistryValueKind]::DWord) } finally { $key.Dispose() }
}
if ($mode -eq 'auxiliary-locked') {
$residual = Join-Path $installPath 'held-log.txt'
[IO.File]::WriteAllText($residual, 'held auxiliary data')
$held = [IO.File]::Open($residual, 'Open', 'Read', 'Read')
}
if ($mode -eq 'unsafe-root') {
$linked = Join-Path $OutputDirectory 'Linked Install'
New-Item -ItemType Junction -Path $linked -Target $externalPath | Out-Null
$process = Start-Process -FilePath $launchUninstaller -ArgumentList ('/S _?=' + $linked) -PassThru -WindowStyle Hidden
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Linked root was not rejected' }
if (-not (Test-Path -LiteralPath (Join-Path $externalPath 'keep.txt'))) { throw 'Unsafe root deleted external files' }
$report = Get-Content (Join-Path $env:TEMP ('DeepSeek-Harness-uninstall-' + $process.Id + '.txt')) -Raw
if (-not $report.Contains('no deletion started')) { throw 'Unsafe scope missing from report' }
$process.Dispose(); $process = $null
[IO.Directory]::Delete($linked)
}
if ($mode -eq 'main-locked') {
$held = [IO.File]::Open((Join-Path $installPath ($ProductName + '.exe')), 'Open', 'Read', 'Read')
}
$process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle ($(if ($mode -in @('interactive','save-report')) { 'Normal' } else { 'Hidden' }))
if ($mode -in @('interactive','save-report')) {
$welcomeText = $copy.welcome
$welcome = Wait-Text $welcomeText
$window = [InstallerCapture]::TopLevel($welcome)
[void][InstallerCapture]::SaveNative($window, (Join-Path $OutputDirectory 'uninstall-welcome.png'), $false)
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
if ($mode -eq 'save-report') {
$save = Wait-Text $strings.INSTALLER_UNINSTALL_SAVE
$dialog = [InstallerCapture]::TopLevel($save)
[void][InstallerCapture]::SaveNative($dialog, (Join-Path $OutputDirectory 'uninstall-residual.png'), $false)
[InstallerCapture]::Click($save)
$timer = [Diagnostics.Stopwatch]::StartNew()
do {
$picker = [InstallerCapture]::FindWindowTitle($process.Id, $strings.INSTALLER_UNINSTALL_SAVE)
if ($timer.Elapsed.TotalSeconds -gt 20) { throw 'Save file picker did not appear' }
Start-Sleep -Milliseconds 25
} while ($picker -eq [IntPtr]::Zero)
$filename = [InstallerCapture]::FindClass($picker, 'Edit')
if ($filename -eq [IntPtr]::Zero) { throw 'Save filename control missing' }
$savedReport = Join-Path $OutputDirectory ('saved-report-' + [Guid]::NewGuid().ToString('N') + '.txt')
while ([InstallerCapture]::ControlText($filename) -ne 'DeepSeek-Harness-uninstall-report.txt') {
if ($timer.Elapsed.TotalSeconds -gt 20) { throw 'Save filename initialization did not finish' }
Start-Sleep -Milliseconds 25
}
[void][InstallerCapture]::SendMessage($filename, 0xC, [IntPtr]::Zero, $savedReport)
if ([InstallerCapture]::ControlText($filename) -ne $savedReport) { throw 'Save filename was not set' }
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($picker, 1))
# The native picker briefly creates a probe file; the returning report dialog signals the real write is finished.
$save = Wait-Text $strings.INSTALLER_UNINSTALL_SAVE
$timer = [Diagnostics.Stopwatch]::StartNew()
while (-not (Test-Path -LiteralPath $savedReport)) {
if ($timer.Elapsed.TotalSeconds -gt 20) { throw "Save report did not create file: $([InstallerCapture]::VisibleText($process.Id))" }
Start-Sleep -Milliseconds 50
}
if (-not ([IO.File]::ReadAllText($savedReport).Contains($environmentKey))) { throw 'Saved report omitted registry key' }
[void][InstallerCapture]::PostMessage([InstallerCapture]::TopLevel($save), 0x10, [IntPtr]::Zero, [IntPtr]::Zero)
}
$finishedText = $copy.finished
[void](Wait-Text $finishedText)
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
}
if ($mode -eq 'main-locked') {
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Locked main executable did not stop uninstall' }
$report = Get-Content (Join-Path $env:TEMP ("DeepSeek-Harness-uninstall-" + $process.Id + '.txt')) -Raw
if (-not $report.Contains($ProductName + '.exe') -or -not $report.Contains('32')) { throw 'Locked executable missing from report' }
if (-not (Test-Path -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')))) { throw 'Retry uninstaller was removed' }
if (-not (Test-Path -LiteralPath ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey))) { throw 'Retry uninstall entry was removed' }
$held.Dispose(); $held = $null
$process.Dispose(); $process = $null
$process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle Hidden
}
if ($mode -eq 'registration-error') {
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 0) { throw 'Registration failure blocked uninstall' }
$report = Get-Content (Join-Path $env:TEMP ("DeepSeek-Harness-uninstall-" + $process.Id + '.txt')) -Raw
if (-not $report.Contains($environmentKey) -or -not $report.Contains('[Path]')) { throw 'Registry residual missing from report' }
}
if ($mode -eq 'auxiliary-locked') {
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 0) { throw 'Auxiliary failure blocked uninstall' }
if (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe'))) { throw 'Auxiliary failure retained main executable' }
$report = Get-Content (Join-Path $env:TEMP ('DeepSeek-Harness-uninstall-' + $process.Id + '.txt')) -Raw
if (-not $report.Contains('held-log.txt')) { throw 'Auxiliary file missing from report' }
$held.Dispose(); $held = $null
Remove-Item -LiteralPath $residual
[IO.Directory]::Delete($installPath)
}
Wait-Exit
$retained = $mode -in @('upgrade', 'replaced')
$retained = $missingLocation -or $mode -in @('upgrade', 'replaced', 'self-copy')
# A DSH_HOME inside the Electron directory protects that directory (and its scope) but not the other roots.
$userDataRetained = $retained -or $mode -eq 'home-inside'
$userDataRetained = $retained -or $mode -in @('home-inside', 'home-slash-inside')
if ([IO.File]::ReadAllText((Join-Path $externalPath 'keep.txt')) -ne 'outside data root') { throw 'Cleanup followed a junction into a project' }
if (-not (Test-Path (Join-Path $homePath 'session.txt'))) { throw "Harness home retention failed: $mode" }
if ((Test-Path (Join-Path $productDataPath 'state.txt')) -ne $retained) { throw "Product data retention failed: $mode" }
if ((Test-Path (Join-Path $userDataPath 'Local State')) -ne $userDataRetained) { throw "Electron user data retention failed: $mode" }
if ((Test-Path -LiteralPath $scopePath) -ne $userDataRetained) { throw "Package scope directory retention failed: $mode" }
if ((Test-Path (Join-Path $cachePath 'download.txt')) -ne $retained) { throw "Update cache retention failed: $mode" }
$integrationsRetained = $foreign -or $mode -in @('upgrade', 'registration-error', 'save-report')
$owner = Get-ItemProperty -LiteralPath ('HKCU:\' + $ownerKey)
if ([bool]$owner.Directory -ne $integrationsRetained) { throw "Command ownership cleanup failed: $mode" }
$path = (Get-ItemProperty -LiteralPath ('HKCU:\' + $environmentKey)).Path
$pathRetained = $integrationsRetained -or $mode -eq 'owned-retained'
if ($mode -notin @('registration-error', 'save-report') -and ($path.Contains($commandDirectory) -ne $pathRetained -or -not $path.Contains('C:\Windows'))) { throw "PATH cleanup failed: $mode" }
if ($mode -eq 'owned-retained' -and $path -ne ($commandDirectory + ';C:\Windows')) { throw 'Owned cleanup removed a pre-existing manual PATH entry' }
if ((Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) -ne ($foreign -or $mode -eq 'upgrade')) { throw "Protocol cleanup failed: $mode" }
if ($missingLocation -and ((Test-Path -LiteralPath $desktopLink) -or (Test-Path -LiteralPath $startLink) -or (Test-Path -LiteralPath $arpKey))) { throw 'Missing location left an A shortcut or uninstall entry' }
Write-Output "passed: $mode"
}
# Real replacement publishes B after the old A uninstaller has been retained.
$setup = Start-Process $Installer -ArgumentList ('/S /D=' + $installPath) -PassThru -WindowStyle Hidden
Wait-InstallerProcess $setup
$setup.Dispose(); $setup = $null
Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force
$oldCommand = Join-Path $installPath 'resources\runtime\cli\bin'
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ownerKey)
try { $key.SetValue('Directory', $oldCommand); $key.SetValue('RetainedEntries', 0) } finally { $key.Dispose() }
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($environmentKey)
try { $key.SetValue('Path', $oldCommand + ';C:\Windows') } finally { $key.Dispose() }
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command')
try { $key.SetValue('', '"' + (Join-Path $installPath ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() }
New-Item -ItemType Directory -Force -Path $userDataPath | Out-Null
$relocationData = Join-Path $userDataPath 'relocation-state.txt'
[IO.File]::WriteAllText($relocationData, 'retained during relocation')
$newPath = Join-Path $OutputDirectory 'Replacement App'
$env:DSH_HOME = $homePath.Replace('\', '/')
$setup = Start-Process $Installer -ArgumentList ('/S /D=' + $newPath) -PassThru -WindowStyle Hidden
Wait-InstallerProcess $setup
$setup.Dispose(); $setup = $null
if ((Get-ItemProperty ('HKCU:\' + $ownerKey)).Directory) { throw 'Relocation retained old command owner' }
if ((Get-ItemProperty ('HKCU:\' + $environmentKey)).Path -ne 'C:\Windows') { throw 'Relocation retained old command PATH' }
if (Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) { throw 'Relocation retained old protocol' }
if ([IO.File]::ReadAllText($relocationData) -ne 'retained during relocation') { throw 'Relocation removed user data' }
$newCommand = Join-Path $newPath 'resources\runtime\cli\bin'
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ownerKey)
try { $key.SetValue('Directory', $newCommand) } finally { $key.Dispose() }
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($environmentKey)
try { $key.SetValue('Path', $newCommand + ';C:\Windows') } finally { $key.Dispose() }
$newProtocol = '"' + (Join-Path $newPath ($ProductName + '.exe')) + '" "%1"'
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command')
try { $key.SetValue('', $newProtocol) } finally { $key.Dispose() }
$process = Start-Process $uninstaller -ArgumentList ('/S /currentuser _?=' + $installPath) -PassThru -WindowStyle Hidden
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Stale uninstaller was not rejected' }
$process.Dispose(); $process = $null
if (-not (Test-Path -LiteralPath (Join-Path $newPath ($ProductName + '.exe')))) { throw 'Stale uninstaller deleted B' }
$entry = Get-ItemProperty ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey)
if ($entry.InstallLocation.TrimEnd('\') -ne $newPath) { throw 'Stale uninstaller removed B registration' }
if ((Get-ItemProperty ('HKCU:\' + $ownerKey)).Directory -ne $newCommand) { throw 'Stale uninstaller changed B command owner' }
if ((Get-ItemProperty ('HKCU:\' + $environmentKey)).Path -ne ($newCommand + ';C:\Windows')) { throw 'Stale uninstaller changed B PATH' }
if ((Get-Item ('HKCU:\' + $protocolKey + '\shell\open\command')).GetValue('') -ne $newProtocol) { throw 'Stale uninstaller changed B protocol' }
New-Item -ItemType Directory -Force -Path $userDataPath | Out-Null
$replacementData = Join-Path $userDataPath 'replacement-state.txt'
[IO.File]::WriteAllText($replacementData, 'replacement installation data')
$replacementLinks = @{}
foreach ($folder in @([Environment]::GetFolderPath('DesktopDirectory'), [Environment]::GetFolderPath('Programs'))) {
$link = Join-Path $folder ($ProductName + '.lnk')
if (Test-Path -LiteralPath $link) { $replacementLinks[$link] = [Convert]::ToBase64String([IO.File]::ReadAllBytes($link)) }
}
# Keep B's uninstall entry and protocol while the desktop shortcut and CLI still belong to A.
$replacementLinks.Remove($desktopLink)
$shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($desktopLink)
$shortcut.TargetPath = Join-Path $installPath ($ProductName + '.exe')
$shortcut.Save()
Set-ItemProperty ('HKCU:\' + $ownerKey) Directory $oldCommand
Set-ItemProperty ('HKCU:\' + $environmentKey) Path ($oldCommand + ';C:\Windows')
$bUninstall = $entry.UninstallString
New-Item -ItemType Directory -Force -Path $installPath | Out-Null
Get-ChildItem -LiteralPath $newPath | Copy-Item -Destination $installPath -Recurse
if (-not (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe')))) { throw 'Partial takeover fixture lacks the A executable' }
$process = Start-Process $uninstaller -ArgumentList ('/S /currentuser _?=' + $installPath) -PassThru -WindowStyle Hidden
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Existing stale directory was not rejected' }
$report = Get-Content (Join-Path $env:TEMP ('DeepSeek-Harness-uninstall-' + $process.Id + '.txt')) -Raw
if (-not $report.Contains('Removal not confirmed') -or -not $report.Contains($newPath) -or -not $report.Contains($installPath)) { throw 'Silent rejection report lacks reason and both paths' }
$process.Dispose(); $process = $null
$process = Start-Process $uninstaller -ArgumentList ('/currentuser _?=' + $installPath) -PassThru
$welcome = Wait-Text $copy.welcome
$window = [InstallerCapture]::TopLevel($welcome)
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
$continue = Wait-Text $strings.INSTALLER_UNINSTALL_CONTINUE
# TaskDialog common buttons are nested DirectUI controls; use TDM_CLICK_BUTTON with IDCANCEL.
if (-not [InstallerCapture]::PostMessage([InstallerCapture]::TopLevel($continue), 0x466, [IntPtr]2, [IntPtr]::Zero)) { throw 'Could not cancel owner dialog' }
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Owner dialog cancellation did not stop uninstall' }
$report = Get-Content (Join-Path $env:TEMP ('DeepSeek-Harness-uninstall-' + $process.Id + '.txt')) -Raw
if (-not $report.Contains('Removal not confirmed') -or -not $report.Contains($newPath) -or -not $report.Contains($installPath)) { throw 'Cancellation report lacks reason and both paths' }
if (-not (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe')))) { throw 'Cancellation deleted A' }
$process.Dispose(); $process = $null
$process = Start-Process $uninstaller -ArgumentList ('/currentuser _?=' + $installPath) -PassThru
$welcome = Wait-Text $copy.welcome
$window = [InstallerCapture]::TopLevel($welcome)
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
$continue = Wait-Text $strings.INSTALLER_UNINSTALL_CONTINUE
[void][InstallerCapture]::SaveNative([InstallerCapture]::TopLevel($continue), (Join-Path $OutputDirectory 'uninstall-directory-only.png'), $false)
[InstallerCapture]::Click($continue)
[void](Wait-Text $copy.finished)
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
Wait-Exit
if (-not (Test-Path -LiteralPath (Join-Path $newPath ($ProductName + '.exe')))) { throw 'Directory-only removal deleted B' }
$entry = Get-ItemProperty ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey)
if ($entry.InstallLocation.TrimEnd('\') -ne $newPath) { throw 'Directory-only removal deleted B registration' }
if ((Get-ItemProperty ('HKCU:\' + $environmentKey)).Path -ne 'C:\Windows') { throw 'A PATH entry survived partial takeover' }
if ((Get-Item ('HKCU:\' + $protocolKey + '\shell\open\command')).GetValue('') -ne $newProtocol) { throw 'Directory-only removal changed B protocol' }
if ([IO.File]::ReadAllText($replacementData) -ne 'replacement installation data') { throw 'Directory-only removal changed shared user data' }
foreach ($link in $replacementLinks.Keys) {
if ([Convert]::ToBase64String([IO.File]::ReadAllBytes($link)) -ne $replacementLinks[$link]) { throw 'Directory-only removal changed replacement shortcut' }
}
if ((Get-ItemProperty ('HKCU:\' + $ownerKey)).Directory -or (Test-Path -LiteralPath $desktopLink)) { throw 'A owner or shortcut survived partial takeover' }
if ($entry.UninstallString -ne $bUninstall -or $bUninstall -notmatch '^"([^"]+)" (/currentuser)$') { throw 'B uninstall command changed' }
$registeredExe = $Matches[1]
$registeredArgs = $Matches[2]
$installPath = $newPath
if ($registeredExe -ne (Join-Path $newPath ('Uninstall ' + $ProductName + '.exe'))) { throw 'B uninstall entry targets another installation' }
$process = Start-Process $registeredExe -ArgumentList ($registeredArgs + ' /S') -PassThru -WindowStyle Hidden
Wait-Exit
foreach ($key in @($arpKey, ('HKCU:\Software\' + $RegistryKey), ('HKCU:\' + $protocolKey))) {
if (Test-Path -LiteralPath $key) { throw "B uninstall retained registration: $key" }
}
foreach ($link in $replacementLinks.Keys) {
if (Test-Path -LiteralPath $link) { throw "B uninstall retained shortcut: $link" }
}
Write-Output 'passed: installation takeover'
} finally {
Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue
if ($process) { if (-not $process.HasExited) { $process.Kill(); $process.WaitForExit() }; $process.Dispose() }
if ($held) { $held.Dispose() }
if ($setup) { Stop-InstallerProcess $setup; $setup.Dispose() }
if ($process) { Stop-InstallerProcess $process; $process.Dispose() }
if ($ProductName -ne ('Harness Installer Test ' + ([Guid]$RegistryKey).ToString('N').Substring(0, 8))) { throw 'Unexpected fixture identity' }
foreach ($key in @("Software\DSHUninstallTests\$RegistryKey", $protocolKey, "Software\$RegistryKey", "Software\Microsoft\Windows\CurrentVersion\Uninstall\$RegistryKey")) {
[Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($key, $false)
}
foreach ($folder in @('DesktopDirectory', 'Programs')) {
$link = Join-Path ([Environment]::GetFolderPath($folder)) ($ProductName + '.lnk')
if (Test-Path -LiteralPath $link) { Remove-Item -LiteralPath $link -Force }
}
[Environment]::SetEnvironmentVariable('DSH_HOME', $originalHome, 'Process')
# Only unique test identities below known application-data parents are removed.
foreach ($pair in @(@($productDataPath, $roaming), @($scopePath, $roaming), @($cachePath, $local))) {
$target = [IO.Path]::GetFullPath($pair[0])