From af15cdf6c2e4d072c15f6bec239a081b354f7495 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:37:40 +0800 Subject: [PATCH 01/15] fix(desktop): clean owned Windows registrations on manual uninstall --- apps/desktop/README.i18n.yaml | 8 +- apps/desktop/README.md | 4 +- apps/desktop/README.zh.md | 4 +- apps/desktop/installer/locales/de_DE.json | 4 +- apps/desktop/installer/locales/en_US.json | 4 +- apps/desktop/installer/locales/es_ES.json | 4 +- apps/desktop/installer/locales/fr_FR.json | 4 +- apps/desktop/installer/locales/ja_JP.json | 4 +- apps/desktop/installer/locales/pt_BR.json | 4 +- apps/desktop/installer/locales/ru_RU.json | 4 +- apps/desktop/installer/locales/zh_CN.json | 4 +- apps/desktop/installer/uninstall.nsh | 22 ++++++ apps/desktop/scripts/installer.nsh | 1 + .../scripts/test-windows-installer.mjs | 5 +- .../scripts/uninstall-registration.ps1 | 26 +++++++ .../scripts/windows-directory-installer.d.mts | 2 +- .../scripts/windows-directory-installer.mjs | 17 ++++- .../tests/expected/windows-uninstall.json | 10 ++- apps/desktop/tests/fixtures/command-path.ps1 | 23 ++++++ .../desktop/tests/windows-uninstall-smoke.ps1 | 73 ++++++++++++++++++- 20 files changed, 201 insertions(+), 26 deletions(-) create mode 100644 apps/desktop/scripts/uninstall-registration.ps1 diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index dc6cb5f9e0..b0c627b8db 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -18,8 +18,8 @@ en: d4afa46403997884 zh: 9b9fe126afda70f0 /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: ac31ebdd9de54f34 zh: 921e534d5c4b3a16 /deepseek-harness-desktop/windows-installer-interface: - en: f1302ed4a3ab58bb - zh: cb53b9b349815028 + en: 4f61d5a4038423fd + zh: 5ad67e1f9526d517 /deepseek-harness-desktop/updates: en: 67bf0a18faa7aa76 zh: 782e14ce62bb939f diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 68596d719f..619d4a620a 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -63,7 +63,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. @@ -260,7 +260,7 @@ 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 [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. 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. Manual uninstall also removes the owned command PATH entry and its ownership values, and removes `dsh://` only when its command still names this installation. `--updated` preserves these registrations; `/KEEP_APP_DATA` alone does not. A stale uninstaller refuses to proceed when the installation record points elsewhere. Registration-cleanup failure stops before application files are removed; close other installers and retry. 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. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 13661f0590..ae991bc7d8 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -63,7 +63,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)。 @@ -260,7 +260,7 @@ 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 [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` 还会保护所有与其重叠的目标。静默卸载删除相同的数据;以 `--updated` 或 `/KEEP_APP_DATA` 启动的卸载程序保留数据,electron-builder 在原地更新和从其他目录替换旧安装时正是这样启动它。删除通过原生辅助程序执行:它拒绝受保护的 Windows 目录以及与安装目录或主目录重叠的路径,要求固定的本地驱动器,链接的根目录或祖先目录原样保留,遇到重解析点只解除链接而不进入目标,清除只读属性,并在遇到被占用文件后继续删除其余兄弟项;残余不会中止卸载,也不会提示。安装时在 Windows 卸载注册项上记录 `InstallLocation` 作为标准的清单元数据;在 Windows 11 上,开始菜单右键菜单中的“卸载”对所有 Win32 应用都会打开已安装应用列表,只有 MSIX 包能从那里直接卸载。卸载程序声明 DPI 感知,中文使用微软雅黑 UI。手动卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。安装登记指向其他目录时,旧卸载器拒绝继续。注册清理失败会在删除应用文件之前停止;请关闭其他安装程序后重试。此行为仅适用于 Windows。 使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译独立的中英文夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 和 `DSH_HOME` 位于 Electron 数据内的检查。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/locales/de_DE.json b/apps/desktop/installer/locales/de_DE.json index 595002b284..3a2d7bfb9c 100644 --- a/apps/desktop/installer/locales/de_DE.json +++ b/apps/desktop/installer/locales/de_DE.json @@ -32,7 +32,9 @@ "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": "Dieses Deinstallationsprogramm gehört zu einer anderen Installation. Entfernen Sie die aktuelle Installation über Installierte Apps.", + "INSTALLER_UNINSTALL_REGISTRATION": "Die Windows-Befehls- oder Linkregistrierung konnte nicht entfernt werden. Die Anwendungsdateien wurden beibehalten. Schließen Sie andere Installationsprogramme und versuchen Sie es erneut." }, "uninstaller": { "welcome": "Willkommen", diff --git a/apps/desktop/installer/locales/en_US.json b/apps/desktop/installer/locales/en_US.json index 73af2ede5e..b2ed5e8a8c 100644 --- a/apps/desktop/installer/locales/en_US.json +++ b/apps/desktop/installer/locales/en_US.json @@ -32,7 +32,9 @@ "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": "This uninstaller belongs to another installation. Use Installed apps to uninstall the current installation.", + "INSTALLER_UNINSTALL_REGISTRATION": "Windows command or link registration could not be removed. Application files were kept. Close other installers and retry." }, "uninstaller": { "welcome": "Welcome", diff --git a/apps/desktop/installer/locales/es_ES.json b/apps/desktop/installer/locales/es_ES.json index 99e5abe63e..fafcf9dae0 100644 --- a/apps/desktop/installer/locales/es_ES.json +++ b/apps/desktop/installer/locales/es_ES.json @@ -32,7 +32,9 @@ "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": "Este desinstalador pertenece a otra instalación. Use Aplicaciones instaladas para desinstalar la instalación actual.", + "INSTALLER_UNINSTALL_REGISTRATION": "No se pudo eliminar el registro de comandos o enlaces de Windows. Se conservaron los archivos de la aplicación. Cierre los otros instaladores e inténtelo de nuevo." }, "uninstaller": { "welcome": "Bienvenido", diff --git a/apps/desktop/installer/locales/fr_FR.json b/apps/desktop/installer/locales/fr_FR.json index 167922256b..a1c6f0a480 100644 --- a/apps/desktop/installer/locales/fr_FR.json +++ b/apps/desktop/installer/locales/fr_FR.json @@ -32,7 +32,9 @@ "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": "Ce programme de désinstallation appartient à une autre installation. Utilisez Applications installées pour supprimer l’installation actuelle.", + "INSTALLER_UNINSTALL_REGISTRATION": "Impossible de supprimer l’enregistrement des commandes ou des liens Windows. Les fichiers de l’application ont été conservés. Fermez les autres programmes d’installation et réessayez." }, "uninstaller": { "welcome": "Bienvenue", diff --git a/apps/desktop/installer/locales/ja_JP.json b/apps/desktop/installer/locales/ja_JP.json index 72ef1cc641..00f29daef3 100644 --- a/apps/desktop/installer/locales/ja_JP.json +++ b/apps/desktop/installer/locales/ja_JP.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "詳細を非表示", "INSTALLER_EXTRACT_SAVED": "完全なレポートを %s に保存しました", "INSTALLER_EXTRACT_UNSAVED": "完全なレポートを保存できませんでした。「エラーの詳細をコピー」で保存してください。", - "INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。" + "INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。", + "INSTALLER_UNINSTALL_OWNER": "このアンインストーラーは別のインストール先用です。「インストールされているアプリ」から現在のアプリを削除してください。", + "INSTALLER_UNINSTALL_REGISTRATION": "Windows のコマンドまたはリンク登録を削除できませんでした。アプリのファイルは保持されています。他のインストーラーを閉じて再試行してください。" }, "uninstaller": { "welcome": "アンインストール ウィザードへようこそ", diff --git a/apps/desktop/installer/locales/pt_BR.json b/apps/desktop/installer/locales/pt_BR.json index 93aacd5dc8..24e756f4f5 100644 --- a/apps/desktop/installer/locales/pt_BR.json +++ b/apps/desktop/installer/locales/pt_BR.json @@ -32,7 +32,9 @@ "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": "Este desinstalador pertence a outra instalação. Use Aplicativos instalados para desinstalar a instalação atual.", + "INSTALLER_UNINSTALL_REGISTRATION": "Não foi possível remover o registro de comandos ou links do Windows. Os arquivos do aplicativo foram mantidos. Feche os outros instaladores e tente novamente." }, "uninstaller": { "welcome": "Bem-vindo", diff --git a/apps/desktop/installer/locales/ru_RU.json b/apps/desktop/installer/locales/ru_RU.json index 20345ea37c..c2363f6be8 100644 --- a/apps/desktop/installer/locales/ru_RU.json +++ b/apps/desktop/installer/locales/ru_RU.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "Скрыть детали", "INSTALLER_EXTRACT_SAVED": "Полный отчет сохранен в %s.", "INSTALLER_EXTRACT_UNSAVED": "Полный отчет не удалось сохранить. Используйте Скопировать сведения об ошибке, чтобы сохранить их.", - "INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена." + "INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена.", + "INSTALLER_UNINSTALL_OWNER": "Этот деинсталлятор относится к другой установке. Удалите текущую установку через раздел «Установленные приложения».", + "INSTALLER_UNINSTALL_REGISTRATION": "Не удалось удалить регистрацию команд или ссылок Windows. Файлы приложения сохранены. Закройте другие установщики и повторите попытку." }, "uninstaller": { "welcome": "Вас приветствует мастер удаления", diff --git a/apps/desktop/installer/locales/zh_CN.json b/apps/desktop/installer/locales/zh_CN.json index 7951f34340..510dc018b3 100644 --- a/apps/desktop/installer/locales/zh_CN.json +++ b/apps/desktop/installer/locales/zh_CN.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "隐藏详情", "INSTALLER_EXTRACT_SAVED": "完整错误报告已保存到 %s", "INSTALLER_EXTRACT_UNSAVED": "无法保存完整错误报告,请使用“复制错误信息”保留。", - "INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。" + "INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。", + "INSTALLER_UNINSTALL_OWNER": "此卸载程序属于另一安装目录。请从“已安装的应用”卸载当前安装。", + "INSTALLER_UNINSTALL_REGISTRATION": "无法清理 Windows 命令或链接注册。应用文件已保留。请关闭其他安装程序后重试。" }, "uninstaller": { "welcome": "欢迎", diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index defdd15923..43f3709202 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -34,3 +34,25 @@ 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" +Function un.CleanRegistration + ${If} ${isUpdated} + Return + ${EndIf} + InitPluginsDir + File /oname=$PLUGINSDIR\command-path.ps1 "${__FILEDIR__}\..\scripts\command-path.ps1" + File /oname=$PLUGINSDIR\uninstall-registration.ps1 "${__FILEDIR__}\..\scripts\uninstall-registration.ps1" + 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}"' + Pop $0 + Pop $1 + ${If} $0 != 0 + DetailPrint $1 + MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UNINSTALL_REGISTRATION)" /SD IDOK + SetErrorLevel 2 + Quit + ${EndIf} +FunctionEnd diff --git a/apps/desktop/scripts/installer.nsh b/apps/desktop/scripts/installer.nsh index 219522f1ee..18b30d5b7a 100644 --- a/apps/desktop/scripts/installer.nsh +++ b/apps/desktop/scripts/installer.nsh @@ -94,6 +94,7 @@ ManifestDPIAware true !macroend !macro customUnInstall + Call un.CleanRegistration Call un.CleanData !macroend diff --git a/apps/desktop/scripts/test-windows-installer.mjs b/apps/desktop/scripts/test-windows-installer.mjs index 02e356b924..3c354d1393 100644 --- a/apps/desktop/scripts/test-windows-installer.mjs +++ b/apps/desktop/scripts/test-windows-installer.mjs @@ -131,11 +131,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_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', diff --git a/apps/desktop/scripts/uninstall-registration.ps1 b/apps/desktop/scripts/uninstall-registration.ps1 new file mode 100644 index 0000000000..e30c3b432b --- /dev/null +++ b/apps/desktop/scripts/uninstall-registration.ps1 @@ -0,0 +1,26 @@ +<# Remove only this installation's user registrations. Fail before payload deletion on an unknown outcome. #> +param([Parameter(Mandatory)][string]$Directory, + [string]$ExecutableName = 'DeepSeek Harness.exe', + [string]$EnvironmentKey = 'Environment', + [string]$OwnerKey = 'Software\DeepSeekHarness\Command', + [string]$ProtocolKey = 'Software\Classes\dsh') +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'command-path.ps1') +try { + $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $options = @{ EnvironmentKey=$EnvironmentKey; OwnerKey=$OwnerKey; MachinePath=''; MutexName=('Global\DeepSeekHarness.Command.' + $sid) } + $command = Join-Path $Directory 'resources\runtime\cli\bin' + $state = Invoke-DshCommandPath -Request @{operation='inspect'; directory=$command} @options + [void](Invoke-DshCommandPath -Request @{operation='remove'; directory=$command; expected=$state.fingerprint} @options) + Send-DshCommandEnvironmentChange + $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 { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/desktop/scripts/windows-directory-installer.d.mts b/apps/desktop/scripts/windows-directory-installer.d.mts index a9be087fe6..5f4863d112 100644 --- a/apps/desktop/scripts/windows-directory-installer.d.mts +++ b/apps/desktop/scripts/windows-directory-installer.d.mts @@ -15,7 +15,7 @@ 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. + * Retain the original uninstall directory, reject another installation owner, and use native data cleanup. * @param source - Pinned upstream uninstaller source. * @returns Uninstaller with long-path application removal and no upstream RMDir data removal. */ diff --git a/apps/desktop/scripts/windows-directory-installer.mjs b/apps/desktop/scripts/windows-directory-installer.mjs index 8508730b47..247bd11ee3 100644 --- a/apps/desktop/scripts/windows-directory-installer.mjs +++ b/apps/desktop/scripts/windows-directory-installer.mjs @@ -85,12 +85,25 @@ export function installWindowsDirectoryInstaller() { } /** - * Keep user-data removal in the native helper, which refuses unsafe roots and never follows links. + * Retain the original uninstall directory, reject another installation owner, and use native data cleanup. * @param {string} source - Pinned upstream uninstaller source. * @returns {string} Uninstaller with long-path application removal and no upstream RMDir data removal. */ export function directoryUninstaller(source) { - const normalized = source.replaceAll('\r\n', '\n') + let normalized = source.replaceAll('\r\n', '\n') + 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 + ReadRegStr $R0 SHELL_CONTEXT "\${INSTALL_REGISTRY_KEY}" InstallLocation + \${If} $R0 != "" + GetFullPathName $R0 "$R0\\." + GetFullPathName $R1 "$INSTDIR\\." + \${If} $R0 != $R1 + MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UNINSTALL_OWNER)" /SD IDOK + SetErrorLevel 2 + Quit + \${EndIf} + \${EndIf}`) 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') diff --git a/apps/desktop/tests/expected/windows-uninstall.json b/apps/desktop/tests/expected/windows-uninstall.json index 8a6a99cc57..80737cdce7 100644 --- a/apps/desktop/tests/expected/windows-uninstall.json +++ b/apps/desktop/tests/expected/windows-uninstall.json @@ -1,3 +1,11 @@ { - "cases": ["interactive", "silent", "upgrade", "replaced", "home-inside"] + "cases": [ + "interactive", + "silent", + "upgrade", + "replaced", + "home-inside", + "registration-error", + "self-copy" + ] } diff --git a/apps/desktop/tests/fixtures/command-path.ps1 b/apps/desktop/tests/fixtures/command-path.ps1 index ef6f15930a..5c5aa08829 100644 --- a/apps/desktop/tests/fixtures/command-path.ps1 +++ b/apps/desktop/tests/fixtures/command-path.ps1 @@ -92,6 +92,29 @@ 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 + 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) + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($protocolKey + '\shell\open\command', $true) + try { $key.SetValue('', '"' + (Join-Path $app 'DeepSeek Harness.exe') + '" "%1"') } finally { $key.Dispose() } + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey + 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' 'WINDOWS_COMMAND_PATH_OK' } finally { [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($keyRoot, $false) diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index dad594f7c3..8450eef6e1 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -20,6 +20,9 @@ $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 function Wait-Text([string]$Text) { $timer = [Diagnostics.Stopwatch]::StartNew() @@ -62,13 +65,31 @@ 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 + $commandDirectory = Join-Path $installPath '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() } + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command') + try { $key.SetValue('', '"' + (Join-Path $installPath ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() } + $launchUninstaller = $uninstaller $arguments = '_?=' + $installPath - if ($mode -in @('silent', 'home-inside')) { $arguments = '/S ' + $arguments } + if ($mode -in @('silent', 'home-inside', 'registration-error')) { $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 'registration-error') { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true) + try { $key.SetValue('Path', 42, [Microsoft.Win32.RegistryValueKind]::DWord) } finally { $key.Dispose() } + } + $process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle ($(if ($mode -eq 'interactive') { 'Normal' } else { 'Hidden' })) if ($mode -eq 'interactive') { $welcomeText = $copy.welcome $welcome = Wait-Text $welcomeText @@ -79,8 +100,16 @@ try { [void](Wait-Text $finishedText) [InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1)) } + if ($mode -eq 'registration-error') { + if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Registration failure did not stop uninstall' } + $process.Dispose(); $process = $null + if (-not (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe')))) { throw 'Failed registration cleanup deleted application' } + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true) + try { $key.SetValue('Path', $commandDirectory + ';C:\Windows', [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Dispose() } + $process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle Hidden + } Wait-Exit - $retained = $mode -in @('upgrade', 'replaced') + $retained = $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' if ([IO.File]::ReadAllText((Join-Path $externalPath 'keep.txt')) -ne 'outside data root') { throw 'Cleanup followed a junction into a project' } @@ -89,9 +118,45 @@ try { 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 = $mode -eq 'upgrade' + $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 + if ($path.Contains($commandDirectory) -ne $integrationsRetained -or -not $path.Contains('C:\Windows')) { throw "PATH cleanup failed: $mode" } + if ((Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) -ne $integrationsRetained) { throw "Protocol cleanup failed: $mode" } 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 + try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover A setup failed' } } finally { $setup.Dispose() } + Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force + $newPath = Join-Path $OutputDirectory 'Replacement App' + $setup = Start-Process $Installer -ArgumentList ('/S /D=' + $newPath) -PassThru -WindowStyle Hidden + try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover B setup failed' } } finally { $setup.Dispose() } + $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' } + $installPath = $newPath + Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force + $process = Start-Process $uninstaller -ArgumentList ('/S _?=' + $installPath) -PassThru -WindowStyle Hidden + Wait-Exit + Write-Output 'passed: installation takeover' } finally { + foreach ($key in @("Software\DSHUninstallTests\$RegistryKey", $protocolKey)) { [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($key, $false) } Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue if ($process) { if (-not $process.HasExited) { $process.Kill(); $process.WaitForExit() }; $process.Dispose() } # Only unique test identities below known application-data parents are removed. From d54a04e902cd6ee7074cd8cc379fbb2c21518e06 Mon Sep 17 00:00:00 2001 From: winewill Date: Fri, 13 Nov 2026 18:21:16 +0800 Subject: [PATCH 02/15] fix(desktop): report uninstall residue and allow scoped cleanup --- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 4 +- apps/desktop/README.zh.md | 4 +- apps/desktop/installer/locales/de_DE.json | 15 +- apps/desktop/installer/locales/en_US.json | 15 +- apps/desktop/installer/locales/es_ES.json | 15 +- apps/desktop/installer/locales/fr_FR.json | 15 +- apps/desktop/installer/locales/ja_JP.json | 15 +- apps/desktop/installer/locales/pt_BR.json | 15 +- apps/desktop/installer/locales/ru_RU.json | 15 +- apps/desktop/installer/locales/zh_CN.json | 15 +- apps/desktop/installer/uninstall-data.h | 24 +- apps/desktop/installer/uninstall-report.h | 299 ++++++++++++++++++ apps/desktop/installer/uninstall.nsh | 129 +++++++- apps/desktop/installer/window-frame.cpp | 1 + apps/desktop/scripts/installer.nsh | 8 + .../scripts/prepare-windows-installer.ps1 | 6 +- .../scripts/test-windows-installer.mjs | 2 +- .../scripts/uninstall-registration.ps1 | 29 +- .../scripts/windows-directory-installer.mjs | 21 +- .../tests/expected/windows-uninstall.json | 6 +- apps/desktop/tests/fixtures/command-path.ps1 | 6 +- apps/desktop/tests/installer-locales.spec.ts | 2 +- .../tests/windows-directory-installer.spec.ts | 5 + apps/desktop/tests/windows-installer-ui.ps1 | 20 ++ apps/desktop/tests/windows-uninstall-data.cpp | 37 +++ .../desktop/tests/windows-uninstall-smoke.ps1 | 110 ++++++- 27 files changed, 766 insertions(+), 71 deletions(-) create mode 100644 apps/desktop/installer/uninstall-report.h diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index b0c627b8db..bf83413624 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -54,8 +54,8 @@ en: ac31ebdd9de54f34 zh: 921e534d5c4b3a16 /deepseek-harness-desktop/windows-installer-interface: - en: 4f61d5a4038423fd - zh: 5ad67e1f9526d517 + en: 176652e23b08686f + zh: 266bfe230ec4165e /deepseek-harness-desktop/updates: en: 67bf0a18faa7aa76 zh: 782e14ce62bb939f diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 619d4a620a..ada1f0fe8f 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -260,9 +260,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 [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. Manual uninstall also removes the owned command PATH entry and its ownership values, and removes `dsh://` only when its command still names this installation. `--updated` preserves these registrations; `/KEEP_APP_DATA` alone does not. A stale uninstaller refuses to proceed when the installation record points elsewhere. Registration-cleanup failure stops before application files are removed; close other installers and retry. 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. 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 uninstall also removes the owned command PATH entry and its ownership values, and removes `dsh://` only when its command still names this installation. `--updated` preserves these registrations; `/KEEP_APP_DATA` alone does not. When the installation record points elsewhere, interactive uninstall offers to clean only the original directory, skipping shared data, shortcuts and registrations; silent uninstall refuses this choice. 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-.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. Compilation does not establish installed-uninstall behavior. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index ae991bc7d8..a306a2bf87 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -260,9 +260,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 [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。手动卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。安装登记指向其他目录时,旧卸载器拒绝继续。注册清理失败会在删除应用文件之前停止;请关闭其他安装程序后重试。此行为仅适用于 Windows。 +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。手动卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。安装登记指向其他目录时,交互式卸载允许用户选择仅清理原卸载目录,跳过共享数据、快捷方式和注册信息;静默卸载拒绝代替用户作此选择。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.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 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/locales/de_DE.json b/apps/desktop/installer/locales/de_DE.json index 3a2d7bfb9c..d36ef30ff3 100644 --- a/apps/desktop/installer/locales/de_DE.json +++ b/apps/desktop/installer/locales/de_DE.json @@ -33,8 +33,19 @@ "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_UNINSTALL_OWNER": "Dieses Deinstallationsprogramm gehört zu einer anderen Installation. Entfernen Sie die aktuelle Installation über Installierte Apps.", - "INSTALLER_UNINSTALL_REGISTRATION": "Die Windows-Befehls- oder Linkregistrierung konnte nicht entfernt werden. Die Anwendungsdateien wurden beibehalten. Schließen Sie andere Installationsprogramme und versuchen Sie es erneut." + "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_DIRECTORY": "Ort des Deinstallationsprogramms:", + "INSTALLER_UNINSTALL_SCOPE": "Beim Fortfahren wird nur dieser Ordner bereinigt:", + "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", diff --git a/apps/desktop/installer/locales/en_US.json b/apps/desktop/installer/locales/en_US.json index b2ed5e8a8c..7792810a52 100644 --- a/apps/desktop/installer/locales/en_US.json +++ b/apps/desktop/installer/locales/en_US.json @@ -33,8 +33,19 @@ "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_UNINSTALL_OWNER": "This uninstaller belongs to another installation. Use Installed apps to uninstall the current installation.", - "INSTALLER_UNINSTALL_REGISTRATION": "Windows command or link registration could not be removed. Application files were kept. Close other installers and retry." + "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_DIRECTORY": "Uninstaller location:", + "INSTALLER_UNINSTALL_SCOPE": "Continuing will only clean", + "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", diff --git a/apps/desktop/installer/locales/es_ES.json b/apps/desktop/installer/locales/es_ES.json index fafcf9dae0..a13dd56594 100644 --- a/apps/desktop/installer/locales/es_ES.json +++ b/apps/desktop/installer/locales/es_ES.json @@ -33,8 +33,19 @@ "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_UNINSTALL_OWNER": "Este desinstalador pertenece a otra instalación. Use Aplicaciones instaladas para desinstalar la instalación actual.", - "INSTALLER_UNINSTALL_REGISTRATION": "No se pudo eliminar el registro de comandos o enlaces de Windows. Se conservaron los archivos de la aplicación. Cierre los otros instaladores e inténtelo de nuevo." + "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_DIRECTORY": "Ubicación del desinstalador:", + "INSTALLER_UNINSTALL_SCOPE": "Al continuar, solo se limpiará", + "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", diff --git a/apps/desktop/installer/locales/fr_FR.json b/apps/desktop/installer/locales/fr_FR.json index a1c6f0a480..a52079ede3 100644 --- a/apps/desktop/installer/locales/fr_FR.json +++ b/apps/desktop/installer/locales/fr_FR.json @@ -33,8 +33,19 @@ "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_UNINSTALL_OWNER": "Ce programme de désinstallation appartient à une autre installation. Utilisez Applications installées pour supprimer l’installation actuelle.", - "INSTALLER_UNINSTALL_REGISTRATION": "Impossible de supprimer l’enregistrement des commandes ou des liens Windows. Les fichiers de l’application ont été conservés. Fermez les autres programmes d’installation et réessayez." + "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_DIRECTORY": "Emplacement du programme de désinstallation :", + "INSTALLER_UNINSTALL_SCOPE": "Continuer nettoiera uniquement", + "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", diff --git a/apps/desktop/installer/locales/ja_JP.json b/apps/desktop/installer/locales/ja_JP.json index 00f29daef3..712a7d2c21 100644 --- a/apps/desktop/installer/locales/ja_JP.json +++ b/apps/desktop/installer/locales/ja_JP.json @@ -33,8 +33,19 @@ "INSTALLER_EXTRACT_SAVED": "完全なレポートを %s に保存しました", "INSTALLER_EXTRACT_UNSAVED": "完全なレポートを保存できませんでした。「エラーの詳細をコピー」で保存してください。", "INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。", - "INSTALLER_UNINSTALL_OWNER": "このアンインストーラーは別のインストール先用です。「インストールされているアプリ」から現在のアプリを削除してください。", - "INSTALLER_UNINSTALL_REGISTRATION": "Windows のコマンドまたはリンク登録を削除できませんでした。アプリのファイルは保持されています。他のインストーラーを閉じて再試行してください。" + "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness が複数の場所にインストールされています", + "INSTALLER_UNINSTALL_REGISTRATION": "一部の項目を削除できませんでした。詳細はレポートを保存して確認できます。", + "INSTALLER_UNINSTALL_REGISTERED": "登録されているインストール先:", + "INSTALLER_UNINSTALL_DIRECTORY": "アンインストーラーの場所:", + "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": "アンインストール ウィザードへようこそ", diff --git a/apps/desktop/installer/locales/pt_BR.json b/apps/desktop/installer/locales/pt_BR.json index 24e756f4f5..c076bc3dcb 100644 --- a/apps/desktop/installer/locales/pt_BR.json +++ b/apps/desktop/installer/locales/pt_BR.json @@ -33,8 +33,19 @@ "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_UNINSTALL_OWNER": "Este desinstalador pertence a outra instalação. Use Aplicativos instalados para desinstalar a instalação atual.", - "INSTALLER_UNINSTALL_REGISTRATION": "Não foi possível remover o registro de comandos ou links do Windows. Os arquivos do aplicativo foram mantidos. Feche os outros instaladores e tente novamente." + "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_DIRECTORY": "Local do desinstalador:", + "INSTALLER_UNINSTALL_SCOPE": "Ao continuar, somente este local será limpo:", + "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", diff --git a/apps/desktop/installer/locales/ru_RU.json b/apps/desktop/installer/locales/ru_RU.json index c2363f6be8..8cf75546d7 100644 --- a/apps/desktop/installer/locales/ru_RU.json +++ b/apps/desktop/installer/locales/ru_RU.json @@ -33,8 +33,19 @@ "INSTALLER_EXTRACT_SAVED": "Полный отчет сохранен в %s.", "INSTALLER_EXTRACT_UNSAVED": "Полный отчет не удалось сохранить. Используйте Скопировать сведения об ошибке, чтобы сохранить их.", "INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена.", - "INSTALLER_UNINSTALL_OWNER": "Этот деинсталлятор относится к другой установке. Удалите текущую установку через раздел «Установленные приложения».", - "INSTALLER_UNINSTALL_REGISTRATION": "Не удалось удалить регистрацию команд или ссылок Windows. Файлы приложения сохранены. Закройте другие установщики и повторите попытку." + "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness установлен в нескольких местах", + "INSTALLER_UNINSTALL_REGISTRATION": "Некоторые элементы не удалось очистить. Сохраните отчёт для просмотра подробностей.", + "INSTALLER_UNINSTALL_REGISTERED": "Зарегистрированное расположение:", + "INSTALLER_UNINSTALL_DIRECTORY": "Расположение программы удаления:", + "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": "Вас приветствует мастер удаления", diff --git a/apps/desktop/installer/locales/zh_CN.json b/apps/desktop/installer/locales/zh_CN.json index 510dc018b3..11803a2c45 100644 --- a/apps/desktop/installer/locales/zh_CN.json +++ b/apps/desktop/installer/locales/zh_CN.json @@ -33,8 +33,19 @@ "INSTALLER_EXTRACT_SAVED": "完整错误报告已保存到 %s", "INSTALLER_EXTRACT_UNSAVED": "无法保存完整错误报告,请使用“复制错误信息”保留。", "INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。", - "INSTALLER_UNINSTALL_OWNER": "此卸载程序属于另一安装目录。请从“已安装的应用”卸载当前安装。", - "INSTALLER_UNINSTALL_REGISTRATION": "无法清理 Windows 命令或链接注册。应用文件已保留。请关闭其他安装程序后重试。" + "INSTALLER_UNINSTALL_OWNER": "当前设备在多个位置安装了 DeepSeek Harness", + "INSTALLER_UNINSTALL_REGISTRATION": "部分内容未能清理成功。你可以保存清理报告,查看具体项目和原因。", + "INSTALLER_UNINSTALL_REGISTERED": "系统登记的安装位置:", + "INSTALLER_UNINSTALL_DIRECTORY": "卸载程序所在位置:", + "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": "欢迎", diff --git a/apps/desktop/installer/uninstall-data.h b/apps/desktop/installer/uninstall-data.h index d582de4c4d..e7f1c0cdcc 100644 --- a/apps/desktop/installer/uninstall-data.h +++ b/apps/desktop/installer/uninstall-data.h @@ -5,6 +5,12 @@ #include namespace uninstall_data { +struct Failure { std::wstring path; DWORD error; }; +using Failures = std::vector; +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 values; Handles() = default; @@ -61,42 +67,42 @@ 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; @@ -146,7 +152,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. diff --git a/apps/desktop/installer/uninstall-report.h b/apps/desktop/installer/uninstall-report.h new file mode 100644 index 0000000000..8cc871ef30 --- /dev/null +++ b/apps/desktop/installer/uninstall-report.h @@ -0,0 +1,299 @@ +// Manual uninstall diagnostics and native dialogs. The NSIS caller owns one session until process exit. +#pragma once +#include +#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(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(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(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(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(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(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) { + std::wstring path; + if (!uninstall_data::Normalize(directory, path)) return ERROR_INVALID_NAME; + if (protectedRoot && *protectedRoot) { + std::wstring home; + if (!uninstall_data::Normalize(protectedRoot, home)) return ERROR_INVALID_NAME; + if (uninstall_data::Contains(path, home) || uninstall_data::Contains(home, path)) return ERROR_ACCESS_DENIED; + } + 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(&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) { + const DWORD error = uninstall_report::Prepare(*session, path, home); + if (error) uninstall_report::Add(*session, L"Validate removal scope; no deletion started", 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(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); + } + 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 directoryLabel, LPCWSTR scopeLabel, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) { + const std::wstring body = std::wstring(registeredLabel) + L"\r\n" + registered + L"\r\n\r\n" + + directoryLabel + L"\r\n" + directory + L"\r\n\r\n" + scopeLabel + L" " + directory; + return uninstall_report::Show(parent, *session, 1, title, heading, body.c_str(), primary, save, failed); +} diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index 43f3709202..6361a861ef 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -2,15 +2,111 @@ !include FileFunc.nsh Var UnTarget Var UnHome +Var UnSession +Var UnDirectoryOnly +Var UnReportPath +Var UnHeading +Var UnBody +Var UnMode +Var UnResult +Var UnRegistered + +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_DIRECTORY)", 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 + 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' + ${If} $0 != 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. @@ -39,20 +135,41 @@ FunctionEnd !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.RefreshOwnership + ${If} ${isUpdated} + Return + ${EndIf} + ReadRegStr $0 SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation + ${If} $0 == "" + StrCpy $UnDirectoryOnly 1 + Return + ${EndIf} + GetFullPathName $0 "$0\." + GetFullPathName $1 "$INSTDIR\." + ${If} $0 != $1 + StrCpy $UnDirectoryOnly 1 + ${EndIf} +FunctionEnd + Function un.CleanRegistration ${If} ${isUpdated} + ${OrIf} $UnDirectoryOnly == 1 + Return + ${EndIf} + Call un.RefreshOwnership + ${If} $UnDirectoryOnly == 1 Return ${EndIf} InitPluginsDir File /oname=$PLUGINSDIR\command-path.ps1 "${__FILEDIR__}\..\scripts\command-path.ps1" File /oname=$PLUGINSDIR\uninstall-registration.ps1 "${__FILEDIR__}\..\scripts\uninstall-registration.ps1" - 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}"' + 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}"' Pop $0 Pop $1 + System::Call '$PLUGINSDIR\window-frame.dll::UninstallImport(p $UnSession, w "$PLUGINSDIR\registration-report.txt") ?c' ${If} $0 != 0 DetailPrint $1 - MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UNINSTALL_REGISTRATION)" /SD IDOK - SetErrorLevel 2 - Quit + 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 diff --git a/apps/desktop/installer/window-frame.cpp b/apps/desktop/installer/window-frame.cpp index 67ec64ce40..d3d3d0308f 100644 --- a/apps/desktop/installer/window-frame.cpp +++ b/apps/desktop/installer/window-frame.cpp @@ -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; diff --git a/apps/desktop/scripts/installer.nsh b/apps/desktop/scripts/installer.nsh index 18b30d5b7a..39c53e24c9 100644 --- a/apps/desktop/scripts/installer.nsh +++ b/apps/desktop/scripts/installer.nsh @@ -94,6 +94,7 @@ ManifestDPIAware true !macroend !macro customUnInstall + Call un.BeginCleanup Call un.CleanRegistration Call un.CleanData !macroend @@ -172,6 +173,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 +205,9 @@ ManifestDPIAware true SetErrorLevel 2 Quit ${EndIf} + !ifdef BUILD_UNINSTALLER + ${EndIf} + !endif !macroend !macro customInstallerDirectoryFailed diff --git a/apps/desktop/scripts/prepare-windows-installer.ps1 b/apps/desktop/scripts/prepare-windows-installer.ps1 index 5195891033..e073e16926 100644 --- a/apps/desktop/scripts/prepare-windows-installer.ps1 +++ b/apps/desktop/scripts/prepare-windows-installer.ps1 @@ -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) { diff --git a/apps/desktop/scripts/test-windows-installer.mjs b/apps/desktop/scripts/test-windows-installer.mjs index 3c354d1393..4bd6afb712 100644 --- a/apps/desktop/scripts/test-windows-installer.mjs +++ b/apps/desktop/scripts/test-windows-installer.mjs @@ -131,7 +131,7 @@ SectionEnd const strings = join(languageOutput, 'strings.nsh') await writeFile(strings, renderInstallerStrings([locale]), 'utf8') const include = join(languageOutput, 'include.nsh') - await writeFile(include, `!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 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 }, diff --git a/apps/desktop/scripts/uninstall-registration.ps1 b/apps/desktop/scripts/uninstall-registration.ps1 index e30c3b432b..37b93b2ec9 100644 --- a/apps/desktop/scripts/uninstall-registration.ps1 +++ b/apps/desktop/scripts/uninstall-registration.ps1 @@ -1,18 +1,30 @@ -<# Remove only this installation's user registrations. Fail before payload deletion on an unknown outcome. #> +<# Remove only owned registrations; independently failed operations leave a diagnostic report. #> param([Parameter(Mandatory)][string]$Directory, [string]$ExecutableName = 'DeepSeek Harness.exe', [string]$EnvironmentKey = 'Environment', [string]$OwnerKey = 'Software\DeepSeekHarness\Command', - [string]$ProtocolKey = 'Software\Classes\dsh') + [string]$ProtocolKey = 'Software\Classes\dsh', + [Parameter(Mandatory)][string]$ReportPath, + [string]$MutexName) $ErrorActionPreference = 'Stop' . (Join-Path $PSScriptRoot 'command-path.ps1') +$failures = [Collections.Generic.List[string]]::new() try { - $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value - $options = @{ EnvironmentKey=$EnvironmentKey; OwnerKey=$OwnerKey; MachinePath=''; MutexName=('Global\DeepSeekHarness.Command.' + $sid) } + 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 - [void](Invoke-DshCommandPath -Request @{operation='remove'; directory=$command; expected=$state.fingerprint} @options) - Send-DshCommandEnvironmentChange + if ($state.managed) { + [void](Invoke-DshCommandPath -Request @{operation='remove'; directory=$command; expected=$state.fingerprint} @options) + Send-DshCommandEnvironmentChange + } +} catch { + $failures.Add("[unverified] Remove owned command registration`r`nHKCU\$EnvironmentKey [Path]`r`nHKCU\$OwnerKey`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)") +} +try { $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($ProtocolKey + '\shell\open\command') try { $registered = if ($key) { $key.GetValue('') } else { $null } } finally { if ($key) { $key.Dispose() } } @@ -21,6 +33,9 @@ try { [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($ProtocolKey, $false) } } catch { - [Console]::Error.WriteLine($_.Exception.Message) + $failures.Add("[unverified] Remove protocol registration`r`nHKCU\$ProtocolKey`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)") +} +if ($failures.Count) { + [IO.File]::WriteAllText($ReportPath, ($failures -join "`r`n`r`n"), [Text.UTF8Encoding]::new($true)) exit 1 } diff --git a/apps/desktop/scripts/windows-directory-installer.mjs b/apps/desktop/scripts/windows-directory-installer.mjs index 247bd11ee3..f0d037e606 100644 --- a/apps/desktop/scripts/windows-directory-installer.mjs +++ b/apps/desktop/scripts/windows-directory-installer.mjs @@ -85,7 +85,7 @@ export function installWindowsDirectoryInstaller() { } /** - * Retain the original uninstall directory, reject another installation owner, and use native data cleanup. + * 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. */ @@ -94,18 +94,29 @@ export function directoryUninstaller(source) { 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 - ReadRegStr $R0 SHELL_CONTEXT "\${INSTALL_REGISTRY_KEY}" InstallLocation - \${If} $R0 != "" + \${If} \${isUpdated} + ReadRegStr $R0 SHELL_CONTEXT "\${INSTALL_REGISTRY_KEY}" InstallLocation GetFullPathName $R0 "$R0\\." GetFullPathName $R1 "$INSTDIR\\." \${If} $R0 != $R1 - MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UNINSTALL_OWNER)" /SD IDOK 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"') } diff --git a/apps/desktop/tests/expected/windows-uninstall.json b/apps/desktop/tests/expected/windows-uninstall.json index 80737cdce7..03a1ccdf22 100644 --- a/apps/desktop/tests/expected/windows-uninstall.json +++ b/apps/desktop/tests/expected/windows-uninstall.json @@ -6,6 +6,10 @@ "replaced", "home-inside", "registration-error", - "self-copy" + "main-locked", + "self-copy", + "auxiliary-locked", + "unsafe-root", + "save-report" ] } diff --git a/apps/desktop/tests/fixtures/command-path.ps1 b/apps/desktop/tests/fixtures/command-path.ps1 index 5c5aa08829..82eb4e8a16 100644 --- a/apps/desktop/tests/fixtures/command-path.ps1 +++ b/apps/desktop/tests/fixtures/command-path.ps1 @@ -1,4 +1,4 @@ -param([string]$Worker, [string]$Root) +param([string]$Worker, [string]$Root) $ErrorActionPreference = 'Stop' [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) . $Worker @@ -103,7 +103,7 @@ try { $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 + & 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') @@ -111,7 +111,7 @@ try { [void](Apply 'install' $bin) $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($protocolKey + '\shell\open\command', $true) try { $key.SetValue('', '"' + (Join-Path $app 'DeepSeek Harness.exe') + '" "%1"') } finally { $key.Dispose() } - & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey + & 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' diff --git a/apps/desktop/tests/installer-locales.spec.ts b/apps/desktop/tests/installer-locales.spec.ts index be9675184d..b4a8feeca2 100644 --- a/apps/desktop/tests/installer-locales.spec.ts +++ b/apps/desktop/tests/installer-locales.spec.ts @@ -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}') }) diff --git a/apps/desktop/tests/windows-directory-installer.spec.ts b/apps/desktop/tests/windows-directory-installer.spec.ts index fa3c6b34e9..466da27978 100644 --- a/apps/desktop/tests/windows-directory-installer.spec.ts +++ b/apps/desktop/tests/windows-directory-installer.spec.ts @@ -13,12 +13,17 @@ it('keeps data cleanup out of the upstream template while retaining application 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).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(() => 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') }) diff --git a/apps/desktop/tests/windows-installer-ui.ps1 b/apps/desktop/tests/windows-installer-ui.ps1 index bf2f6e63e5..3383f51728 100644 --- a/apps/desktop/tests/windows-installer-ui.ps1 +++ b/apps/desktop/tests/windows-installer-ui.ps1 @@ -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) { diff --git a/apps/desktop/tests/windows-uninstall-data.cpp b/apps/desktop/tests/windows-uninstall-data.cpp index 086d09ebcd..1498818cae 100644 --- a/apps/desktop/tests/windows-uninstall-data.cpp +++ b/apps/desktop/tests/windows-uninstall-data.cpp @@ -6,6 +6,11 @@ #include #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); + 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); @@ -86,6 +91,38 @@ 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())); assert(RemoveDirectoryW(root.c_str())); } diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index 8450eef6e1..262b0c3581 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -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, @@ -24,6 +24,8 @@ $environmentKey = "Software\DSHUninstallTests\$RegistryKey\CommandEnvironment" $ownerKey = "Software\DSHUninstallTests\$RegistryKey\CommandOwner" $protocolKey = "Software\Classes\dsh-test-$RegistryKey" $process = $null +$held = $null +$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 { @@ -74,7 +76,7 @@ try { try { $key.SetValue('', '"' + (Join-Path $installPath ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() } $launchUninstaller = $uninstaller $arguments = '_?=' + $installPath - if ($mode -in @('silent', 'home-inside', 'registration-error')) { $arguments = '/S ' + $arguments } + if ($mode -in @('silent', 'home-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') { Set-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation -Value ($installPath + '\') @@ -85,29 +87,94 @@ try { $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 } - if ($mode -eq 'registration-error') { + 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() } } - $process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle ($(if ($mode -eq 'interactive') { 'Normal' } else { 'Hidden' })) - if ($mode -eq 'interactive') { + 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)) + $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' } + $save = Wait-Text $strings.INSTALLER_UNINSTALL_SAVE + [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 'registration-error') { - if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Registration failure did not stop uninstall' } + 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 - if (-not (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe')))) { throw 'Failed registration cleanup deleted application' } - $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true) - try { $key.SetValue('Path', $commandDirectory + ';C:\Windows', [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Dispose() } $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', 'self-copy') # A DSH_HOME inside the Electron directory protects that directory (and its scope) but not the other roots. @@ -118,12 +185,12 @@ try { 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 = $mode -eq 'upgrade' + $integrationsRetained = $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 - if ($path.Contains($commandDirectory) -ne $integrationsRetained -or -not $path.Contains('C:\Windows')) { throw "PATH cleanup failed: $mode" } - if ((Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) -ne $integrationsRetained) { throw "Protocol cleanup failed: $mode" } + if ($mode -notin @('registration-error', 'save-report') -and ($path.Contains($commandDirectory) -ne $integrationsRetained -or -not $path.Contains('C:\Windows'))) { throw "PATH cleanup failed: $mode" } + if ((Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) -ne ($mode -eq 'upgrade')) { throw "Protocol cleanup failed: $mode" } Write-Output "passed: $mode" } # Real replacement publishes B after the old A uninstaller has been retained. @@ -150,12 +217,29 @@ try { 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' } + Copy-Item -LiteralPath $newPath -Destination $installPath -Recurse + $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 ($newCommand + ';C:\Windows')) { throw 'Directory-only removal changed B PATH' } + if ((Get-Item ('HKCU:\' + $protocolKey + '\shell\open\command')).GetValue('') -ne $newProtocol) { throw 'Directory-only removal changed B protocol' } $installPath = $newPath Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force $process = Start-Process $uninstaller -ArgumentList ('/S _?=' + $installPath) -PassThru -WindowStyle Hidden Wait-Exit Write-Output 'passed: installation takeover' } finally { + if ($held) { $held.Dispose() } foreach ($key in @("Software\DSHUninstallTests\$RegistryKey", $protocolKey)) { [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($key, $false) } Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue if ($process) { if (-not $process.HasExited) { $process.Kill(); $process.WaitForExit() }; $process.Dispose() } From 99278a0768aae11f6c1020ae1119755a2f4952d6 Mon Sep 17 00:00:00 2001 From: winewill Date: Fri, 13 Nov 2026 18:30:56 +0800 Subject: [PATCH 03/15] test(desktop): wait for saved reports and verify takeover data --- apps/desktop/tests/windows-uninstall-smoke.ps1 | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index 262b0c3581..7f1fdc67ab 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -138,13 +138,14 @@ try { [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' } - $save = Wait-Text $strings.INSTALLER_UNINSTALL_SAVE [void][InstallerCapture]::PostMessage([InstallerCapture]::TopLevel($save), 0x10, [IntPtr]::Zero, [IntPtr]::Zero) } $finishedText = $copy.finished @@ -217,6 +218,14 @@ try { 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)) } + } Copy-Item -LiteralPath $newPath -Destination $installPath -Recurse $process = Start-Process $uninstaller -ArgumentList ('/currentuser _?=' + $installPath) -PassThru $welcome = Wait-Text $copy.welcome @@ -233,6 +242,11 @@ try { if ($entry.InstallLocation.TrimEnd('\') -ne $newPath) { throw 'Directory-only removal deleted B registration' } if ((Get-ItemProperty ('HKCU:\' + $environmentKey)).Path -ne ($newCommand + ';C:\Windows')) { throw 'Directory-only removal changed B PATH' } 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 -ne $newCommand) { throw 'Directory-only removal changed B command owner' } $installPath = $newPath Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force $process = Start-Process $uninstaller -ArgumentList ('/S _?=' + $installPath) -PassThru -WindowStyle Hidden From c3bfc6ef85f332f6f5a4ddaeee3dac9559baa6b2 Mon Sep 17 00:00:00 2001 From: winewill Date: Mon, 16 Nov 2026 15:13:50 +0800 Subject: [PATCH 04/15] fix(desktop): simplify uninstall location confirmation --- apps/desktop/installer/locales/de_DE.json | 3 +-- apps/desktop/installer/locales/en_US.json | 3 +-- apps/desktop/installer/locales/es_ES.json | 3 +-- apps/desktop/installer/locales/fr_FR.json | 3 +-- apps/desktop/installer/locales/ja_JP.json | 3 +-- apps/desktop/installer/locales/pt_BR.json | 3 +-- apps/desktop/installer/locales/ru_RU.json | 3 +-- apps/desktop/installer/locales/zh_CN.json | 3 +-- apps/desktop/installer/uninstall-report.h | 4 ++-- apps/desktop/installer/uninstall.nsh | 2 +- 10 files changed, 11 insertions(+), 19 deletions(-) diff --git a/apps/desktop/installer/locales/de_DE.json b/apps/desktop/installer/locales/de_DE.json index d36ef30ff3..694cb0bb96 100644 --- a/apps/desktop/installer/locales/de_DE.json +++ b/apps/desktop/installer/locales/de_DE.json @@ -36,8 +36,7 @@ "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_DIRECTORY": "Ort des Deinstallationsprogramms:", - "INSTALLER_UNINSTALL_SCOPE": "Beim Fortfahren wird nur dieser Ordner bereinigt:", + "INSTALLER_UNINSTALL_SCOPE": "Wenn Sie fortfahren, wird das folgende Verzeichnis bereinigt:", "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.", diff --git a/apps/desktop/installer/locales/en_US.json b/apps/desktop/installer/locales/en_US.json index 7792810a52..f590fbc6fa 100644 --- a/apps/desktop/installer/locales/en_US.json +++ b/apps/desktop/installer/locales/en_US.json @@ -36,8 +36,7 @@ "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_DIRECTORY": "Uninstaller location:", - "INSTALLER_UNINSTALL_SCOPE": "Continuing will only clean", + "INSTALLER_UNINSTALL_SCOPE": "Continuing will clean the following directory:", "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.", diff --git a/apps/desktop/installer/locales/es_ES.json b/apps/desktop/installer/locales/es_ES.json index a13dd56594..acdccc2f4c 100644 --- a/apps/desktop/installer/locales/es_ES.json +++ b/apps/desktop/installer/locales/es_ES.json @@ -36,8 +36,7 @@ "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_DIRECTORY": "Ubicación del desinstalador:", - "INSTALLER_UNINSTALL_SCOPE": "Al continuar, solo se limpiará", + "INSTALLER_UNINSTALL_SCOPE": "Si continúa, se limpiará el siguiente directorio:", "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.", diff --git a/apps/desktop/installer/locales/fr_FR.json b/apps/desktop/installer/locales/fr_FR.json index a52079ede3..522b90853b 100644 --- a/apps/desktop/installer/locales/fr_FR.json +++ b/apps/desktop/installer/locales/fr_FR.json @@ -36,8 +36,7 @@ "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_DIRECTORY": "Emplacement du programme de désinstallation :", - "INSTALLER_UNINSTALL_SCOPE": "Continuer nettoiera uniquement", + "INSTALLER_UNINSTALL_SCOPE": "Si vous continuez, le répertoire suivant sera nettoyé :", "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.", diff --git a/apps/desktop/installer/locales/ja_JP.json b/apps/desktop/installer/locales/ja_JP.json index 712a7d2c21..61c10b0990 100644 --- a/apps/desktop/installer/locales/ja_JP.json +++ b/apps/desktop/installer/locales/ja_JP.json @@ -36,8 +36,7 @@ "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness が複数の場所にインストールされています", "INSTALLER_UNINSTALL_REGISTRATION": "一部の項目を削除できませんでした。詳細はレポートを保存して確認できます。", "INSTALLER_UNINSTALL_REGISTERED": "登録されているインストール先:", - "INSTALLER_UNINSTALL_DIRECTORY": "アンインストーラーの場所:", - "INSTALLER_UNINSTALL_SCOPE": "続行すると、次の場所のみを削除します:", + "INSTALLER_UNINSTALL_SCOPE": "続行すると、次のディレクトリを削除します:", "INSTALLER_UNINSTALL_CONTINUE": "アンインストール先の削除を続行", "INSTALLER_UNINSTALL_SAVE": "削除レポートを保存…", "INSTALLER_UNINSTALL_SAVE_FAILED": "レポートを保存できませんでした。別の保存先を選んでください。", diff --git a/apps/desktop/installer/locales/pt_BR.json b/apps/desktop/installer/locales/pt_BR.json index c076bc3dcb..b69b7f6926 100644 --- a/apps/desktop/installer/locales/pt_BR.json +++ b/apps/desktop/installer/locales/pt_BR.json @@ -36,8 +36,7 @@ "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_DIRECTORY": "Local do desinstalador:", - "INSTALLER_UNINSTALL_SCOPE": "Ao continuar, somente este local será limpo:", + "INSTALLER_UNINSTALL_SCOPE": "Ao continuar, o seguinte diretório será limpo:", "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.", diff --git a/apps/desktop/installer/locales/ru_RU.json b/apps/desktop/installer/locales/ru_RU.json index 8cf75546d7..004133c6d7 100644 --- a/apps/desktop/installer/locales/ru_RU.json +++ b/apps/desktop/installer/locales/ru_RU.json @@ -36,8 +36,7 @@ "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness установлен в нескольких местах", "INSTALLER_UNINSTALL_REGISTRATION": "Некоторые элементы не удалось очистить. Сохраните отчёт для просмотра подробностей.", "INSTALLER_UNINSTALL_REGISTERED": "Зарегистрированное расположение:", - "INSTALLER_UNINSTALL_DIRECTORY": "Расположение программы удаления:", - "INSTALLER_UNINSTALL_SCOPE": "При продолжении будет очищен только каталог", + "INSTALLER_UNINSTALL_SCOPE": "При продолжении будет очищен следующий каталог:", "INSTALLER_UNINSTALL_CONTINUE": "Продолжить очистку каталога удаления", "INSTALLER_UNINSTALL_SAVE": "Сохранить отчёт об очистке…", "INSTALLER_UNINSTALL_SAVE_FAILED": "Не удалось сохранить отчёт. Выберите другое расположение.", diff --git a/apps/desktop/installer/locales/zh_CN.json b/apps/desktop/installer/locales/zh_CN.json index 11803a2c45..56c049dccf 100644 --- a/apps/desktop/installer/locales/zh_CN.json +++ b/apps/desktop/installer/locales/zh_CN.json @@ -36,8 +36,7 @@ "INSTALLER_UNINSTALL_OWNER": "当前设备在多个位置安装了 DeepSeek Harness", "INSTALLER_UNINSTALL_REGISTRATION": "部分内容未能清理成功。你可以保存清理报告,查看具体项目和原因。", "INSTALLER_UNINSTALL_REGISTERED": "系统登记的安装位置:", - "INSTALLER_UNINSTALL_DIRECTORY": "卸载程序所在位置:", - "INSTALLER_UNINSTALL_SCOPE": "继续后仅清理", + "INSTALLER_UNINSTALL_SCOPE": "选择继续,将清理以下目录:", "INSTALLER_UNINSTALL_CONTINUE": "继续清理卸载目录", "INSTALLER_UNINSTALL_SAVE": "保存清理报告…", "INSTALLER_UNINSTALL_SAVE_FAILED": "报告未能保存,请重新选择保存位置。", diff --git a/apps/desktop/installer/uninstall-report.h b/apps/desktop/installer/uninstall-report.h index 8cc871ef30..a36f402c8c 100644 --- a/apps/desktop/installer/uninstall-report.h +++ b/apps/desktop/installer/uninstall-report.h @@ -292,8 +292,8 @@ extern "C" __declspec(dllexport) void __cdecl UninstallImport(uninstall_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 directoryLabel, LPCWSTR scopeLabel, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) { + LPCWSTR scopeLabel, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) { const std::wstring body = std::wstring(registeredLabel) + L"\r\n" + registered + L"\r\n\r\n" - + directoryLabel + L"\r\n" + directory + L"\r\n\r\n" + scopeLabel + L" " + directory; + + scopeLabel + L"\r\n" + directory; return uninstall_report::Show(parent, *session, 1, title, heading, body.c_str(), primary, save, failed); } diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index 6361a861ef..1b8e445307 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -16,7 +16,7 @@ Function un.ShowCleanup 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_DIRECTORY)", w "$(INSTALLER_UNINSTALL_SCOPE)", w "$(INSTALLER_UNINSTALL_CONTINUE)", w "$(INSTALLER_UNINSTALL_SAVE)", w "$(INSTALLER_UNINSTALL_SAVE_FAILED)") i.r0 ?c' + 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} From 45d6ae9ff2148af4ef51685b7d990ea41d7f937f Mon Sep 17 00:00:00 2001 From: winewill Date: Mon, 16 Nov 2026 18:25:53 +0800 Subject: [PATCH 05/15] fix(desktop): handle long paths during upgrade uninstall --- apps/desktop/packaging/README.i18n.yaml | 4 ++-- apps/desktop/packaging/README.md | 2 +- apps/desktop/packaging/README.zh.md | 2 +- apps/desktop/scripts/windows-directory-installer.d.mts | 2 +- apps/desktop/scripts/windows-directory-installer.mjs | 4 +++- apps/desktop/tests/windows-directory-installer.spec.ts | 4 ++++ apps/desktop/tests/windows-uninstall-smoke.ps1 | 4 ++++ 7 files changed, 16 insertions(+), 6 deletions(-) diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index c623d2fb8f..228f07da88 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -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 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index e2619f0237..d8aa7714ee 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -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-.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. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index cc6da7e75c..bdffd46c99 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -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`。如果恢复失败,安装器会清理未被占用的暂存文件并保留备份。上报此失败后,退出清理不再重试恢复。请保留报告所列的备份目录,并在重新安装前联系支持人员。静默安装保存相同的诊断,不显示弹窗。 diff --git a/apps/desktop/scripts/windows-directory-installer.d.mts b/apps/desktop/scripts/windows-directory-installer.d.mts index 5f4863d112..648cbf5106 100644 --- a/apps/desktop/scripts/windows-directory-installer.d.mts +++ b/apps/desktop/scripts/windows-directory-installer.d.mts @@ -17,7 +17,7 @@ export function directoryInstallerExits(source: string): string /** * Retain the original uninstall directory, reject another installation owner, and use native data cleanup. * @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 and upgrade rollback, without upstream RMDir data removal. */ export function directoryUninstaller(source: string): string diff --git a/apps/desktop/scripts/windows-directory-installer.mjs b/apps/desktop/scripts/windows-directory-installer.mjs index f0d037e606..64b1cd173d 100644 --- a/apps/desktop/scripts/windows-directory-installer.mjs +++ b/apps/desktop/scripts/windows-directory-installer.mjs @@ -87,10 +87,12 @@ export function installWindowsDirectoryInstaller() { /** * 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 and upgrade rollback, without upstream RMDir data removal. */ export function directoryUninstaller(source) { 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 diff --git a/apps/desktop/tests/windows-directory-installer.spec.ts b/apps/desktop/tests/windows-directory-installer.spec.ts index 466da27978..64417dcbe2 100644 --- a/apps/desktop/tests/windows-directory-installer.spec.ts +++ b/apps/desktop/tests/windows-directory-installer.spec.ts @@ -23,6 +23,10 @@ it('keeps data cleanup out of the upstream template while retaining application 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') diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index 7f1fdc67ab..de51dcd2b1 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -57,6 +57,10 @@ try { } finally { $setup.Dispose() } $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'))) { From c0336fbdae559c0c20b45a0cc544e4cea902d7a9 Mon Sep 17 00:00:00 2001 From: winewill Date: Tue, 17 Nov 2026 11:07:55 +0800 Subject: [PATCH 06/15] fix(desktop): clean old command registration on relocation --- apps/desktop/README.i18n.yaml | 4 ++-- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- .../scripts/windows-directory-installer.d.mts | 7 +++++++ .../scripts/windows-directory-installer.mjs | 14 +++++++++++++- .../tests/windows-directory-installer.spec.ts | 13 ++++++++++++- apps/desktop/tests/windows-uninstall-smoke.ps1 | 14 ++++++++++++++ 7 files changed, 50 insertions(+), 6 deletions(-) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index f0c0cb232e..9a040535b3 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: 379db0c315dc471f - zh: 62b27af9ee0c9c5f + en: d70a8ff2b9e5b14a + zh: 4f8dafcbc3d8eb4b /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 9accf68eab..7217e69647 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -267,7 +267,7 @@ 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 [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; 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 uninstall also removes the owned command PATH entry and its ownership values, and removes `dsh://` only when its command still names this installation. `--updated` preserves these registrations; `/KEEP_APP_DATA` alone does not. When the installation record points elsewhere, interactive uninstall offers to clean only the original directory, skipping shared data, shortcuts and registrations; silent uninstall refuses this choice. 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-.txt` when writable; interactive dialogs also offer Save cleanup report, and a failed save allows another location. 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. 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 uninstall also removes the owned command PATH entry and its ownership values, and removes `dsh://` only when its command still names this installation. `--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 offers to clean only the original directory, skipping shared data, shortcuts and registrations; silent uninstall refuses this choice. 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-.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 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. Compilation does not establish installed-uninstall behavior. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 7bfac1d76a..524bde70e0 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -267,7 +267,7 @@ 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 [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。手动卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。安装登记指向其他目录时,交互式卸载允许用户选择仅清理原卸载目录,跳过共享数据、快捷方式和注册信息;静默卸载拒绝代替用户作此选择。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 +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。手动卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载允许用户选择仅清理原卸载目录,跳过共享数据、快捷方式和注册信息;静默卸载拒绝代替用户作此选择。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译八种安装语言的独立夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 、`DSH_HOME` 位于 Electron 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/scripts/windows-directory-installer.d.mts b/apps/desktop/scripts/windows-directory-installer.d.mts index 648cbf5106..873d8db1ac 100644 --- a/apps/desktop/scripts/windows-directory-installer.d.mts +++ b/apps/desktop/scripts/windows-directory-installer.d.mts @@ -14,6 +14,13 @@ export function directoryInstallSection(source: string): string */ export function directoryInstallerExits(source: string): string +/** + * 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, reject another installation owner, and use native data cleanup. * @param source - Pinned upstream uninstaller source. diff --git a/apps/desktop/scripts/windows-directory-installer.mjs b/apps/desktop/scripts/windows-directory-installer.mjs index 64b1cd173d..eeda6115b0 100644 --- a/apps/desktop/scripts/windows-directory-installer.mjs +++ b/apps/desktop/scripts/windows-directory-installer.mjs @@ -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') diff --git a/apps/desktop/tests/windows-directory-installer.spec.ts b/apps/desktop/tests/windows-directory-installer.spec.ts index 64417dcbe2..fd0d43c715 100644 --- a/apps/desktop/tests/windows-directory-installer.spec.ts +++ b/apps/desktop/tests/windows-directory-installer.spec.ts @@ -3,12 +3,23 @@ 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) diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index de51dcd2b1..b850d6f53f 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -202,9 +202,23 @@ try { $setup = Start-Process $Installer -ArgumentList ('/S /D=' + $installPath) -PassThru -WindowStyle Hidden try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover A setup failed' } } finally { $setup.Dispose() } 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' $setup = Start-Process $Installer -ArgumentList ('/S /D=' + $newPath) -PassThru -WindowStyle Hidden try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover B setup failed' } } finally { $setup.Dispose() } + 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() } From fcb105b77841bf6adf03e3e5bfbb23d792880463 Mon Sep 17 00:00:00 2001 From: winewill Date: Tue, 17 Nov 2026 16:47:50 +0800 Subject: [PATCH 07/15] fix(desktop): remove orphan PATH after uninstall --- apps/desktop/README.i18n.yaml | 4 ++-- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/installer/uninstall.nsh | 22 +++++++++++++++++-- apps/desktop/scripts/command-path.ps1 | 20 ++++++++++++++++- .../scripts/uninstall-registration.ps1 | 17 ++++++++++---- .../tests/expected/windows-uninstall.json | 2 ++ apps/desktop/tests/fixtures/command-path.ps1 | 22 +++++++++++++++++++ .../desktop/tests/windows-uninstall-smoke.ps1 | 14 ++++++++++-- 9 files changed, 92 insertions(+), 13 deletions(-) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 9a040535b3..8632539828 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: d70a8ff2b9e5b14a - zh: 4f8dafcbc3d8eb4b + en: 73bc1636e2a060c7 + zh: 0c6ca0c458ae6831 /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 7217e69647..829b8ae0e7 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -267,7 +267,7 @@ 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 [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; 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 uninstall also removes the owned command PATH entry and its ownership values, and removes `dsh://` only when its command still names this installation. `--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 offers to clean only the original directory, skipping shared data, shortcuts and registrations; silent uninstall refuses this choice. 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-.txt` when writable; interactive dialogs also offer Save cleanup report, and a failed save allows another location. 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. 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 removes `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 offers to clean only the original directory, skipping shared data, shortcuts and registrations; silent uninstall refuses this choice. 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-.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 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. Compilation does not establish installed-uninstall behavior. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 524bde70e0..fdef5b9bc8 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -267,7 +267,7 @@ 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 [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。手动卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载允许用户选择仅清理原卸载目录,跳过共享数据、快捷方式和注册信息;静默卸载拒绝代替用户作此选择。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 +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。手动和静默卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。命令所有权缺失时,额外清理只移除匹配本安装 CLI 目录的 PATH 条目,并先确认安装目录已不存在;目录仍存在或检查失败时保留条目并生成清理报告。其他命令安装保持不变。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载允许用户选择仅清理原卸载目录,跳过共享数据、快捷方式和注册信息;静默卸载拒绝代替用户作此选择。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译八种安装语言的独立夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 、`DSH_HOME` 位于 Electron 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index 1b8e445307..40bdd144e2 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -10,6 +10,9 @@ 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' @@ -89,7 +92,12 @@ Function un.FinishCleanup Return ${EndIf} System::Call '$PLUGINSDIR\window-frame.dll::UninstallFinish(p $UnSession, w "$INSTDIR", w "${UNINSTALL_FILENAME}") i.r0 ?c' - ${If} $0 != 0 + 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)" @@ -161,14 +169,24 @@ Function un.CleanRegistration ${If} $UnDirectoryOnly == 1 Return ${EndIf} + Delete "$PLUGINSDIR\unowned-path" + StrCpy $UnRegistrationArguments "" + 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" - 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}"' + 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 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} diff --git a/apps/desktop/scripts/command-path.ps1 b/apps/desktop/scripts/command-path.ps1 index 4e1da931a3..3b4807cc92 100644 --- a/apps/desktop/scripts/command-path.ps1 +++ b/apps/desktop/scripts/command-path.ps1 @@ -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) { diff --git a/apps/desktop/scripts/uninstall-registration.ps1 b/apps/desktop/scripts/uninstall-registration.ps1 index 37b93b2ec9..c467396566 100644 --- a/apps/desktop/scripts/uninstall-registration.ps1 +++ b/apps/desktop/scripts/uninstall-registration.ps1 @@ -5,7 +5,9 @@ param([Parameter(Mandatory)][string]$Directory, [string]$OwnerKey = 'Software\DeepSeekHarness\Command', [string]$ProtocolKey = 'Software\Classes\dsh', [Parameter(Mandatory)][string]$ReportPath, - [string]$MutexName) + [string]$MutexName, + [switch]$UnownedOnly, + [string]$UnownedMarker) $ErrorActionPreference = 'Stop' . (Join-Path $PSScriptRoot 'command-path.ps1') $failures = [Collections.Generic.List[string]]::new() @@ -17,14 +19,21 @@ try { $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 ($state.managed) { + 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)") } -try { +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() } } @@ -34,7 +43,7 @@ try { } } catch { $failures.Add("[unverified] Remove protocol registration`r`nHKCU\$ProtocolKey`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)") -} +} } if ($failures.Count) { [IO.File]::WriteAllText($ReportPath, ($failures -join "`r`n`r`n"), [Text.UTF8Encoding]::new($true)) exit 1 diff --git a/apps/desktop/tests/expected/windows-uninstall.json b/apps/desktop/tests/expected/windows-uninstall.json index 03a1ccdf22..90da9852ed 100644 --- a/apps/desktop/tests/expected/windows-uninstall.json +++ b/apps/desktop/tests/expected/windows-uninstall.json @@ -2,6 +2,8 @@ "cases": [ "interactive", "silent", + "unowned", + "owned-retained", "upgrade", "replaced", "home-inside", diff --git a/apps/desktop/tests/fixtures/command-path.ps1 b/apps/desktop/tests/fixtures/command-path.ps1 index 82eb4e8a16..3c5fd1dff1 100644 --- a/apps/desktop/tests/fixtures/command-path.ps1 +++ b/apps/desktop/tests/fixtures/command-path.ps1 @@ -115,6 +115,28 @@ try { 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($keyRoot, $false) diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index b850d6f53f..37b295f814 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -76,11 +76,19 @@ try { 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 $installPath ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() } $launchUninstaller = $uninstaller $arguments = '_?=' + $installPath - if ($mode -in @('silent', 'home-inside', 'registration-error', 'main-locked', 'auxiliary-locked', 'unsafe-root')) { $arguments = '/S ' + $arguments } + if ($mode -in @('silent', 'unowned', 'owned-retained', 'home-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') { Set-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation -Value ($installPath + '\') @@ -194,7 +202,9 @@ try { $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 - if ($mode -notin @('registration-error', 'save-report') -and ($path.Contains($commandDirectory) -ne $integrationsRetained -or -not $path.Contains('C:\Windows'))) { throw "PATH cleanup failed: $mode" } + $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 ($mode -eq 'upgrade')) { throw "Protocol cleanup failed: $mode" } Write-Output "passed: $mode" } From 776844563ff6a88b03892bba3125423c7bcdb212 Mon Sep 17 00:00:00 2001 From: winewill Date: Wed, 18 Nov 2026 10:31:00 +0800 Subject: [PATCH 08/15] fix(desktop): require explicit uninstall registry keys --- apps/desktop/scripts/uninstall-registration.ps1 | 6 +++--- apps/desktop/scripts/windows-directory-installer.d.mts | 4 ++-- apps/desktop/scripts/windows-directory-installer.mjs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/desktop/scripts/uninstall-registration.ps1 b/apps/desktop/scripts/uninstall-registration.ps1 index c467396566..7604ff7db7 100644 --- a/apps/desktop/scripts/uninstall-registration.ps1 +++ b/apps/desktop/scripts/uninstall-registration.ps1 @@ -1,9 +1,9 @@ <# Remove only owned registrations; independently failed operations leave a diagnostic report. #> param([Parameter(Mandatory)][string]$Directory, [string]$ExecutableName = 'DeepSeek Harness.exe', - [string]$EnvironmentKey = 'Environment', - [string]$OwnerKey = 'Software\DeepSeekHarness\Command', - [string]$ProtocolKey = 'Software\Classes\dsh', + [Parameter(Mandatory)][string]$EnvironmentKey, + [Parameter(Mandatory)][string]$OwnerKey, + [Parameter(Mandatory)][string]$ProtocolKey, [Parameter(Mandatory)][string]$ReportPath, [string]$MutexName, [switch]$UnownedOnly, diff --git a/apps/desktop/scripts/windows-directory-installer.d.mts b/apps/desktop/scripts/windows-directory-installer.d.mts index 873d8db1ac..8038b103de 100644 --- a/apps/desktop/scripts/windows-directory-installer.d.mts +++ b/apps/desktop/scripts/windows-directory-installer.d.mts @@ -22,9 +22,9 @@ export function directoryInstallerExits(source: string): string export function directoryInstallUtil(source: string): string /** - * Retain the original uninstall directory, reject another installation owner, and use native data cleanup. + * Retain the original uninstall directory and bypass shared cleanup for directory-only removal. * @param source - Pinned upstream uninstaller source. - * @returns Uninstaller with long-path removal and upgrade rollback, without 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 diff --git a/apps/desktop/scripts/windows-directory-installer.mjs b/apps/desktop/scripts/windows-directory-installer.mjs index eeda6115b0..45c890712c 100644 --- a/apps/desktop/scripts/windows-directory-installer.mjs +++ b/apps/desktop/scripts/windows-directory-installer.mjs @@ -99,7 +99,7 @@ export function installWindowsDirectoryInstaller() { /** * 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 removal and upgrade rollback, without 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) { let normalized = source.replaceAll('\r\n', '\n') From 60c5461ea2028cf4f5480935f0fb7529c1a070a0 Mon Sep 17 00:00:00 2001 From: winewill Date: Wed, 18 Nov 2026 11:16:02 +0800 Subject: [PATCH 09/15] fix(desktop): clean attributable registrations without install location --- apps/desktop/installer/uninstall.nsh | 30 +++++++------------ apps/desktop/tests/command-path.spec.ts | 2 ++ .../tests/expected/windows-uninstall.json | 2 ++ apps/desktop/tests/fixtures/command-path.ps1 | 15 ++++++++-- .../tests/fixtures/register-test-protocol.cjs | 4 +++ .../tests/windows-directory-installer.spec.ts | 1 + .../desktop/tests/windows-uninstall-smoke.ps1 | 16 ++++++---- 7 files changed, 42 insertions(+), 28 deletions(-) create mode 100644 apps/desktop/tests/fixtures/register-test-protocol.cjs diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index 40bdd144e2..880efcaeb7 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -144,30 +144,22 @@ FunctionEnd !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.RefreshOwnership - ${If} ${isUpdated} - Return - ${EndIf} - ReadRegStr $0 SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation - ${If} $0 == "" - StrCpy $UnDirectoryOnly 1 - Return - ${EndIf} - GetFullPathName $0 "$0\." - GetFullPathName $1 "$INSTDIR\." - ${If} $0 != $1 - StrCpy $UnDirectoryOnly 1 - ${EndIf} -FunctionEnd - Function un.CleanRegistration ${If} ${isUpdated} ${OrIf} $UnDirectoryOnly == 1 Return ${EndIf} - Call un.RefreshOwnership - ${If} $UnDirectoryOnly == 1 - Return + ReadRegStr $0 SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation + ${If} $0 == "" + ; Only the command owner and protocol target can identify this installation. + StrCpy $UnDirectoryOnly 1 + ${Else} + GetFullPathName $0 "$0\." + GetFullPathName $1 "$INSTDIR\." + ${If} $0 != $1 + StrCpy $UnDirectoryOnly 1 + Return + ${EndIf} ${EndIf} Delete "$PLUGINSDIR\unowned-path" StrCpy $UnRegistrationArguments "" diff --git a/apps/desktop/tests/command-path.spec.ts b/apps/desktop/tests/command-path.spec.ts index 0b6612fdd0..b528b31f2b 100644 --- a/apps/desktop/tests/command-path.spec.ts +++ b/apps/desktop/tests/command-path.spec.ts @@ -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') diff --git a/apps/desktop/tests/expected/windows-uninstall.json b/apps/desktop/tests/expected/windows-uninstall.json index 90da9852ed..635208dc97 100644 --- a/apps/desktop/tests/expected/windows-uninstall.json +++ b/apps/desktop/tests/expected/windows-uninstall.json @@ -3,6 +3,8 @@ "interactive", "silent", "unowned", + "missing-location", + "missing-location-foreign", "owned-retained", "upgrade", "replaced", diff --git a/apps/desktop/tests/fixtures/command-path.ps1 b/apps/desktop/tests/fixtures/command-path.ps1 index 3c5fd1dff1..699289bbc7 100644 --- a/apps/desktop/tests/fixtures/command-path.ps1 +++ b/apps/desktop/tests/fixtures/command-path.ps1 @@ -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 @@ -109,8 +109,16 @@ try { $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) - $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($protocolKey + '\shell\open\command', $true) - try { $key.SetValue('', '"' + (Join-Path $app 'DeepSeek Harness.exe') + '" "%1"') } finally { $key.Dispose() } + $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' @@ -139,5 +147,6 @@ try { 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) } diff --git a/apps/desktop/tests/fixtures/register-test-protocol.cjs b/apps/desktop/tests/fixtures/register-test-protocol.cjs new file mode 100644 index 0000000000..59c80ad362 --- /dev/null +++ b/apps/desktop/tests/fixtures/register-test-protocol.cjs @@ -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)) diff --git a/apps/desktop/tests/windows-directory-installer.spec.ts b/apps/desktop/tests/windows-directory-installer.spec.ts index fd0d43c715..ccbd392c8d 100644 --- a/apps/desktop/tests/windows-directory-installer.spec.ts +++ b/apps/desktop/tests/windows-directory-installer.spec.ts @@ -30,6 +30,7 @@ it('keeps data cleanup out of the upstream template while retaining application 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) diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index 37b295f814..3880c90cbe 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -71,7 +71,11 @@ 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 - $commandDirectory = Join-Path $installPath 'resources\runtime\cli\bin' + $missingLocation = $mode -in @('missing-location', 'missing-location-foreign') + $foreign = $mode -eq 'missing-location-foreign' + if ($missingLocation) { Remove-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation } + $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) @@ -85,10 +89,10 @@ try { 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 $installPath ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() } + try { $key.SetValue('', '"' + (Join-Path $integrationRoot ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() } $launchUninstaller = $uninstaller $arguments = '_?=' + $installPath - if ($mode -in @('silent', 'unowned', 'owned-retained', 'home-inside', 'registration-error', 'main-locked', 'auxiliary-locked', 'unsafe-root')) { $arguments = '/S ' + $arguments } + if ($mode -in @('silent', 'missing-location', 'missing-location-foreign', 'unowned', 'owned-retained', 'home-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') { Set-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation -Value ($installPath + '\') @@ -189,7 +193,7 @@ try { [IO.Directory]::Delete($installPath) } Wait-Exit - $retained = $mode -in @('upgrade', 'replaced', 'self-copy') + $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' if ([IO.File]::ReadAllText((Join-Path $externalPath 'keep.txt')) -ne 'outside data root') { throw 'Cleanup followed a junction into a project' } @@ -198,14 +202,14 @@ try { 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 = $mode -in @('upgrade', 'registration-error', 'save-report') + $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 ($mode -eq 'upgrade')) { throw "Protocol cleanup failed: $mode" } + if ((Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) -ne ($foreign -or $mode -eq 'upgrade')) { throw "Protocol cleanup failed: $mode" } Write-Output "passed: $mode" } # Real replacement publishes B after the old A uninstaller has been retained. From 2a840de9d0931ede867b593d892f31389a5f8277 Mon Sep 17 00:00:00 2001 From: winewill Date: Wed, 18 Nov 2026 15:16:47 +0800 Subject: [PATCH 10/15] fix(desktop): clean Windows entries that still target the removed installation --- apps/desktop/README.i18n.yaml | 4 +-- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/installer/locales/de_DE.json | 2 +- apps/desktop/installer/locales/en_US.json | 2 +- apps/desktop/installer/locales/es_ES.json | 2 +- apps/desktop/installer/locales/fr_FR.json | 2 +- apps/desktop/installer/locales/ja_JP.json | 2 +- apps/desktop/installer/locales/pt_BR.json | 2 +- apps/desktop/installer/locales/ru_RU.json | 2 +- apps/desktop/installer/locales/zh_CN.json | 2 +- apps/desktop/installer/uninstall.nsh | 22 +++++++++++++-- .../scripts/uninstall-registration.ps1 | 16 ++++++++++- .../desktop/tests/windows-uninstall-smoke.ps1 | 28 ++++++++++++++++--- 14 files changed, 70 insertions(+), 20 deletions(-) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 8632539828..7f3c514245 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: 73bc1636e2a060c7 - zh: 0c6ca0c458ae6831 + en: f4509d2a92e7af75 + zh: 67e080e2906d4dcc /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 829b8ae0e7..536299dab0 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -267,7 +267,7 @@ 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 [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; 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 removes `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 offers to clean only the original directory, skipping shared data, shortcuts and registrations; silent uninstall refuses this choice. 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-.txt` when writable; interactive dialogs also offer Save cleanup report, and a failed save allows another location. 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. 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-.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 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. Compilation does not establish installed-uninstall behavior. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index fdef5b9bc8..27df210074 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -267,7 +267,7 @@ 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 [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。手动和静默卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。命令所有权缺失时,额外清理只移除匹配本安装 CLI 目录的 PATH 条目,并先确认安装目录已不存在;目录仍存在或检查失败时保留条目并生成清理报告。其他命令安装保持不变。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载允许用户选择仅清理原卸载目录,跳过共享数据、快捷方式和注册信息;静默卸载拒绝代替用户作此选择。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 +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。手动和静默卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。命令所有权缺失时,额外清理只移除匹配本安装 CLI 目录的 PATH 条目,并先确认安装目录已不存在;目录仍存在或检查失败时保留条目并生成清理报告。其他命令安装保持不变。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载请求确认,静默卸载停止。安装地址缺失或指向其他位置时,卸载会清理仍指向本目录的命令、协议、快捷方式和 Windows 卸载入口,保留共享用户数据和系统外壳设置。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译八种安装语言的独立夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 、`DSH_HOME` 位于 Electron 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/locales/de_DE.json b/apps/desktop/installer/locales/de_DE.json index 694cb0bb96..aefac91fbb 100644 --- a/apps/desktop/installer/locales/de_DE.json +++ b/apps/desktop/installer/locales/de_DE.json @@ -36,7 +36,7 @@ "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": "Wenn Sie fortfahren, wird das folgende Verzeichnis bereinigt:", + "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.", diff --git a/apps/desktop/installer/locales/en_US.json b/apps/desktop/installer/locales/en_US.json index f590fbc6fa..46473f800e 100644 --- a/apps/desktop/installer/locales/en_US.json +++ b/apps/desktop/installer/locales/en_US.json @@ -36,7 +36,7 @@ "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 will clean the following directory:", + "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.", diff --git a/apps/desktop/installer/locales/es_ES.json b/apps/desktop/installer/locales/es_ES.json index acdccc2f4c..9f267f21dc 100644 --- a/apps/desktop/installer/locales/es_ES.json +++ b/apps/desktop/installer/locales/es_ES.json @@ -36,7 +36,7 @@ "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": "Si continúa, se limpiará el siguiente directorio:", + "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.", diff --git a/apps/desktop/installer/locales/fr_FR.json b/apps/desktop/installer/locales/fr_FR.json index 522b90853b..40936f4bbf 100644 --- a/apps/desktop/installer/locales/fr_FR.json +++ b/apps/desktop/installer/locales/fr_FR.json @@ -36,7 +36,7 @@ "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": "Si vous continuez, le répertoire suivant sera nettoyé :", + "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.", diff --git a/apps/desktop/installer/locales/ja_JP.json b/apps/desktop/installer/locales/ja_JP.json index 61c10b0990..785bafdd7b 100644 --- a/apps/desktop/installer/locales/ja_JP.json +++ b/apps/desktop/installer/locales/ja_JP.json @@ -36,7 +36,7 @@ "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness が複数の場所にインストールされています", "INSTALLER_UNINSTALL_REGISTRATION": "一部の項目を削除できませんでした。詳細はレポートを保存して確認できます。", "INSTALLER_UNINSTALL_REGISTERED": "登録されているインストール先:", - "INSTALLER_UNINSTALL_SCOPE": "続行すると、次のディレクトリを削除します:", + "INSTALLER_UNINSTALL_SCOPE": "続行すると、次のフォルダーと、それを参照するコマンド、ショートカット、登録情報を削除します:", "INSTALLER_UNINSTALL_CONTINUE": "アンインストール先の削除を続行", "INSTALLER_UNINSTALL_SAVE": "削除レポートを保存…", "INSTALLER_UNINSTALL_SAVE_FAILED": "レポートを保存できませんでした。別の保存先を選んでください。", diff --git a/apps/desktop/installer/locales/pt_BR.json b/apps/desktop/installer/locales/pt_BR.json index b69b7f6926..90b3ed8b8e 100644 --- a/apps/desktop/installer/locales/pt_BR.json +++ b/apps/desktop/installer/locales/pt_BR.json @@ -36,7 +36,7 @@ "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": "Ao continuar, o seguinte diretório será limpo:", + "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.", diff --git a/apps/desktop/installer/locales/ru_RU.json b/apps/desktop/installer/locales/ru_RU.json index 004133c6d7..a1f9957dfd 100644 --- a/apps/desktop/installer/locales/ru_RU.json +++ b/apps/desktop/installer/locales/ru_RU.json @@ -36,7 +36,7 @@ "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness установлен в нескольких местах", "INSTALLER_UNINSTALL_REGISTRATION": "Некоторые элементы не удалось очистить. Сохраните отчёт для просмотра подробностей.", "INSTALLER_UNINSTALL_REGISTERED": "Зарегистрированное расположение:", - "INSTALLER_UNINSTALL_SCOPE": "При продолжении будет очищен следующий каталог:", + "INSTALLER_UNINSTALL_SCOPE": "Будут удалены этот каталог и указывающие на него команды, ярлыки и записи:", "INSTALLER_UNINSTALL_CONTINUE": "Продолжить очистку каталога удаления", "INSTALLER_UNINSTALL_SAVE": "Сохранить отчёт об очистке…", "INSTALLER_UNINSTALL_SAVE_FAILED": "Не удалось сохранить отчёт. Выберите другое расположение.", diff --git a/apps/desktop/installer/locales/zh_CN.json b/apps/desktop/installer/locales/zh_CN.json index 56c049dccf..2f6a9bbec0 100644 --- a/apps/desktop/installer/locales/zh_CN.json +++ b/apps/desktop/installer/locales/zh_CN.json @@ -36,7 +36,7 @@ "INSTALLER_UNINSTALL_OWNER": "当前设备在多个位置安装了 DeepSeek Harness", "INSTALLER_UNINSTALL_REGISTRATION": "部分内容未能清理成功。你可以保存清理报告,查看具体项目和原因。", "INSTALLER_UNINSTALL_REGISTERED": "系统登记的安装位置:", - "INSTALLER_UNINSTALL_SCOPE": "选择继续,将清理以下目录:", + "INSTALLER_UNINSTALL_SCOPE": "选择继续,将清理以下目录,以及仍指向它的命令、快捷方式和系统登记:", "INSTALLER_UNINSTALL_CONTINUE": "继续清理卸载目录", "INSTALLER_UNINSTALL_SAVE": "保存清理报告…", "INSTALLER_UNINSTALL_SAVE_FAILED": "报告未能保存,请重新选择保存位置。", diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index 880efcaeb7..b61fa56111 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -144,25 +144,41 @@ FunctionEnd !define /ifndef DSH_COMMAND_OWNER_KEY "Software\DeepSeekHarness\Command" !define /ifndef DSH_PROTOCOL_KEY "Software\Classes\dsh" !define /ifndef DSH_COMMAND_MUTEX "default" +!macro unRemoveOwnedUninstallEntry KEY + ReadRegStr $0 SHELL_CONTEXT "${KEY}" UninstallString + ${If} $0 == '"$INSTDIR\${UNINSTALL_FILENAME}" /currentuser' + ClearErrors + DeleteRegKey SHELL_CONTEXT "${KEY}" + ${If} ${Errors} + System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "[unverified] Delete uninstall entry: ${KEY}") ?c' + ${EndIf} + ${EndIf} +!macroend + Function un.CleanRegistration ${If} ${isUpdated} - ${OrIf} $UnDirectoryOnly == 1 Return ${EndIf} ReadRegStr $0 SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation ${If} $0 == "" - ; Only the command owner and protocol target can identify this installation. + ; 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 - Return ${EndIf} ${EndIf} Delete "$PLUGINSDIR\unowned-path" StrCpy $UnRegistrationArguments "" + ${If} $UnDirectoryOnly == 1 + !insertmacro unRemoveOwnedUninstallEntry "${UNINSTALL_REGISTRY_KEY}" + !ifdef UNINSTALL_REGISTRY_KEY_2 + !insertmacro unRemoveOwnedUninstallEntry "${UNINSTALL_REGISTRY_KEY_2}" + !endif + StrCpy $UnRegistrationArguments '-DesktopLink "$oldDesktopLink" -StartMenuLink "$oldStartMenuLink"' + ${EndIf} Call un.RunRegistrationCleanup IfFileExists "$PLUGINSDIR\unowned-path" 0 +2 StrCpy $UnRegistrationEligible 1 diff --git a/apps/desktop/scripts/uninstall-registration.ps1 b/apps/desktop/scripts/uninstall-registration.ps1 index 7604ff7db7..267347f79b 100644 --- a/apps/desktop/scripts/uninstall-registration.ps1 +++ b/apps/desktop/scripts/uninstall-registration.ps1 @@ -7,7 +7,9 @@ param([Parameter(Mandatory)][string]$Directory, [Parameter(Mandatory)][string]$ReportPath, [string]$MutexName, [switch]$UnownedOnly, - [string]$UnownedMarker) + [string]$UnownedMarker, + [string]$DesktopLink, + [string]$StartMenuLink) $ErrorActionPreference = 'Stop' . (Join-Path $PSScriptRoot 'command-path.ps1') $failures = [Collections.Generic.List[string]]::new() @@ -44,6 +46,18 @@ if (-not $UnownedOnly) { try { } catch { $failures.Add("[unverified] Remove protocol registration`r`nHKCU\$ProtocolKey`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 diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index 3880c90cbe..bc51642f34 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -74,6 +74,14 @@ try { $missingLocation = $mode -in @('missing-location', '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 + $desktopLink = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) ($ProductName + '.lnk') + if ($missingLocation) { + $shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($desktopLink) + $shortcut.TargetPath = Join-Path $installPath ($ProductName + '.exe') + $shortcut.Save() + if (-not (Test-Path -LiteralPath $desktopLink) -or (Get-ItemProperty $arpKey).UninstallString -notlike ('*' + $installPath + '*')) { 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) @@ -210,6 +218,7 @@ try { 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 $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. @@ -258,6 +267,14 @@ try { $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 Copy-Item -LiteralPath $newPath -Destination $installPath -Recurse $process = Start-Process $uninstaller -ArgumentList ('/currentuser _?=' + $installPath) -PassThru $welcome = Wait-Text $copy.welcome @@ -272,16 +289,19 @@ try { 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 ($newCommand + ';C:\Windows')) { throw 'Directory-only removal changed B PATH' } + 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 -ne $newCommand) { throw 'Directory-only removal changed B command owner' } + 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 - Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force - $process = Start-Process $uninstaller -ArgumentList ('/S _?=' + $installPath) -PassThru -WindowStyle Hidden + 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 Write-Output 'passed: installation takeover' } finally { From b2f8b99d212cc9ca162488bf5c8276ebbea2c9a4 Mon Sep 17 00:00:00 2001 From: winewill Date: Wed, 18 Nov 2026 16:12:40 +0800 Subject: [PATCH 11/15] fix(desktop): normalize uninstall targets and report registry read failures --- apps/desktop/installer/uninstall.nsh | 16 ++---------- .../scripts/uninstall-registration.ps1 | 25 ++++++++++++++++++- .../desktop/tests/windows-uninstall-smoke.ps1 | 15 ++++++++++- 3 files changed, 40 insertions(+), 16 deletions(-) diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index b61fa56111..f61af3884b 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -144,17 +144,6 @@ FunctionEnd !define /ifndef DSH_COMMAND_OWNER_KEY "Software\DeepSeekHarness\Command" !define /ifndef DSH_PROTOCOL_KEY "Software\Classes\dsh" !define /ifndef DSH_COMMAND_MUTEX "default" -!macro unRemoveOwnedUninstallEntry KEY - ReadRegStr $0 SHELL_CONTEXT "${KEY}" UninstallString - ${If} $0 == '"$INSTDIR\${UNINSTALL_FILENAME}" /currentuser' - ClearErrors - DeleteRegKey SHELL_CONTEXT "${KEY}" - ${If} ${Errors} - System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "[unverified] Delete uninstall entry: ${KEY}") ?c' - ${EndIf} - ${EndIf} -!macroend - Function un.CleanRegistration ${If} ${isUpdated} Return @@ -173,11 +162,10 @@ Function un.CleanRegistration Delete "$PLUGINSDIR\unowned-path" StrCpy $UnRegistrationArguments "" ${If} $UnDirectoryOnly == 1 - !insertmacro unRemoveOwnedUninstallEntry "${UNINSTALL_REGISTRY_KEY}" + StrCpy $UnRegistrationArguments '-DesktopLink "$oldDesktopLink" -StartMenuLink "$oldStartMenuLink" -UninstallKey "${UNINSTALL_REGISTRY_KEY}" -UninstallerName "${UNINSTALL_FILENAME}"' !ifdef UNINSTALL_REGISTRY_KEY_2 - !insertmacro unRemoveOwnedUninstallEntry "${UNINSTALL_REGISTRY_KEY_2}" + StrCpy $UnRegistrationArguments '$UnRegistrationArguments -LegacyUninstallKey "${UNINSTALL_REGISTRY_KEY_2}"' !endif - StrCpy $UnRegistrationArguments '-DesktopLink "$oldDesktopLink" -StartMenuLink "$oldStartMenuLink"' ${EndIf} Call un.RunRegistrationCleanup IfFileExists "$PLUGINSDIR\unowned-path" 0 +2 diff --git a/apps/desktop/scripts/uninstall-registration.ps1 b/apps/desktop/scripts/uninstall-registration.ps1 index 267347f79b..6dd01815d6 100644 --- a/apps/desktop/scripts/uninstall-registration.ps1 +++ b/apps/desktop/scripts/uninstall-registration.ps1 @@ -9,7 +9,10 @@ param([Parameter(Mandatory)][string]$Directory, [switch]$UnownedOnly, [string]$UnownedMarker, [string]$DesktopLink, - [string]$StartMenuLink) + [string]$StartMenuLink, + [string]$UninstallKey, + [string]$LegacyUninstallKey, + [string]$UninstallerName) $ErrorActionPreference = 'Stop' . (Join-Path $PSScriptRoot 'command-path.ps1') $failures = [Collections.Generic.List[string]]::new() @@ -46,6 +49,26 @@ if (-not $UnownedOnly) { try { } 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 { diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index bc51642f34..77fbc55297 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -75,8 +75,15 @@ try { $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 + '\.\') + Set-ItemProperty $arpKey UninstallString $alternateCommand + } $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() @@ -218,7 +225,7 @@ try { 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 $arpKey))) { throw 'Missing location left an A shortcut or uninstall entry' } + 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. @@ -303,6 +310,12 @@ try { 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 { if ($held) { $held.Dispose() } From 2e69a944d9ab0efdb73cfd65719f3e47f4c7abf3 Mon Sep 17 00:00:00 2001 From: winewill Date: Wed, 18 Nov 2026 16:45:37 +0800 Subject: [PATCH 12/15] fix(desktop): include all uncertain uninstall targets in fallback reports --- apps/desktop/installer/uninstall.nsh | 7 +++++++ apps/desktop/tests/expected/windows-uninstall.json | 1 + apps/desktop/tests/windows-uninstall-smoke.ps1 | 13 ++++++++++--- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index f61af3884b..714e7826c7 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -184,6 +184,13 @@ Function un.RunRegistrationCleanup ${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 diff --git a/apps/desktop/tests/expected/windows-uninstall.json b/apps/desktop/tests/expected/windows-uninstall.json index 635208dc97..148db0ed5c 100644 --- a/apps/desktop/tests/expected/windows-uninstall.json +++ b/apps/desktop/tests/expected/windows-uninstall.json @@ -4,6 +4,7 @@ "silent", "unowned", "missing-location", + "missing-location-short", "missing-location-foreign", "owned-retained", "upgrade", diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index 77fbc55297..db12575c5c 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -71,15 +71,22 @@ 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-foreign') + $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) { @@ -87,7 +94,7 @@ try { $shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($desktopLink) $shortcut.TargetPath = Join-Path $installPath ($ProductName + '.exe') $shortcut.Save() - if (-not (Test-Path -LiteralPath $desktopLink) -or (Get-ItemProperty $arpKey).UninstallString -notlike ('*' + $installPath + '*')) { throw 'Missing A uninstall fixtures' } + 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' @@ -107,7 +114,7 @@ try { try { $key.SetValue('', '"' + (Join-Path $integrationRoot ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() } $launchUninstaller = $uninstaller $arguments = '_?=' + $installPath - if ($mode -in @('silent', 'missing-location', 'missing-location-foreign', 'unowned', 'owned-retained', 'home-inside', 'registration-error', 'main-locked', 'auxiliary-locked', 'unsafe-root')) { $arguments = '/S ' + $arguments } + if ($mode -in @('silent', 'missing-location', 'missing-location-short', 'missing-location-foreign', 'unowned', 'owned-retained', 'home-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') { Set-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation -Value ($installPath + '\') From 9220db6c97feaeabfa6d7cd8cc4cf98abdcb4d7d Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 19 Nov 2026 11:05:32 +0800 Subject: [PATCH 13/15] Fix uninstall home path normalization and cleanup diagnostics --- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/installer/uninstall-data.h | 25 ++++++++++++- apps/desktop/installer/uninstall-report.h | 8 +++- apps/desktop/installer/uninstall.nsh | 2 + .../tests/expected/windows-uninstall.json | 3 ++ apps/desktop/tests/windows-uninstall-data.cpp | 37 +++++++++++++++++++ .../desktop/tests/windows-uninstall-smoke.ps1 | 35 ++++++++++++++++-- 9 files changed, 107 insertions(+), 11 deletions(-) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 20aff07a4c..fd0476350c 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: 538f0a8158d3c61e - zh: 0a4a1a37f8d511cd + en: f816b98b0fde9d08 + zh: b69facb3b5fbe828 /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index bff2f7dc91..f4c6f5b7f8 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -267,7 +267,7 @@ 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 [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; 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-.txt` when writable; interactive dialogs also offer Save cleanup report, and a failed save allows another location. 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; relative paths remain unverifiable because the application working directory is unavailable to the uninstaller. 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-.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 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. Compilation does not establish installed-uninstall behavior. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index cedc78bf4e..77360526dd 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -267,7 +267,7 @@ 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 [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。手动和静默卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。命令所有权缺失时,额外清理只移除匹配本安装 CLI 目录的 PATH 条目,并先确认安装目录已不存在;目录仍存在或检查失败时保留条目并生成清理报告。其他命令安装保持不变。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载请求确认,静默卸载停止。安装地址缺失或指向其他位置时,卸载会清理仍指向本目录的命令、协议、快捷方式和 Windows 卸载入口,保留共享用户数据和系统外壳设置。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 +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。手动和静默卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。命令所有权缺失时,额外清理只移除匹配本安装 CLI 目录的 PATH 条目,并先确认安装目录已不存在;目录仍存在或检查失败时保留条目并生成清理报告。其他命令安装保持不变。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载请求确认,静默卸载停止。安装地址缺失或指向其他位置时,卸载会清理仍指向本目录的命令、协议、快捷方式和 Windows 卸载入口,保留共享用户数据和系统外壳设置。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译八种安装语言的独立夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 、`DSH_HOME` 位于 Electron 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/uninstall-data.h b/apps/desktop/installer/uninstall-data.h index e7f1c0cdcc..c0e4f23dba 100644 --- a/apps/desktop/installer/uninstall-data.h +++ b/apps/desktop/installer/uninstall-data.h @@ -45,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, @@ -109,7 +132,7 @@ inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot, 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 { diff --git a/apps/desktop/installer/uninstall-report.h b/apps/desktop/installer/uninstall-report.h index a36f402c8c..e0dd2f60f1 100644 --- a/apps/desktop/installer/uninstall-report.h +++ b/apps/desktop/installer/uninstall-report.h @@ -174,7 +174,7 @@ inline DWORD Prepare(Session& session, LPCWSTR directory, LPCWSTR protectedRoot) if (!uninstall_data::Normalize(directory, path)) return ERROR_INVALID_NAME; if (protectedRoot && *protectedRoot) { std::wstring home; - if (!uninstall_data::Normalize(protectedRoot, home)) return ERROR_INVALID_NAME; + 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; } const KNOWNFOLDERID* folders[] = {&FOLDERID_Profile, &FOLDERID_RoamingAppData, &FOLDERID_LocalAppData, @@ -267,10 +267,14 @@ extern "C" __declspec(dllexport) int __cdecl UninstallShow(uninstall_report::Ses } 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(file.c_str()); + 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(); diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index 714e7826c7..151d9c7b04 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -61,6 +61,8 @@ Function un.BeginCleanup 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} diff --git a/apps/desktop/tests/expected/windows-uninstall.json b/apps/desktop/tests/expected/windows-uninstall.json index 148db0ed5c..b1f147d358 100644 --- a/apps/desktop/tests/expected/windows-uninstall.json +++ b/apps/desktop/tests/expected/windows-uninstall.json @@ -10,6 +10,9 @@ "upgrade", "replaced", "home-inside", + "home-slash", + "home-tilde", + "home-slash-inside", "registration-error", "main-locked", "self-copy", diff --git a/apps/desktop/tests/windows-uninstall-data.cpp b/apps/desktop/tests/windows-uninstall-data.cpp index 1498818cae..887f83b796 100644 --- a/apps/desktop/tests/windows-uninstall-data.cpp +++ b/apps/desktop/tests/windows-uninstall-data.cpp @@ -51,6 +51,9 @@ 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")); // A pinned directory cannot be renamed or replaced while the helper holds it. @@ -124,5 +127,39 @@ int wmain(int argc, wchar_t** argv) { 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); + assert(RemoveDirectoryW(installation.c_str())); + + std::vector 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())); } diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index db12575c5c..b44302ce06 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -25,6 +25,7 @@ $ownerKey = "Software\DSHUninstallTests\$RegistryKey\CommandOwner" $protocolKey = "Software\Classes\dsh-test-$RegistryKey" $process = $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() @@ -114,7 +115,7 @@ try { try { $key.SetValue('', '"' + (Join-Path $integrationRoot ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() } $launchUninstaller = $uninstaller $arguments = '_?=' + $installPath - if ($mode -in @('silent', 'missing-location', 'missing-location-short', 'missing-location-foreign', 'unowned', 'owned-retained', 'home-inside', 'registration-error', 'main-locked', 'auxiliary-locked', 'unsafe-root')) { $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') { Set-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation -Value ($installPath + '\') @@ -125,6 +126,12 @@ try { $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 } + 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() } @@ -217,7 +224,7 @@ try { Wait-Exit $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" } @@ -250,6 +257,7 @@ try { $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 try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover B setup failed' } } finally { $setup.Dispose() } if ((Get-ItemProperty ('HKCU:\' + $ownerKey)).Directory) { throw 'Relocation retained old command owner' } @@ -289,7 +297,26 @@ try { Set-ItemProperty ('HKCU:\' + $ownerKey) Directory $oldCommand Set-ItemProperty ('HKCU:\' + $environmentKey) Path ($oldCommand + ';C:\Windows') $bUninstall = $entry.UninstallString - Copy-Item -LiteralPath $newPath -Destination $installPath -Recurse + 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) @@ -327,7 +354,7 @@ try { } finally { if ($held) { $held.Dispose() } foreach ($key in @("Software\DSHUninstallTests\$RegistryKey", $protocolKey)) { [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($key, $false) } - Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue + [Environment]::SetEnvironmentVariable('DSH_HOME', $originalHome, 'Process') if ($process) { if (-not $process.HasExited) { $process.Kill(); $process.WaitForExit() }; $process.Dispose() } # Only unique test identities below known application-data parents are removed. foreach ($pair in @(@($productDataPath, $roaming), @($scopePath, $roaming), @($cachePath, $local))) { From 25c10e7fd19ee6de2d1eb9c85e34125ee5dde318 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 19 Nov 2026 14:17:59 +0800 Subject: [PATCH 14/15] Handle network uninstall home paths and reap timed-out fixtures --- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 4 +- apps/desktop/README.zh.md | 4 +- apps/desktop/installer/uninstall-data.h | 88 ++++++++++++++++++- apps/desktop/installer/uninstall-report.h | 13 +-- .../scripts/prepare-windows-installer.ps1 | 2 +- .../scripts/test-windows-installer.mjs | 2 + .../tests/windows-installer-process-test.ps1 | 49 +++++++++++ .../tests/windows-installer-process.ps1 | 22 +++++ apps/desktop/tests/windows-uninstall-data.cpp | 48 +++++++++- .../desktop/tests/windows-uninstall-smoke.ps1 | 26 ++++-- 11 files changed, 236 insertions(+), 26 deletions(-) create mode 100644 apps/desktop/tests/windows-installer-process-test.ps1 create mode 100644 apps/desktop/tests/windows-installer-process.ps1 diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index fd0476350c..f63d1999ca 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: f816b98b0fde9d08 - zh: b69facb3b5fbe828 + en: d92ef9966ba984a9 + zh: 0b200e57d2dd08db /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index f4c6f5b7f8..226c88e295 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -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 [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. Home paths accept `~/`, `~\` and forward slashes; relative paths remain unverifiable because the application working directory is unavailable to the uninstaller. 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-.txt` when writable; interactive dialogs also offer Save cleanup report, and a failed save allows another location. 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 `~/`, `~\`, forward slashes, UNC shares and mapped or removable drives. Existing directory identities and their relative descendants detect overlap through aliases; inaccessible roots stop deletion and report the failing `DSH_HOME` value. Relative paths remain unverifiable because the application working directory is unavailable to the uninstaller. 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-.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 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. 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. For live SMB coverage, run the generated `ui/data-cleanup-test.exe ` against an existing accessible share; it checks separate and overlapping UNC paths and creates then removes a temporary mapped drive. Compilation does not establish installed-uninstall behavior. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 77360526dd..5625aeb7c4 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -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 [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。手动和静默卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。命令所有权缺失时,额外清理只移除匹配本安装 CLI 目录的 PATH 条目,并先确认安装目录已不存在;目录仍存在或检查失败时保留条目并生成清理报告。其他命令安装保持不变。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载请求确认,静默卸载停止。安装地址缺失或指向其他位置时,卸载会清理仍指向本目录的命令、协议、快捷方式和 Windows 卸载入口,保留共享用户数据和系统外壳设置。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 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-.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 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。安装超时会先终止并等待夹具进程树退出,再清理测试资源;独立回归覆盖成功、非零退出及带存活子进程的父进程超时。真实 SMB 验证可在已有且可访问的共享上运行生成的 `ui/data-cleanup-test.exe `,检查分离与重叠的 UNC 路径,并创建、移除临时映射盘。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/uninstall-data.h b/apps/desktop/installer/uninstall-data.h index c0e4f23dba..7361d8789c 100644 --- a/apps/desktop/installer/uninstall-data.h +++ b/apps/desktop/installer/uninstall-data.h @@ -45,6 +45,16 @@ inline bool Normalize(LPCWSTR input, std::wstring& result) { return true; } +inline size_t RootLength(const std::wstring& path) { + if (path.size() >= 3 && path[1] == L':' && path[2] == L'\\') return 3; + if (path.compare(0, 2, L"\\\\") != 0) return 0; + const size_t server = path.find(L'\\', 2); + if (server == std::wstring::npos || server == 2) return 0; + const size_t share = path.find(L'\\', server + 1); + if (server + 1 == path.size() || share == server + 1) return 0; + return share == std::wstring::npos ? path.size() : share + 1; +} + // 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) { @@ -65,7 +75,78 @@ inline bool NormalizeHome(LPCWSTR input, std::wstring& result) { 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); + if (_wcsnicmp(value.c_str(), L"\\\\?\\UNC\\", 8) == 0) value = L"\\\\" + value.substr(8); + else if (value.compare(0, 4, L"\\\\?\\") == 0) value = value.substr(4); + const size_t root = RootLength(value); + if (!root || value.compare(0, 4, L"\\\\.\\") == 0) return false; + if (wcspbrk(value.c_str() + (value[1] == L':' ? 2 : 0), L":*?\"<>|\r\n\t")) return false; + WCHAR buffer[32768]; + const DWORD length = GetFullPathNameW(value.c_str(), ARRAYSIZE(buffer), buffer, nullptr); + if (!length || length >= ARRAYSIZE(buffer)) return false; + result.assign(buffer, length); + const size_t normalizedRoot = RootLength(result); + while (result.size() > normalizedRoot && result.back() == L'\\') result.pop_back(); + for (size_t start = normalizedRoot; start < result.size();) { + size_t end = result.find(L'\\', start); + if (end == std::wstring::npos) end = result.size(); + if (end == start || result[end - 1] == L'.' || result[end - 1] == L' ') return false; + start = end + 1; + } + return true; +} + +struct Ancestor { + BY_HANDLE_FILE_INFORMATION identity; + std::wstring suffix; +}; +// Keep absent suffixes relative to existing ancestors. File identities also match +// local SMB shares, mapped drives and junction aliases whose path strings differ. +inline DWORD Ancestors(std::wstring path, std::vector& ancestors) { + std::wstring suffix; + const size_t root = RootLength(path); + for (;;) { + const std::wstring extended = path.compare(0, 2, L"\\\\") == 0 + ? L"\\\\?\\UNC\\" + path.substr(2) : L"\\\\?\\" + path; + HANDLE handle = CreateFileW(extended.c_str(), FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + if (handle == INVALID_HANDLE_VALUE) { + const DWORD error = GetLastError(); + if ((error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND) || path.size() <= root) return error; + } else { + BY_HANDLE_FILE_INFORMATION identity{}; + const BOOL read = GetFileInformationByHandle(handle, &identity); + const DWORD error = read ? ERROR_SUCCESS : GetLastError(); + CloseHandle(handle); + if (error) return error; + if (!(identity.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) return ERROR_DIRECTORY; + ancestors.push_back({identity, suffix}); + } + if (path.size() <= root) break; + const size_t separator = path.find_last_of(L'\\'); + suffix = path.substr(separator + 1) + (suffix.empty() ? L"" : L"\\" + suffix); + path.resize(separator < root ? root : separator); + } + return ERROR_SUCCESS; +} + +inline DWORD CheckHome(const std::wstring& target, LPCWSTR input, bool* homeFailure = nullptr) { + if (homeFailure) *homeFailure = true; + std::wstring home; + if (!NormalizeHome(input, home)) return ERROR_INVALID_NAME; + std::vector protectedAncestors, targetAncestors; + DWORD error = Ancestors(home, protectedAncestors); + if (error) return error; + if (homeFailure) *homeFailure = false; + error = Ancestors(target, targetAncestors); + if (error) return error; + if (homeFailure) *homeFailure = true; + for (const auto& a : protectedAncestors) for (const auto& b : targetAncestors) { + if (a.identity.dwVolumeSerialNumber == b.identity.dwVolumeSerialNumber + && a.identity.nFileIndexHigh == b.identity.nFileIndexHigh && a.identity.nFileIndexLow == b.identity.nFileIndexLow + && (a.suffix.empty() || b.suffix.empty() || Contains(a.suffix, b.suffix) || Contains(b.suffix, a.suffix))) + return ERROR_ACCESS_DENIED; + } + return ERROR_SUCCESS; } // Listing access takes part in share checks, so the open handle refuses the DELETE access a rename or removal needs. @@ -130,10 +211,9 @@ inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot, 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 (!NormalizeHome(protectedRoot, home)) return ERROR_INVALID_NAME; - if (Contains(path, home) || Contains(home, path)) return ERROR_ACCESS_DENIED; + const DWORD error = CheckHome(path, protectedRoot); + if (error) return error; } struct ComScope { HRESULT result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); diff --git a/apps/desktop/installer/uninstall-report.h b/apps/desktop/installer/uninstall-report.h index e0dd2f60f1..dc1e892953 100644 --- a/apps/desktop/installer/uninstall-report.h +++ b/apps/desktop/installer/uninstall-report.h @@ -169,13 +169,13 @@ inline int Show(HWND parent, Session& session, int mode, LPCWSTR title, LPCWSTR } // Pin every ancestor and reject shell roots/ancestors before any payload removal. -inline DWORD Prepare(Session& session, LPCWSTR directory, LPCWSTR protectedRoot) { +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) { - 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; + const DWORD error = uninstall_data::CheckHome(path, protectedRoot, &homeFailure); + if (error) return error; + homeFailure = false; } const KNOWNFOLDERID* folders[] = {&FOLDERID_Profile, &FOLDERID_RoamingAppData, &FOLDERID_LocalAppData, &FOLDERID_Desktop, &FOLDERID_Documents, &FOLDERID_Downloads, &FOLDERID_Pictures, &FOLDERID_Music, @@ -243,8 +243,9 @@ extern "C" __declspec(dllexport) uninstall_report::Session* __cdecl UninstallBeg return session; } extern "C" __declspec(dllexport) DWORD __cdecl UninstallPrepare(uninstall_report::Session* session, LPCWSTR path, LPCWSTR home) { - const DWORD error = uninstall_report::Prepare(*session, path, home); - if (error) uninstall_report::Add(*session, L"Validate removal scope; no deletion started", path, error); + 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) { diff --git a/apps/desktop/scripts/prepare-windows-installer.ps1 b/apps/desktop/scripts/prepare-windows-installer.ps1 index e073e16926..bdede1e63d 100644 --- a/apps/desktop/scripts/prepare-windows-installer.ps1 +++ b/apps/desktop/scripts/prepare-windows-installer.ps1 @@ -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 "{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) + [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 mpr.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) { diff --git a/apps/desktop/scripts/test-windows-installer.mjs b/apps/desktop/scripts/test-windows-installer.mjs index 4bd6afb712..a3a711d76a 100644 --- a/apps/desktop/scripts/test-windows-installer.mjs +++ b/apps/desktop/scripts/test-windows-installer.mjs @@ -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') diff --git a/apps/desktop/tests/windows-installer-process-test.ps1 b/apps/desktop/tests/windows-installer-process-test.ps1 new file mode 100644 index 0000000000..7c43d46a0f --- /dev/null +++ b/apps/desktop/tests/windows-installer-process-test.ps1 @@ -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 +} diff --git a/apps/desktop/tests/windows-installer-process.ps1 b/apps/desktop/tests/windows-installer-process.ps1 new file mode 100644 index 0000000000..a59eaa8ee3 --- /dev/null +++ b/apps/desktop/tests/windows-installer-process.ps1 @@ -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 + } +} diff --git a/apps/desktop/tests/windows-uninstall-data.cpp b/apps/desktop/tests/windows-uninstall-data.cpp index 887f83b796..9b4696374a 100644 --- a/apps/desktop/tests/windows-uninstall-data.cpp +++ b/apps/desktop/tests/windows-uninstall-data.cpp @@ -3,6 +3,7 @@ #define NOMINMAX #define UNICODE #include +#include #include #include "../installer/uninstall-data.h" @@ -10,6 +11,7 @@ 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); @@ -22,7 +24,7 @@ static void File(const std::wstring& path, DWORD attributes = FILE_ATTRIBUTE_NOR static bool Exists(const std::wstring& path) { return GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES; } int wmain(int argc, wchar_t** argv) { - assert(argc == 2); + assert(argc == 2 || argc == 3); const std::wstring root = argv[1]; const std::wstring installation = root + L"\\application"; const std::wstring data = root + L"\\data"; @@ -37,6 +39,30 @@ int wmain(int argc, wchar_t** argv) { File(cache + L"\\LOCK", FILE_ATTRIBUTE_READONLY); File(cache + L"\\MANIFEST"); + // Optional live SMB coverage: argv[2] is the same private root through an existing share. + if (argc == 3) { + const std::wstring networkRoot = argv[2]; + assert(uninstall_data::CheckHome(installation, (networkRoot + L"\\data").c_str()) == ERROR_SUCCESS); + assert(uninstall_data::CheckHome(installation, (networkRoot + L"\\application").c_str()) == ERROR_ACCESS_DENIED); + assert(uninstall_data::CheckHome(installation, (networkRoot + L"\\application\\missing").c_str()) == ERROR_ACCESS_DENIED); + WCHAR drive[] = L"Z:"; + NETRESOURCEW resource{}; + resource.dwType = RESOURCETYPE_DISK; + resource.lpRemoteName = argv[2]; + resource.lpLocalName = drive; + DWORD mapped = ERROR_ALREADY_ASSIGNED; + for (; drive[0] >= L'F'; --drive[0]) { + mapped = WNetAddConnection2W(&resource, nullptr, nullptr, CONNECT_TEMPORARY); + if (mapped != ERROR_ALREADY_ASSIGNED && mapped != ERROR_DEVICE_ALREADY_REMEMBERED) break; + } + assert(mapped == ERROR_SUCCESS); + const DWORD separate = uninstall_data::CheckHome(installation, (std::wstring(drive) + L"\\data").c_str()); + const DWORD overlapping = uninstall_data::CheckHome(installation, (std::wstring(drive) + L"\\application").c_str()); + assert(WNetCancelConnection2W(drive, 0, FALSE) == ERROR_SUCCESS); + assert(separate == ERROR_SUCCESS); + assert(overlapping == ERROR_ACCESS_DENIED); + } + // Refused roots: the test root contains the installation; shell roots and malformed paths are rejected. assert(uninstall_data::Remove(root.c_str(), installation.c_str(), nullptr) == ERROR_ACCESS_DENIED); assert(uninstall_data::Remove(L"C:\\", installation.c_str(), nullptr) == ERROR_INVALID_NAME); @@ -56,6 +82,17 @@ int wmain(int argc, wchar_t** argv) { assert(uninstall_data::Remove(data.c_str(), installation.c_str(), slashHome.c_str()) == ERROR_ACCESS_DENIED); assert(Exists(cache + L"\\CURRENT")); + // Missing children still overlap their existing parent; absent siblings are separate. + assert(uninstall_data::CheckHome(installation, (installation + L"\\missing\\home").c_str()) == ERROR_ACCESS_DENIED); + assert(uninstall_data::CheckHome(installation, (root + L"\\missing\\home").c_str()) == ERROR_SUCCESS); + assert(uninstall_data::CheckHome(installation, (L"\\\\?\\" + installation).c_str()) == ERROR_ACCESS_DENIED); + std::wstring normalizedHome; + assert(uninstall_data::NormalizeHome(L"\\\\server\\share\\home", normalizedHome)); + assert(uninstall_data::NormalizeHome(L"\\\\?\\UNC\\server\\share\\home", normalizedHome)); + assert(normalizedHome == L"\\\\server\\share\\home"); + assert(!uninstall_data::NormalizeHome(L"\\\\server", normalizedHome)); + assert(!uninstall_data::NormalizeHome(L"\\\\.\\C:\\home", normalizedHome)); + // A pinned directory cannot be renamed or replaced while the helper holds it. { uninstall_data::Handles pinned; @@ -142,6 +179,15 @@ int wmain(int argc, wchar_t** argv) { 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 longDirectories; diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index b44302ce06..25ca2e4407 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -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') @@ -24,6 +25,7 @@ $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 @@ -52,10 +54,8 @@ 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') @@ -244,7 +244,8 @@ try { } # Real replacement publishes B after the old A uninstaller has been retained. $setup = Start-Process $Installer -ArgumentList ('/S /D=' + $installPath) -PassThru -WindowStyle Hidden - try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover A setup failed' } } finally { $setup.Dispose() } + 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) @@ -259,7 +260,8 @@ try { $newPath = Join-Path $OutputDirectory 'Replacement App' $env:DSH_HOME = $homePath.Replace('\', '/') $setup = Start-Process $Installer -ArgumentList ('/S /D=' + $newPath) -PassThru -WindowStyle Hidden - try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover B setup failed' } } finally { $setup.Dispose() } + 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' } @@ -353,9 +355,17 @@ try { Write-Output 'passed: installation takeover' } finally { if ($held) { $held.Dispose() } - foreach ($key in @("Software\DSHUninstallTests\$RegistryKey", $protocolKey)) { [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($key, $false) } + 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') - if ($process) { if (-not $process.HasExited) { $process.Kill(); $process.WaitForExit() }; $process.Dispose() } # 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]) From 396593b9fd6f2f8e281e33763a324d61f2484f89 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 19 Nov 2026 14:44:58 +0800 Subject: [PATCH 15/15] Revert network home expansion and retain uninstall diagnostics --- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 4 +- apps/desktop/README.zh.md | 4 +- apps/desktop/installer/uninstall-data.h | 88 +------------------ apps/desktop/installer/uninstall-report.h | 6 +- .../scripts/prepare-windows-installer.ps1 | 2 +- apps/desktop/tests/windows-uninstall-data.cpp | 44 ++-------- 7 files changed, 23 insertions(+), 129 deletions(-) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index f63d1999ca..a146117824 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: d92ef9966ba984a9 - zh: 0b200e57d2dd08db + en: 80f8f18b571864b6 + zh: 45af1d593b7e1b64 /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 226c88e295..01bfdd9676 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -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 [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. Home paths accept `~/`, `~\`, forward slashes, UNC shares and mapped or removable drives. Existing directory identities and their relative descendants detect overlap through aliases; inaccessible roots stop deletion and report the failing `DSH_HOME` value. Relative paths remain unverifiable because the application working directory is unavailable to the uninstaller. 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-.txt` when writable; interactive dialogs also offer Save cleanup report, and a failed save allows another location. 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-.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 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. For live SMB coverage, run the generated `ui/data-cleanup-test.exe ` against an existing accessible share; it checks separate and overlapping UNC paths and creates then removes a temporary mapped drive. 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. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 5625aeb7c4..22e2edc76f 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -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 [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` 还会保护所有与其重叠的目标。主目录路径支持 `~/`、`~\`、正斜杠、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-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 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-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 -使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译八种安装语言的独立夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 、`DSH_HOME` 位于 Electron 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。安装超时会先终止并等待夹具进程树退出,再清理测试资源;独立回归覆盖成功、非零退出及带存活子进程的父进程超时。真实 SMB 验证可在已有且可访问的共享上运行生成的 `ui/data-cleanup-test.exe `,检查分离与重叠的 UNC 路径,并创建、移除临时映射盘。编译本身不能证明已安装卸载行为。 +使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译八种安装语言的独立夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 、`DSH_HOME` 位于 Electron 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。安装超时会先终止并等待夹具进程树退出,再清理测试资源;独立回归覆盖成功、非零退出及带存活子进程的父进程超时。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/uninstall-data.h b/apps/desktop/installer/uninstall-data.h index 7361d8789c..c0e4f23dba 100644 --- a/apps/desktop/installer/uninstall-data.h +++ b/apps/desktop/installer/uninstall-data.h @@ -45,16 +45,6 @@ inline bool Normalize(LPCWSTR input, std::wstring& result) { return true; } -inline size_t RootLength(const std::wstring& path) { - if (path.size() >= 3 && path[1] == L':' && path[2] == L'\\') return 3; - if (path.compare(0, 2, L"\\\\") != 0) return 0; - const size_t server = path.find(L'\\', 2); - if (server == std::wstring::npos || server == 2) return 0; - const size_t share = path.find(L'\\', server + 1); - if (server + 1 == path.size() || share == server + 1) return 0; - return share == std::wstring::npos ? path.size() : share + 1; -} - // 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) { @@ -75,78 +65,7 @@ inline bool NormalizeHome(LPCWSTR input, std::wstring& result) { value = profile + (value.size() > 1 ? L"\\" + value.substr(2) : L""); } for (auto& character : value) if (character == L'/') character = L'\\'; - if (_wcsnicmp(value.c_str(), L"\\\\?\\UNC\\", 8) == 0) value = L"\\\\" + value.substr(8); - else if (value.compare(0, 4, L"\\\\?\\") == 0) value = value.substr(4); - const size_t root = RootLength(value); - if (!root || value.compare(0, 4, L"\\\\.\\") == 0) return false; - if (wcspbrk(value.c_str() + (value[1] == L':' ? 2 : 0), L":*?\"<>|\r\n\t")) return false; - WCHAR buffer[32768]; - const DWORD length = GetFullPathNameW(value.c_str(), ARRAYSIZE(buffer), buffer, nullptr); - if (!length || length >= ARRAYSIZE(buffer)) return false; - result.assign(buffer, length); - const size_t normalizedRoot = RootLength(result); - while (result.size() > normalizedRoot && result.back() == L'\\') result.pop_back(); - for (size_t start = normalizedRoot; start < result.size();) { - size_t end = result.find(L'\\', start); - if (end == std::wstring::npos) end = result.size(); - if (end == start || result[end - 1] == L'.' || result[end - 1] == L' ') return false; - start = end + 1; - } - return true; -} - -struct Ancestor { - BY_HANDLE_FILE_INFORMATION identity; - std::wstring suffix; -}; -// Keep absent suffixes relative to existing ancestors. File identities also match -// local SMB shares, mapped drives and junction aliases whose path strings differ. -inline DWORD Ancestors(std::wstring path, std::vector& ancestors) { - std::wstring suffix; - const size_t root = RootLength(path); - for (;;) { - const std::wstring extended = path.compare(0, 2, L"\\\\") == 0 - ? L"\\\\?\\UNC\\" + path.substr(2) : L"\\\\?\\" + path; - HANDLE handle = CreateFileW(extended.c_str(), FILE_READ_ATTRIBUTES, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); - if (handle == INVALID_HANDLE_VALUE) { - const DWORD error = GetLastError(); - if ((error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND) || path.size() <= root) return error; - } else { - BY_HANDLE_FILE_INFORMATION identity{}; - const BOOL read = GetFileInformationByHandle(handle, &identity); - const DWORD error = read ? ERROR_SUCCESS : GetLastError(); - CloseHandle(handle); - if (error) return error; - if (!(identity.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) return ERROR_DIRECTORY; - ancestors.push_back({identity, suffix}); - } - if (path.size() <= root) break; - const size_t separator = path.find_last_of(L'\\'); - suffix = path.substr(separator + 1) + (suffix.empty() ? L"" : L"\\" + suffix); - path.resize(separator < root ? root : separator); - } - return ERROR_SUCCESS; -} - -inline DWORD CheckHome(const std::wstring& target, LPCWSTR input, bool* homeFailure = nullptr) { - if (homeFailure) *homeFailure = true; - std::wstring home; - if (!NormalizeHome(input, home)) return ERROR_INVALID_NAME; - std::vector protectedAncestors, targetAncestors; - DWORD error = Ancestors(home, protectedAncestors); - if (error) return error; - if (homeFailure) *homeFailure = false; - error = Ancestors(target, targetAncestors); - if (error) return error; - if (homeFailure) *homeFailure = true; - for (const auto& a : protectedAncestors) for (const auto& b : targetAncestors) { - if (a.identity.dwVolumeSerialNumber == b.identity.dwVolumeSerialNumber - && a.identity.nFileIndexHigh == b.identity.nFileIndexHigh && a.identity.nFileIndexLow == b.identity.nFileIndexLow - && (a.suffix.empty() || b.suffix.empty() || Contains(a.suffix, b.suffix) || Contains(b.suffix, a.suffix))) - return ERROR_ACCESS_DENIED; - } - return ERROR_SUCCESS; + 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. @@ -211,9 +130,10 @@ inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot, 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. - const DWORD error = CheckHome(path, protectedRoot); - if (error) return error; + if (!NormalizeHome(protectedRoot, home)) return ERROR_INVALID_NAME; + if (Contains(path, home) || Contains(home, path)) return ERROR_ACCESS_DENIED; } struct ComScope { HRESULT result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); diff --git a/apps/desktop/installer/uninstall-report.h b/apps/desktop/installer/uninstall-report.h index dc1e892953..32c685593d 100644 --- a/apps/desktop/installer/uninstall-report.h +++ b/apps/desktop/installer/uninstall-report.h @@ -173,8 +173,10 @@ inline DWORD Prepare(Session& session, LPCWSTR directory, LPCWSTR protectedRoot, std::wstring path; if (!uninstall_data::Normalize(directory, path)) return ERROR_INVALID_NAME; if (protectedRoot && *protectedRoot) { - const DWORD error = uninstall_data::CheckHome(path, protectedRoot, &homeFailure); - if (error) return error; + 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, diff --git a/apps/desktop/scripts/prepare-windows-installer.ps1 b/apps/desktop/scripts/prepare-windows-installer.ps1 index bdede1e63d..e073e16926 100644 --- a/apps/desktop/scripts/prepare-windows-installer.ps1 +++ b/apps/desktop/scripts/prepare-windows-installer.ps1 @@ -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 "{3}" shell32.lib ole32.lib uuid.lib advapi32.lib mpr.lib' -f $cleanupSource, (Join-Path $output 'data-cleanup-test.obj'), $cleanupExecutable, (Join-Path $output 'window-frame.lib'))), [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) { diff --git a/apps/desktop/tests/windows-uninstall-data.cpp b/apps/desktop/tests/windows-uninstall-data.cpp index 9b4696374a..c2cca07e70 100644 --- a/apps/desktop/tests/windows-uninstall-data.cpp +++ b/apps/desktop/tests/windows-uninstall-data.cpp @@ -3,7 +3,6 @@ #define NOMINMAX #define UNICODE #include -#include #include #include "../installer/uninstall-data.h" @@ -11,6 +10,7 @@ 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) { @@ -24,7 +24,7 @@ static void File(const std::wstring& path, DWORD attributes = FILE_ATTRIBUTE_NOR static bool Exists(const std::wstring& path) { return GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES; } int wmain(int argc, wchar_t** argv) { - assert(argc == 2 || argc == 3); + assert(argc == 2); const std::wstring root = argv[1]; const std::wstring installation = root + L"\\application"; const std::wstring data = root + L"\\data"; @@ -39,30 +39,6 @@ int wmain(int argc, wchar_t** argv) { File(cache + L"\\LOCK", FILE_ATTRIBUTE_READONLY); File(cache + L"\\MANIFEST"); - // Optional live SMB coverage: argv[2] is the same private root through an existing share. - if (argc == 3) { - const std::wstring networkRoot = argv[2]; - assert(uninstall_data::CheckHome(installation, (networkRoot + L"\\data").c_str()) == ERROR_SUCCESS); - assert(uninstall_data::CheckHome(installation, (networkRoot + L"\\application").c_str()) == ERROR_ACCESS_DENIED); - assert(uninstall_data::CheckHome(installation, (networkRoot + L"\\application\\missing").c_str()) == ERROR_ACCESS_DENIED); - WCHAR drive[] = L"Z:"; - NETRESOURCEW resource{}; - resource.dwType = RESOURCETYPE_DISK; - resource.lpRemoteName = argv[2]; - resource.lpLocalName = drive; - DWORD mapped = ERROR_ALREADY_ASSIGNED; - for (; drive[0] >= L'F'; --drive[0]) { - mapped = WNetAddConnection2W(&resource, nullptr, nullptr, CONNECT_TEMPORARY); - if (mapped != ERROR_ALREADY_ASSIGNED && mapped != ERROR_DEVICE_ALREADY_REMEMBERED) break; - } - assert(mapped == ERROR_SUCCESS); - const DWORD separate = uninstall_data::CheckHome(installation, (std::wstring(drive) + L"\\data").c_str()); - const DWORD overlapping = uninstall_data::CheckHome(installation, (std::wstring(drive) + L"\\application").c_str()); - assert(WNetCancelConnection2W(drive, 0, FALSE) == ERROR_SUCCESS); - assert(separate == ERROR_SUCCESS); - assert(overlapping == ERROR_ACCESS_DENIED); - } - // Refused roots: the test root contains the installation; shell roots and malformed paths are rejected. assert(uninstall_data::Remove(root.c_str(), installation.c_str(), nullptr) == ERROR_ACCESS_DENIED); assert(uninstall_data::Remove(L"C:\\", installation.c_str(), nullptr) == ERROR_INVALID_NAME); @@ -82,16 +58,12 @@ int wmain(int argc, wchar_t** argv) { assert(uninstall_data::Remove(data.c_str(), installation.c_str(), slashHome.c_str()) == ERROR_ACCESS_DENIED); assert(Exists(cache + L"\\CURRENT")); - // Missing children still overlap their existing parent; absent siblings are separate. - assert(uninstall_data::CheckHome(installation, (installation + L"\\missing\\home").c_str()) == ERROR_ACCESS_DENIED); - assert(uninstall_data::CheckHome(installation, (root + L"\\missing\\home").c_str()) == ERROR_SUCCESS); - assert(uninstall_data::CheckHome(installation, (L"\\\\?\\" + installation).c_str()) == ERROR_ACCESS_DENIED); - std::wstring normalizedHome; - assert(uninstall_data::NormalizeHome(L"\\\\server\\share\\home", normalizedHome)); - assert(uninstall_data::NormalizeHome(L"\\\\?\\UNC\\server\\share\\home", normalizedHome)); - assert(normalizedHome == L"\\\\server\\share\\home"); - assert(!uninstall_data::NormalizeHome(L"\\\\server", normalizedHome)); - assert(!uninstall_data::NormalizeHome(L"\\\\.\\C:\\home", normalizedHome)); + // 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. {