From d54a04e902cd6ee7074cd8cc379fbb2c21518e06 Mon Sep 17 00:00:00 2001 From: winewill Date: Fri, 13 Nov 2026 18:21:16 +0800 Subject: [PATCH] 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() }