JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(updater): 巩固windows和mac桌面端自动更新流程,支持预览版自动更新
kdgmpw24336420ffe4
diff --git a/docs/README.md b/docs/README.mdindex 1f4a8ed0a3..9f17e1bd22 100644--- a/docs/README.md+++ b/docs/README.md@@ -183,8 +183,8 @@</tr><tr><td width="22%"><strong>自动更新</strong></td>- <td width="28%"><a href="zh/windows自动更新设计.md">Windows 自动更新设计</a></td>- <td width="50%">Windows 客户端自动更新方案、流程与关键模块。</td>+ <td width="28%"><a href="zh/windows自动更新设计.md">桌面端自动更新设计</a></td>+ <td width="50%">Windows 与 macOS 桌面端自动更新方案、流程与关键模块(含预发布版推送)。</td></tr><tr><td width="22%"><strong>开发者文档</strong></td>diff --git a/docs/README_EN.md b/docs/README_EN.mdindex e0f465c617..dbf4162506 100644--- a/docs/README_EN.md+++ b/docs/README_EN.md@@ -183,8 +183,8 @@ This page collects common JiuwenSwarm usage instructions, feature documentation,</tr><tr><td width="22%"><strong>Auto Update</strong></td>- <td width="28%"><a href="en/WindowsAutoUpdateDesign.md">Windows Auto-Update Design</a></td>- <td width="50%">Windows client auto-update design, flow, and key modules.</td>+ <td width="28%"><a href="en/WindowsAutoUpdateDesign.md">Desktop Auto-Update Design</a></td>+ <td width="50%">Windows and macOS desktop auto-update design, flow, and key modules (including pre-release pushes).</td></tr><tr><td width="22%"><strong>Developer Documentation</strong></td>diff --git a/docs/en/InstallGuide.md b/docs/en/InstallGuide.mdindex 77871d62f5..833eb3be98 100644--- a/docs/en/InstallGuide.md+++ b/docs/en/InstallGuide.md@@ -65,7 +65,7 @@ curl -L --fail -o JiuwenSwarm-<version>.dmg \On first launch the app creates `~/.jiuwenswarm/`. Then follow [Post-start verification](#3-post-start-verification) to finish model configuration.-> Match the version to the actual download link on the Release page. For Windows auto-update behavior, see [Windows auto-update design](WindowsAutoUpdateDesign.md).+> Match the version to the actual download link on the Release page. For desktop auto-update behavior (Windows and macOS), see [Desktop auto-update design](WindowsAutoUpdateDesign.md).---diff --git a/docs/en/SUMMARY.md b/docs/en/SUMMARY.mdindex b626d63915..95e53c05b2 100644--- a/docs/en/SUMMARY.md+++ b/docs/en/SUMMARY.md@@ -40,7 +40,7 @@- [MCP Configuration](MCPConfiguration.md)- [Packaging desktop executables](PackExeGuide.md)- [ACP Plugin Usage](ACP_Client_Config.md)- - [Windows auto-update design](WindowsAutoUpdateDesign.md)+ - [Desktop auto-update design](WindowsAutoUpdateDesign.md)- [Logging System](Logs.md)- [Development practices](development-practices/README.md)- [Daily report generator practice](development-practices/JiuwenSwarm-Daily-Report-Generator.md)diff --git a/docs/en/WindowsAutoUpdateDesign.md b/docs/en/WindowsAutoUpdateDesign.mdindex 51560d478d..dfa74b6ab2 100644--- a/docs/en/WindowsAutoUpdateDesign.md+++ b/docs/en/WindowsAutoUpdateDesign.md@@ -1,49 +1,74 @@-# Windows Auto-Update Design+# Desktop Auto-Update Design-This document describes the minimum viable auto-update solution for JiuwenSwarm on Windows desktop. The goal is to prioritize stability over seamless upgrades.+This document describes the auto-update solution for JiuwenSwarm desktop (Windows and macOS). The goal is to prioritize stability while covering both stable and pre-release (beta) upgrade flows.## Scope-- Windows desktop edition only+- Supports Windows and macOS desktop (Linux desktop also applies)- Automatic update check on startup- Manual update check via the sidebar "Update" page-- Update source: GitHub Releases-- Download artifact: Inno Setup installer `jiuwenswarm-setup-<version>.exe`-- After download, an external helper script performs a silent install and restarts the application+- Desktop update source defaults to GitCode Releases, switchable to GitHub Releases; pip install mode uses PyPI+- Download artifacts differ per platform:+ - Windows: Inno Setup installer `JiuwenSwarm-setup-<version>.exe`+ - macOS: DMG image `JiuwenSwarm-<version>.dmg`+ - Linux: `JiuwenSwarm-<version>.tar.gz`+- After download, an external helper completes installation and restart: Windows via an interactive install wizard, macOS / Linux via a silent helper script that installs and restarts+- Pre-release support: stable and pre-release releases share the same update channel, so stable users also receive beta pushes## Out of Scope- No incremental/delta updates- No in-process self-replacement-- No macOS auto-install- No version-skip, canary releases, or multi-channel distribution- No forced updates+## Version Numbers and Pre-release Rules++Installer naming examples:++| Type | Windows | macOS |+|---|---|---|+| Stable | `JiuwenSwarm-setup-0.2.2.exe` | `JiuwenSwarm-0.2.2.dmg` |+| Pre-release | `JiuwenSwarm-setup-0.2.3.beta1.exe` | `JiuwenSwarm-0.2.3.beta1.dmg` |++Windows and macOS installers for the same version are released together.++Version comparison uses a total-order key `release_sort_key` with these rules:++1. Base version compared numerically first (segment by segment): `0.2.3` > `0.2.2`+2. At the same base, a stable release ranks above any pre-release: `0.2.3` > `0.2.3.beta1`+3. Among pre-releases at the same base, the type decides: `dev` < `alpha` < `beta` < `rc` < `pre`+4. Within the same type, a larger number is newer: `0.2.3.beta2` > `0.2.3.beta1`++Because stable and pre-release releases share a channel, a user running stable `0.2.2` is prompted to update to `0.2.3.beta1` (a higher base version); this is the intended behavior.+## Core Flow1. After app launch, the frontend asynchronously calls `updater.check`-2. The backend requests the GitHub Releases API for the latest release-3. If a new version is found, it records the latest version, publish date, release notes, and installer download URL-4. The user clicks "Download Update" on the Update page-5. The backend downloads the installer to `%USERPROFILE%\\.jiuwenswarm\\.updates` in the background-6. After download completes, the frontend calls the pywebview API to trigger installation-7. The desktop process writes a temporary `cmd` helper script that waits for the current process to exit-8. The helper runs the Inno Setup installer silently, then restarts the application+2. The backend requests the Releases list endpoint and fetches all published releases (including pre-releases, skipping drafts)+3. The newest version is selected by `release_sort_key` and compared against the current `__version__`+4. If a newer version is found, the latest version, publish date, release notes, and the platform-matched installer download URL are recorded+5. The user clicks "Download Update" on the Update page+6. The backend downloads the installer to the `.updates` directory under the user workspace in the background+7. After download completes, the frontend calls the pywebview API `install_update` to trigger installation+8. The desktop process launches the platform-specific helper, which waits for the current process and ports to release, then performs installation (interactive on Windows, silent on macOS / Linux) and restarts the app## Update Source-Default GitHub Releases API:+Desktop defaults to the GitCode Releases list endpoint:```text-https://api.github.com/repos/{owner}/{repo}/releases/latest+https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases```+It can also be switched to GitHub Releases. To discover pre-releases, the backend fetches the full releases list (not the `/latest` endpoint, which excludes pre-releases), skips drafts, keeps prereleases, and picks the newest by version sort. It falls back to `/latest` when the list endpoint is unavailable.+Fields read from the release:-- `tag_name` — latest version number+- `tag_name` — version number (pre-release suffix preserved, e.g. `0.2.3.beta1`)- `body` — release notes- `published_at` — publish date-- `assets[]` — the installer and optional sha256 file+- `assets[]` — the platform-matched installer## Configuration@@ -52,21 +77,29 @@ Update settings are in the `updater` section of `config.yaml`:```yamlupdater:enabled: true- repo_owner: CharlieZhao95+ desktop_release_api_type: gitcode # gitcode | github+ repo_owner: openJiuwenrepo_name: jiuwenswarmrelease_api_url: ""- asset_name_pattern: "jiuwenswarm-setup-{version}.exe"- sha256_name_pattern: "jiuwenswarm-setup-{version}.exe.sha256"+ asset_name_pattern_windows: "JiuwenSwarm-setup-{version}.exe"+ asset_name_pattern_macos: "JiuwenSwarm-{version}.dmg"+ asset_name_pattern_linux: "JiuwenSwarm-{version}.tar.gz"timeout_seconds: 20```+Pip install mode additionally supports a `pypi_mirror` field.+## Backend API-Three WebSocket RPC methods are registered:+The following WebSocket RPC methods are registered:++- `updater.get_status` — query current update status+- `updater.check` — check for updates+- `updater.download` — download the installer (desktop mode) / perform pip upgrade (pip mode)+- `updater.upgrade` — pip mode only, perform upgrade and restart+- `updater.set_conf` — save update configuration-- `updater.get_status`-- `updater.check`-- `updater.download`+In desktop mode, installation is triggered by the frontend via the pywebview API `install_update(installer_path)`, executed directly by the desktop process (it owns the window and can close it before installation).Status values:@@ -77,21 +110,48 @@ Status values:- `downloading`- `downloaded`- `installing`+- `upgrading` (pip mode)+- `restart_pending` / `restarting` (pip mode)- `error`- `unsupported`+- `disabled`## Installation Execution-To avoid replacing files while the main process is running, installation is not performed within the current process.+To avoid replacing files while the main process is running, installation is not performed within the current process. When the desktop process receives an install request from the frontend, it launches a platform-specific helper process/script that completes installation and restart after the main process exits.-When the desktop process receives an install request from the frontend:+### Windows-1. It generates a temporary `cmd` helper script-2. The helper waits for the desktop main process to exit-3. The helper runs the installer with:+The desktop process launches an independent update-helper subprocess via the `update-helper` subcommand, passing the installer path, app executable path, and parent PID. The helper flow:-```text-/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP- /CLOSEAPPLICATIONS-```+1. Wait for the parent process to exit+2. Wait for backend / frontend ports to release (up to 15 seconds)+3. Launch the installer interactively (no silent arguments), showing the Inno Setup wizard++The installer handles elevation (UAC prompt) and file replacement itself via Inno Setup. After the user completes the wizard, the installer is responsible for relaunching the app (Inno Setup's `[Run]` section can be configured to launch the app after install). The helper exits right after launching the installer; the installation is left to the user and the installer.++### macOS++The desktop process generates a bash helper script and launches it independently. The script flow:++1. Wait for the parent process to exit+2. Wait for backend / frontend ports to release (up to 15 seconds)+3. `hdiutil attach` mounts the DMG at a controlled mount point+4. Find the `.app` bundle inside the mount point+5. `ditto` copies the `.app` to a temp target `<install_target>.new`+6. Atomic swap: move the old bundle aside as `<install_target>.old`, move the new one into place, then remove the old one+7. `hdiutil detach` unmounts the DMG and cleans up the mount point+8. `xattr -dr com.apple.quarantine` removes the quarantine attribute+9. `open` launches the new app++The install target is fixed to `/Applications/JiuwenSwarm.app` (derived by walking up from the executable path to the `.app` bundle name).++### Linux++The desktop process generates a bash helper script that, after the parent process exits, backs up the current install directory, extracts the tar.gz into it, removes the backup, and relaunches `jiuwenswarm`.++## Security Notes-4. After installation completes, it restarts `jiuwenswarm.exe`\ No newline at end of file+- All external paths are escaped with `shlex.quote` in helper scripts to prevent shell injection if the release API serves a malicious asset name+- Helper scripts are written to the `.updates` directory under the user workspace, with write permission checked before writing+- The macOS helper writes full execution logs to `update_helper.log` in the logs directorydiff --git a/docs/en/install.md b/docs/en/install.mdindex 6b8e010066..30f45e5355 100644--- a/docs/en/install.md+++ b/docs/en/install.md@@ -62,7 +62,7 @@ curl -L --fail -o JiuwenSwarm-<version>.dmg \On first launch the app creates `~/.jiuwenswarm/`. Then follow [Post-start verification](#3-post-start-verification) to finish model configuration.-> Match the version to the actual download link on the Release page. For Windows auto-update behavior, see [Windows auto-update design](WindowsAutoUpdateDesign.md).+> Match the version to the actual download link on the Release page. For desktop auto-update behavior (Windows and macOS), see [Desktop auto-update design](WindowsAutoUpdateDesign.md).---diff --git a/docs/zh/SUMMARY.md b/docs/zh/SUMMARY.mdindex 80009ab4d3..5976c657e0 100644--- a/docs/zh/SUMMARY.md+++ b/docs/zh/SUMMARY.md@@ -43,7 +43,7 @@- [MCP 配置](MCP配置.md)- [打包 exe 指南](打包exe指南.md)- [ACP 插件使用](ACP插件使用.md)- - [Windows 自动更新设计](windows自动更新设计.md)+ - [桌面端自动更新设计](windows自动更新设计.md)- [日志系统](日志.md)- [开发实践](开发实践/README.md)- [日报生成器开发实践](开发实践/JiuwenSwarm日报生成器开发实践.md)diff --git "a/docs/zh/windows\350\207\252\345\212\250\346\233\264\346\226\260\350\256\276\350\256\241.md" "b/docs/zh/windows\350\207\252\345\212\250\346\233\264\346\226\260\350\256\276\350\256\241.md"index 780ffdbd78..6ae6c59b84 100644--- "a/docs/zh/windows\350\207\252\345\212\250\346\233\264\346\226\260\350\256\276\350\256\241.md"+++ "b/docs/zh/windows\350\207\252\345\212\250\346\233\264\346\226\260\350\256\276\350\256\241.md"@@ -1,49 +1,74 @@-# Windows 自动更新设计+# 桌面端自动更新设计-本文档描述 JiuwenSwarm 在 Windows 桌面版上的最小可用自动更新方案。目标是优先保证稳定性,而不是追求无感升级。+本文档描述 JiuwenSwarm 桌面版(Windows 与 macOS)的自动更新方案。目标是优先保证稳定性,同时覆盖正式版与预发布版(beta)的升级流程。## 目标范围-- 仅支持 Windows 桌面版+- 支持 Windows 与 macOS 桌面版(Linux 桌面版同样适用)- 启动时自动检查一次更新- 用户可在左侧栏 `更新` 页面手动检查更新-- 更新源直接使用 GitHub Release-- 下载产物为 Inno Setup 安装包 `jiuwenswarm-setup-<version>.exe`-- 下载完成后由外部 helper 脚本静默安装并重启应用+- 桌面版更新源默认使用 GitCode Releases,可切换为 GitHub Releases;pip 安装模式使用 PyPI+- 下载产物按平台区分:+ - Windows:Inno Setup 安装包 `JiuwenSwarm-setup-<version>.exe`+ - macOS:DMG 镜像 `JiuwenSwarm-<version>.dmg`+ - Linux:`JiuwenSwarm-<version>.tar.gz`+- 下载完成后由外部 helper 完成安装与重启:Windows 以交互式安装向导完成,macOS / Linux 由 helper 脚本静默安装并重启+- 支持预发布版本:稳定版与预发布版共用同一更新通道,稳定版用户也会收到 beta 推送## 不做的能力- 不做增量更新- 不做运行中自替换-- 不做 macOS 自动安装-- 不做版本忽略、灰度发布、多渠道+- 不做版本忽略、灰度发布、多渠道分流- 不做强制更新+## 版本号与预发布规则++安装包命名示例:++| 类型 | Windows | macOS |+|---|---|---|+| 正式版 | `JiuwenSwarm-setup-0.2.2.exe` | `JiuwenSwarm-0.2.2.dmg` |+| 预发布版 | `JiuwenSwarm-setup-0.2.3.beta1.exe` | `JiuwenSwarm-0.2.3.beta1.dmg` |++同一个版本的 Windows 与 macOS 安装包一起发布。++版本比较采用全序关系 `release_sort_key`,排序规则:++1. 先比较基础版本号(数字逐段比较):`0.2.3` > `0.2.2`+2. 同一基础版本下,正式版高于任意预发布版:`0.2.3` > `0.2.3.beta1`+3. 同一基础版本的预发布之间,按类型排序:`dev` < `alpha` < `beta` < `rc` < `pre`+4. 同一类型下,序号大者为新:`0.2.3.beta2` > `0.2.3.beta1`++由于稳定版与预发布版共用通道,运行 `0.2.2` 稳定版的用户会被提示更新到 `0.2.3.beta1`(更高基础版本),这是设计预期行为。+## 核心流程1. 应用启动后,前端异步调用 `updater.check`-2. 后端请求 GitHub Releases API 获取最新 release-3. 若发现新版本,则记录最新版本、发布时间、说明和安装包下载地址-4. 用户在 `更新` 页点击 `下载更新`-5. 后端后台下载安装包到 `%USERPROFILE%\\.jiuwenswarm\\.updates`-6. 下载完成后,前端调用 pywebview API 触发安装-7. 桌面进程写入临时 `cmd` helper,等待当前进程退出-8. helper 静默执行 Inno Setup 安装包,然后重启应用+2. 后端请求 Releases 列表接口,获取全部已发布版本(含预发布,跳过 draft)+3. 按 `release_sort_key` 选出最新版本,与当前 `__version__` 比较+4. 若发现新版本,记录最新版本、发布时间、更新说明和对应平台的安装包下载地址+5. 用户在 `更新` 页点击 `下载更新`+6. 后端后台下载安装包到用户工作区下的 `.updates` 目录+7. 下载完成后,前端调用 pywebview API `install_update` 触发安装+8. 桌面进程拉起平台对应的 helper,等待当前进程与端口释放后执行安装(Windows 交互式、macOS / Linux 静默)并重启应用## 更新源-默认使用 GitHub Releases API:+桌面版默认使用 GitCode Releases 列表接口:```text-https://api.github.com/repos/{owner}/{repo}/releases/latest+https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases```+也可切换为 GitHub Releases。为了发现预发布版本,后端拉取完整 releases 列表(而非 `/latest` 端点,因为 `/latest` 会排除预发布),跳过 draft、保留 prerelease,再按版本排序取最新。当列表接口不可用时回退到 `/latest`。+从 release 中读取:-- `tag_name` 作为最新版本号+- `tag_name` 作为版本号(保留预发布后缀,如 `0.2.3.beta1`)- `body` 作为更新说明- `published_at` 作为发布时间-- `assets[]` 中的安装包和可选 sha256 文件+- `assets[]` 中按平台匹配的安装包## 配置@@ -52,21 +77,29 @@ https://api.github.com/repos/{owner}/{repo}/releases/latest```yamlupdater:enabled: true- repo_owner: CharlieZhao95+ desktop_release_api_type: gitcode # gitcode | github+ repo_owner: openJiuwenrepo_name: jiuwenswarmrelease_api_url: ""- asset_name_pattern: "jiuwenswarm-setup-{version}.exe"- sha256_name_pattern: "jiuwenswarm-setup-{version}.exe.sha256"+ asset_name_pattern_windows: "JiuwenSwarm-setup-{version}.exe"+ asset_name_pattern_macos: "JiuwenSwarm-{version}.dmg"+ asset_name_pattern_linux: "JiuwenSwarm-{version}.tar.gz"timeout_seconds: 20```+pip 安装模式额外支持 `pypi_mirror` 字段。+## 后端接口-通过现有 WebSocket RPC 注册 3 个方法:+通过 WebSocket RPC 注册以下方法:++- `updater.get_status` — 查询当前更新状态+- `updater.check` — 检查更新+- `updater.download` — 下载安装包(desktop 模式)/ 执行 pip 升级(pip 模式)+- `updater.upgrade` — 仅 pip 模式使用,执行升级并重启+- `updater.set_conf` — 保存更新配置-- `updater.get_status`-- `updater.check`-- `updater.download`+桌面模式下的安装由前端通过 pywebview API `install_update(installer_path)` 触发,由桌面进程直接执行(它持有窗口并能在安装前关闭窗口)。状态字段:@@ -77,21 +110,48 @@ updater:- `downloading`- `downloaded`- `installing`+- `upgrading`(pip 模式)+- `restart_pending` / `restarting`(pip 模式)- `error`- `unsupported`+- `disabled`## 安装执行方式-为了避免主程序运行中替换自身文件,安装动作不在当前进程内完成。+为了避免主程序运行中替换自身文件,安装动作不在当前进程内完成。桌面进程在接到前端安装请求后,按平台拉起独立的 helper 进程/脚本,helper 在主进程退出后完成安装与重启。-桌面进程在接到前端安装请求后:+### Windows-1. 生成临时 `cmd` helper 脚本-2. helper 等待桌面主进程退出-3. helper 运行安装包:+桌面进程通过子命令 `update-helper` 拉起一个独立的更新助手进程,传入安装包路径、应用可执行路径与父进程 PID。助手流程:-```text-/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP- /CLOSEAPPLICATIONS-```+1. 等待父进程退出+2. 等待后端 / 前端端口释放(最多 15 秒)+3. 以交互式方式启动安装包(不带静默参数),弹出 Inno Setup 安装向导++安装包由 Inno Setup 自身处理提权(UAC 弹窗)与文件替换,用户在向导中完成安装后由安装包负责重启应用(Inno Setup 的 `[Run]` 段可配置安装完成后启动应用)。助手在启动安装包后即退出,安装过程交由用户与安装包完成。++### macOS++桌面进程生成一个 bash helper 脚本并独立启动。脚本流程:++1. 等待父进程退出+2. 等待后端 / 前端端口释放(最多 15 秒)+3. `hdiutil attach` 将 DMG 挂载到受控挂载点+4. 在挂载点内查找 `.app` 包+5. `ditto` 将 `.app` 拷贝到临时目标 `<install_target>.new`+6. 原子交换:将旧包移为 `<install_target>.old`、新包就位、删除旧包+7. `hdiutil detach` 卸载 DMG 并清理挂载点+8. `xattr -dr com.apple.quarantine` 去除隔离属性+9. `open` 启动新应用++安装目标固定为 `/Applications/JiuwenSwarm.app`(从可执行路径上溯到 `.app` 包名推导)。++### Linux++桌面进程生成 bash helper 脚本,等待父进程退出后:备份当前安装目录、解压 tar.gz 到安装目录、删除备份、重启 `jiuwenswarm`。++## 安全说明-4. 安装完成后重新启动 `jiuwenswarm.exe`+- 所有外部路径在 helper 脚本中均使用 `shlex.quote` 转义,防止 release 接口返回恶意资源名时发生 shell 注入+- helper 脚本写入用户工作区下的 `.updates` 目录,写入前检查写权限+- macOS helper 将完整执行日志写入日志目录的 `update_helper.log`diff --git "a/docs/zh/\345\256\211\350\243\205\346\214\207\345\215\227.md" "b/docs/zh/\345\256\211\350\243\205\346\214\207\345\215\227.md"index efe0c1d0c5..0bbb66086e 100644--- "a/docs/zh/\345\256\211\350\243\205\346\214\207\345\215\227.md"+++ "b/docs/zh/\345\256\211\350\243\205\346\214\207\345\215\227.md"@@ -65,7 +65,7 @@ curl -L --fail -o JiuwenSwarm-<version>.dmg \首次启动后,系统会创建配置目录 `~/.jiuwenswarm/`,之后请参考 [启动后验证](#3-启动后验证) 完成模型配置。-> 版本号以 Release 页面实际下载链接为准。Windows 桌面版的自动更新方案见 [Windows 自动更新设计](windows自动更新设计.md)。+> 版本号以 Release 页面实际下载链接为准。Windows 与 macOS 桌面端的自动更新方案见 [桌面端自动更新设计](windows自动更新设计.md)。---diff --git a/jiuwenswarm/channels/desktop/desktop_app.py b/jiuwenswarm/channels/desktop/desktop_app.pyindex 0b8c9a7f46..93f306be2d 100644--- a/jiuwenswarm/channels/desktop/desktop_app.py+++ b/jiuwenswarm/channels/desktop/desktop_app.py@@ -6,6 +6,7 @@ import binasciiimport http.clientimport loggingimport os+import shleximport shutilimport signalimport socket@@ -34,6 +35,16 @@ STARTUP_TIMEOUT_SECONDS = 45.0PNG_DATA_URL_PREFIX = "data:image/png;base64,"PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"DesktopSaveResult = dict[str, bool]+UPDATE_CLEANUP_PATTERNS = (+ "JiuwenSwarm-setup-*.exe",+ "JiuwenSwarm-*.dmg",+ "JiuwenSwarm-*.tar.gz",+ "JiuwenSwarm-*.exe.part",+ "JiuwenSwarm-*.dmg.part",+ "JiuwenSwarm-*.tar.gz.part",+ "_install_helper.ps1",+ "_install_helper.sh",+)def _setup_logger() -> logging.Logger:@@ -72,6 +83,27 @@ def _setup_logger() -> logging.Logger:logger = _setup_logger()+def _cleanup_stale_update_artifacts() -> None:+ updates_dir = get_user_workspace_dir() / ".updates"+ if not updates_dir.is_dir():+ return++ removed = 0+ for pattern in UPDATE_CLEANUP_PATTERNS:+ for path in updates_dir.glob(pattern):+ try:+ if path.is_dir():+ shutil.rmtree(path)+ else:+ path.unlink(missing_ok=True)+ removed += 1+ except OSError as exc:+ logger.warning("[desktop] failed to remove stale update artifact %s: %s", path, exc)++ if removed:+ logger.info("[desktop] cleaned %d stale update artifact(s) from %s", removed, updates_dir)++def _desktop_save_result(ok: bool, cancelled: bool = False) -> DesktopSaveResult:return {"ok": ok, "cancelled": cancelled}@@ -468,7 +500,7 @@ class DesktopRuntime:if os.name == "nt":ok = self._launch_windows_install_helper(target, app_executable)elif sys.platform == "darwin":- ok = self._launch_macos_install_helper(target)+ ok = self._launch_macos_install_helper(target, app_executable)else:ok = self._launch_linux_install_helper(target, app_executable)@@ -481,7 +513,7 @@ class DesktopRuntime:return True@staticmethod- def _launch_macos_install_helper(target: Path) -> bool:+ def _launch_macos_install_helper(target: Path, app_executable: Path) -> bool:parent_pid = os.getpid()updates_dir = get_user_workspace_dir() / ".updates"updates_dir.mkdir(parents=True, exist_ok=True)@@ -490,13 +522,139 @@ class DesktopRuntime:logger.error("[desktop] no write permission for updates directory: %s", updates_dir)return False+ # Derive the .app bundle path from the frozen executable.+ # sys.executable is typically:+ # /Applications/JiuwenSwarm.app/Contents/MacOS/jiuwenswarm+ # so the bundle is three levels up. Prefer replacing the exact bundle+ # the user launched, but fall back to /Applications when running from a+ # read-only DMG mount or from a non-bundled development executable.+ app_bundle = app_executable.parent.parent.parent+ if app_bundle.suffix == ".app" and not str(app_bundle).startswith("/Volumes/"):+ install_target = str(app_bundle)+ elif app_bundle.suffix == ".app":+ install_target = f"/Applications/{app_bundle.name}"+ else:+ install_target = "/Applications/JiuwenSwarm.app"++ log_file = get_logs_dir() / "update_helper.log"++ # shlex.quote all external paths to prevent shell injection if the+ # release API serves a malicious asset name.+ q_target = shlex.quote(str(target))+ q_install_target = shlex.quote(install_target)+ q_log_file = shlex.quote(str(log_file))+ q_temp_target = shlex.quote(f"{install_target}.new")+ q_old_target = shlex.quote(f"{install_target}.old")+helper_content = f"""#!/bin/bashset -e-PARENT_PID={parent_pid}-while kill -0 "$PARENT_PID" 2>/dev/null; do++LOG_FILE={q_log_file}+exec >>"$LOG_FILE" 2>&1++echo "=== JiuwenSwarm macOS install helper: $(date) ==="+echo "[helper] dmg={q_target}"+echo "[helper] install_target={q_install_target}"+echo "[helper] parent_pid={parent_pid}"++# Wait for parent process to exit+echo "[helper] waiting for parent pid {parent_pid} to exit"+while kill -0 "{parent_pid}" 2>/dev/null; dosleep 1done-open "{target}"+echo "[helper] parent process exited"++# Wait for backend/frontend ports to release+wait_port_release() {{+ local port=$1+ local name=$2+ local deadline=$(( SECONDS + 15 ))+ while [ $SECONDS -lt $deadline ]; do+ if ! lsof -iTCP:"$port" -sTCP:LISTEN -P -n >/dev/null 2>&1; then+ echo "[helper] port $port ($name) released"+ return 0+ fi+ sleep 0.5+ done+ echo "[helper] warning: port $port ($name) still in use after 15s, proceeding anyway"+}}+wait_port_release {BACKEND_PORT} backend+wait_port_release {FRONTEND_PORT} frontend++# Mount the DMG at a controlled mount point+MOUNT_POINT="/tmp/jiuwenswarm_dmg_{parent_pid}"+rm -rf "$MOUNT_POINT" 2>/dev/null || true+mkdir -p "$MOUNT_POINT"+echo "[helper] attaching DMG at $MOUNT_POINT"+if ! hdiutil attach {q_target} -mountpoint "$MOUNT_POINT" -nobrowse -noautoopen -quiet; then+ echo "[helper] ERROR: hdiutil attach failed"+ rm -rf "$MOUNT_POINT" 2>/dev/null || true+ exit 1+fi++# Find the .app bundle inside the mounted DMG+APP_BUNDLE=$(find "$MOUNT_POINT" -maxdepth 1 -name "*.app" -print -quit)+if [ -z "$APP_BUNDLE" ]; then+ echo "[helper] ERROR: no .app bundle found in DMG"+ hdiutil detach "$MOUNT_POINT" -quiet || true+ rm -rf "$MOUNT_POINT" 2>/dev/null || true+ exit 1+fi+echo "[helper] found app bundle: $APP_BUNDLE"++# Copy to a temp target first. During the final swap, keep the previous bundle+# as OLD_TARGET so a failed install can be rolled back.+TEMP_TARGET={q_temp_target}+OLD_TARGET={q_old_target}+rm -rf "$TEMP_TARGET" 2>/dev/null || true+rm -rf "$OLD_TARGET" 2>/dev/null || true++echo "[helper] copying app to $TEMP_TARGET"+if ! ditto "$APP_BUNDLE" "$TEMP_TARGET"; then+ echo "[helper] ERROR: ditto copy failed"+ rm -rf "$TEMP_TARGET" 2>/dev/null || true+ hdiutil detach "$MOUNT_POINT" -quiet || true+ rm -rf "$MOUNT_POINT" 2>/dev/null || true+ exit 1+fi++restore_old_target() {{+ status=$?+ if [ $status -ne 0 ] && [ -d "$OLD_TARGET" ]; then+ echo "[helper] install failed, restoring previous app bundle"+ rm -rf {q_install_target} 2>/dev/null || true+ mv "$OLD_TARGET" {q_install_target} || true+ fi+ rm -rf "$TEMP_TARGET" 2>/dev/null || true+ hdiutil detach "$MOUNT_POINT" -quiet || true+ rm -rf "$MOUNT_POINT" 2>/dev/null || true+ exit $status+}}+trap restore_old_target EXIT++# Install: move the old app aside, move the verified new bundle into place,+# and let the EXIT trap restore OLD_TARGET if a step fails.+if [ -d {q_install_target} ]; then+ echo "[helper] backing up existing app bundle to $OLD_TARGET"+ mv {q_install_target} "$OLD_TARGET"+fi+mv "$TEMP_TARGET" {q_install_target}++trap - EXIT+rm -rf "$OLD_TARGET" 2>/dev/null || true+echo "[helper] install complete: {q_install_target}"++# Detach DMG and clean up mount point+hdiutil detach "$MOUNT_POINT" -quiet || true+rm -rf "$MOUNT_POINT" 2>/dev/null || true++# Remove quarantine attribute from downloaded DMG contents+xattr -dr com.apple.quarantine {q_install_target} 2>/dev/null || true++# Launch the new app+echo "[helper] launching {q_install_target}"+open {q_install_target} || echo "[helper] WARNING: failed to launch app"+echo "=== install helper finished: $(date) ===""""helper_path = updates_dir / "_install_helper.sh"helper_path.write_text(helper_content, encoding="utf-8")@@ -508,7 +666,10 @@ open "{target}"stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,)- logger.info("[desktop] macOS install helper launched, target=%s", target)+ logger.info(+ "[desktop] macOS install helper launched, target=%s, install_target=%s",+ target, install_target,+ )return True@staticmethod@@ -524,6 +685,13 @@ open "{target}"install_dir = str(app_executable.parent.resolve())backup_dir = f"{install_dir}.bak.$RANDOM"+ # shlex.quote all external paths to prevent shell injection if the+ # release API serves a malicious asset name.+ q_target = shlex.quote(str(target))+ q_install_dir = shlex.quote(install_dir)+ q_backup_dir = shlex.quote(backup_dir)+ q_executable = shlex.quote(f"{install_dir}/jiuwenswarm")+helper_content = f"""#!/bin/bashset -ePARENT_PID={parent_pid}@@ -531,14 +699,14 @@ while kill -0 "$PARENT_PID" 2>/dev/null; dosleep 1done-BACKUP="{backup_dir}"-if [ -d "{install_dir}" ]; then- mv "{install_dir}" "$BACKUP"+BACKUP={q_backup_dir}+if [ -d {q_install_dir} ]; then+ mv {q_install_dir} "$BACKUP"fi-mkdir -p "{install_dir}"-tar xzf "{target}" -C "{install_dir}"+mkdir -p {q_install_dir}+tar xzf {q_target} -C {q_install_dir}rm -rf "$BACKUP" 2>/dev/null || true-nohup "{install_dir}/jiuwenswarm" >/dev/null 2>&1 &+nohup {q_executable} >/dev/null 2>&1 &"""helper_path = updates_dir / "_install_helper.sh"helper_path.write_text(helper_content, encoding="utf-8")@@ -882,6 +1050,7 @@ def main() -> None:_launch_windows_installer_helper(args.installer_path, args.app_executable, args.parent_pid)return+ _cleanup_stale_update_artifacts()_setup_tui_path()runtime = DesktopRuntime(diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex ddacdb3748..8a900a6605 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -486,19 +486,23 @@ function AppContent() {}, [request, t, setAvailableModels]);useEffect(() => {- if (!FEATURE_APP_UPDATER_UI || !isConnected || !initialDataLoaded || startupUpdateCheckRef.current) {+ if (!FEATURE_APP_UPDATER_UI || !isConnected || startupUpdateCheckRef.current) {return;}startupUpdateCheckRef.current = true;const timeoutId = window.setTimeout(() => {- void request('updater.check', { manual: false }).catch((updateError) => {- console.warn('Startup updater check failed:', updateError);- });- }, 30000);+ void request('updater.check', { manual: false })+ .then((payload) => {+ window.dispatchEvent(new CustomEvent('jiuwenswarm:updater-status', { detail: payload }));+ })+ .catch((updateError) => {+ console.warn('Startup updater check failed:', updateError);+ });+ }, 5000);return () => {window.clearTimeout(timeoutId);};- }, [initialDataLoaded, isConnected, request]);+ }, [isConnected, request]);const clearRestartAutoCloseTimer = useCallback(() => {if (restartAutoCloseTimerRef.current != null) {diff --git a/jiuwenswarm/channels/web/frontend/src/components/UpdatePanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/UpdatePanel/index.tsxindex 250369c528..60c29f167e 100644--- a/jiuwenswarm/channels/web/frontend/src/components/UpdatePanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/UpdatePanel/index.tsx@@ -68,6 +68,8 @@ function formatPublishedAt(value: string, locale: string): string {}).format(date);}+const UPDATER_STATUS_EVENT = 'jiuwenswarm:updater-status';+export function UpdatePanel({ isConnected, request }: UpdatePanelProps) {const { t, i18n } = useTranslation();const [status, setStatus] = useState<UpdateStatusPayload | null>(null);@@ -106,7 +108,27 @@ export function UpdatePanel({ isConnected, request }: UpdatePanelProps) {}, [refreshConfig, refreshStatus]);useEffect(() => {- if (normalizeString(status?.state) !== 'downloading' && normalizeString(status?.state) !== 'upgrading') {+ const handleUpdaterStatus = (event: Event) => {+ const payload = (event as CustomEvent<UpdateStatusPayload>).detail;+ if (!payload || typeof payload !== 'object') {+ return;+ }+ setStatus(payload);+ setError(normalizeString(payload.error) || null);+ };+ window.addEventListener(UPDATER_STATUS_EVENT, handleUpdaterStatus);+ return () => {+ window.removeEventListener(UPDATER_STATUS_EVENT, handleUpdaterStatus);+ };+ }, []);++ useEffect(() => {+ if (+ normalizeString(status?.state) !== 'checking' &&+ normalizeString(status?.state) !== 'downloading' &&+ normalizeString(status?.state) !== 'upgrading' &&+ normalizeString(status?.state) !== 'installing'+ ) {return;}const timer = window.setInterval(() => {@@ -174,13 +196,18 @@ export function UpdatePanel({ isConnected, request }: UpdatePanelProps) {setError(t('updatePanel.errors.installUnavailable'));return;}+ // Optimistically switch to "installing" so the UI reflects the in-progress+ // state before the desktop app closes the window.+ setStatus((prev) => ({ ...(prev ?? {}), state: 'installing', installing: true }));try {const ok = await api.install_update(installerPath);if (!ok) {setError(t('updatePanel.errors.installFailed'));+ setStatus((prev) => ({ ...(prev ?? {}), state: 'downloaded', installing: false }));}} catch (installError) {setError(installError instanceof Error ? installError.message : t('updatePanel.errors.installFailed'));+ setStatus((prev) => ({ ...(prev ?? {}), state: 'downloaded', installing: false }));}}, [status?.downloaded_path, t]);diff --git a/jiuwenswarm/common/updater.py b/jiuwenswarm/common/updater.pyindex dadc6c7f64..875535ce8d 100644--- a/jiuwenswarm/common/updater.py+++ b/jiuwenswarm/common/updater.py@@ -1,7 +1,6 @@from __future__ import annotationsimport os-import reimport signalimport sysimport threading@@ -19,8 +18,6 @@ from jiuwenswarm.common.version_source import (GitCodeReleasesSource,PyPIVersionSource,ReleaseInfo,- is_prerelease_version,- strip_prerelease_suffix,)DEFAULT_RELEASE_API_GITCODE = "https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases/latest"@@ -30,7 +27,7 @@ DEFAULT_ASSET_PATTERN_WINDOWS = "JiuwenSwarm-setup-{version}.exe"DEFAULT_ASSET_PATTERN_MACOS = "JiuwenSwarm-{version}.dmg"DEFAULT_ASSET_PATTERN_LINUX = "JiuwenSwarm-{version}.tar.gz"DEFAULT_TIMEOUT_SECONDS = 20-DEFAULT_TEXT = "HzUzzbjzJNsWmfsdiy2GKcEg"+DEFAULT_TEXT = "WbrW92Yn6jif-4Ks3kvzhWVv"DESKTOP_ENV_FLAG = "JIUWENSWARM_DESKTOP"@@ -38,61 +35,20 @@ def get_access_token() -> str:return os.getenv("GITCODE_TOKEN", "").strip() or DEFAULT_TEXT-def _normalize_version(raw: str) -> str:- return (raw or "").strip().lstrip("vV")---def _version_key(version: str) -> tuple[int, ...]:- numbers = re.findall(r"\d+", _normalize_version(version))- return tuple(int(part) for part in numbers) or (0,)---def _base_version_key(version: str) -> tuple[int, ...]:- """Numeric key for the *base* version with pre-release suffix removed.-- ``0.2.0.beta1`` and ``0.2.0`` both yield ``(0, 2, 0)``.- """- return _version_key(strip_prerelease_suffix(version))--def _is_newer_version(candidate: str, current: str) -> bool:"""Return True when *candidate* is a newer release than *current*.- Pre-release rules:- - A stable release is always newer than a pre-release with the same base version.- e.g. 0.2.0 > 0.2.0.beta1- - A pre-release is *never* considered newer than a stable release with the same- base version. e.g. 0.2.0.rc1 is NOT newer than 0.2.0- - Between two pre-releases (or two stables) the numeric components decide.+ Pre-release rules (consistent with :func:`release_sort_key`):+ - Base version compared numerically first (``0.2.3`` > ``0.2.2``).+ - A stable release is always newer than a pre-release with the same base+ version (``0.2.3`` > ``0.2.3.beta1``).+ - Among pre-releases at the same base, the type decides first:+ dev < alpha < beta < rc < pre.+ - Within the same type, a larger pre-release number is newer+ (``0.2.3.beta2`` > ``0.2.3.beta1``)."""- candidate_base = _base_version_key(candidate)- current_base = _base_version_key(current)- max_len = max(len(candidate_base), len(current_base))- candidate_padded = candidate_base + (0,) * (max_len - len(candidate_base))- current_padded = current_base + (0,) * (max_len - len(current_base))-- if candidate_padded > current_padded:- return True- if candidate_padded < current_padded:- return False-- # Same base — pre-release vs stable decides- current_is_pre = is_prerelease_version(current)- candidate_is_pre = is_prerelease_version(candidate)- if current_is_pre and not candidate_is_pre:- return True # stable > pre-release- if candidate_is_pre and not current_is_pre:- return False # pre-release < stable-- # Both pre-release (e.g. 0.2.0.beta2 vs 0.2.0.beta1) — full segments decide- if candidate_is_pre and current_is_pre:- candidate_full = _version_key(candidate)- current_full = _version_key(current)- max_full = max(len(candidate_full), len(current_full))- return (candidate_full + (0,) * (max_full - len(candidate_full))- > current_full + (0,) * (max_full - len(current_full)))-- return False+ from jiuwenswarm.common.version_source import release_sort_key+ return release_sort_key(candidate) > release_sort_key(current)def _detect_install_mode() -> str:@@ -205,6 +161,20 @@ class UpdaterService:if status["state"] in ("downloading", "upgrading"):return status+ if not status.get("has_update"):+ self._update_status(+ state="error",+ error="No update available. Please run an update check first.",+ )+ return self.get_status()++ if install_mode == "desktop" and not status.get("download_url"):+ self._update_status(+ state="error",+ error="No download URL resolved. Please run an update check first.",+ )+ return self.get_status()+config = self._load_config()executor = create_executor(install_mode,@@ -230,18 +200,23 @@ class UpdaterService:thread.start()return self.get_status()- def mark_installing(self, installer_path: str) -> dict[str, Any]:- self._update_status(- state="installing",- installing=True,- downloaded_path=installer_path,- error="",- )- return self.get_status()-def start_upgrade(self) -> dict[str, Any]:status = self.get_status()install_mode = status.get("install_mode", "desktop")++ # Desktop installs are driven by the desktop app via the pywebview+ # install_update API (it owns the window and can close it). This WS+ # method only handles pip-mode restarts.+ if install_mode != "pip":+ self._update_status(+ state="error",+ error=(+ "Desktop upgrades are handled by the desktop app via "+ "install_update. This method is only for pip mode."+ ),+ )+ return self.get_status()+config = self._load_config()executor = create_executor(install_mode,@@ -249,9 +224,8 @@ class UpdaterService:self._executor_callback,)- pip_state = "restarting" if install_mode == "pip" else "installing"self._update_status(- state=pip_state,+ state="restarting",installing=True,error="",)@@ -265,8 +239,7 @@ class UpdaterService:)return self.get_status()- if install_mode == "pip":- threading.Timer(3.0, os.kill, args=[os.getpid(), signal.SIGTERM]).start()+ threading.Timer(3.0, os.kill, args=[os.getpid(), signal.SIGTERM]).start()return self.get_status()@@ -346,8 +319,12 @@ class UpdaterService:def _resolve_desktop_asset(self, config: dict[str, Any], release: ReleaseInfo) -> None:platform_key = _platform_asset_key()pattern_key = f"asset_name_pattern_{platform_key}"- asset_name_pattern = config.get(pattern_key) or config.get("asset_name_pattern_windows",- DEFAULT_ASSET_PATTERN_WINDOWS)+ default_pattern = {+ "windows": DEFAULT_ASSET_PATTERN_WINDOWS,+ "macos": DEFAULT_ASSET_PATTERN_MACOS,+ "linux": DEFAULT_ASSET_PATTERN_LINUX,+ }.get(platform_key, DEFAULT_ASSET_PATTERN_WINDOWS)+ asset_name_pattern = config.get(pattern_key) or default_patternasset_name = asset_name_pattern.format(version=release.version)matched = next((a for a in release.assets if a.name == asset_name), None)@@ -423,6 +400,8 @@ class UpdaterService:except (TypeError, ValueError):timeout_seconds = DEFAULT_TIMEOUT_SECONDS+ global_asset_name_pattern = updater.get("asset_name_pattern")+return {"enabled": bool(updater.get("enabled", True)),"desktop_release_api_type": desktop_api_type,@@ -432,15 +411,19 @@ class UpdaterService:"repo_name": repo,"release_api_url": release_api_url,"asset_name_pattern_windows": str(- updater.get("asset_name_pattern")- or updater.get("asset_name_pattern_windows")+ updater.get("asset_name_pattern_windows")+ or global_asset_name_patternor DEFAULT_ASSET_PATTERN_WINDOWS),"asset_name_pattern_macos": str(- updater.get("asset_name_pattern_macos") or DEFAULT_ASSET_PATTERN_MACOS+ updater.get("asset_name_pattern_macos")+ or global_asset_name_pattern+ or DEFAULT_ASSET_PATTERN_MACOS),"asset_name_pattern_linux": str(- updater.get("asset_name_pattern_linux") or DEFAULT_ASSET_PATTERN_LINUX+ updater.get("asset_name_pattern_linux")+ or global_asset_name_pattern+ or DEFAULT_ASSET_PATTERN_LINUX),"timeout_seconds": timeout_seconds,"access_token": get_access_token(),diff --git a/jiuwenswarm/common/upgrade_executor.py b/jiuwenswarm/common/upgrade_executor.pyindex f627d8f323..65b4af3ea7 100644--- a/jiuwenswarm/common/upgrade_executor.py+++ b/jiuwenswarm/common/upgrade_executor.py@@ -42,9 +42,11 @@ class UpgradeExecutor(ABC):def install(self) -> None:...- @abstractmethoddef upgrade(self) -> None:- ...+ """Default upgrade raises; overridden by executors that install."""+ raise NotImplementedError(+ f"{type(self).__name__} does not implement upgrade()"+ )@staticmethoddef _fetch_text(url: str, headers: dict[str, str], timeout: int) -> str:@@ -118,131 +120,6 @@ class DesktopExecutor(UpgradeExecutor):"downloaded_bytes": 0,})- def upgrade(self) -> None:- installer_path = str(self._config.get("downloaded_path", ""))- if not installer_path or not Path(installer_path).is_file():- self._status_callback({- "state": "error",- "error": "Installer not found. Please download first.",- })- return-- self._status_callback({"state": "installing", "installing": True, "error": ""})-- platform = sys.platform- try:- if platform == "win32":- self._upgrade_windows(installer_path)- elif platform == "darwin":- self._upgrade_macos(installer_path)- else:- self._upgrade_linux(installer_path)- except Exception as exc:- self._status_callback({- "state": "error",- "error": f"Install failed: {exc}",- })-- def _upgrade_windows(self, installer_path: str) -> None:- target = Path(installer_path).resolve()- parent_pid = os.getpid()- helper_content = f"""@echo off-setlocal-set "SELF_PID={parent_pid}"-:WAIT_PARENT-tasklist /fi "PID eq %SELF_PID%" 2>nul | find "%SELF_PID%" >nul-if not errorlevel 1 (- timeout /t 1 /nobreak >nul- goto WAIT_PARENT-)-start "" "{target}"-"""- helper_path = _updates_dir() / "_install_helper.cmd"- helper_path.write_text(helper_content, encoding="utf-8")-- subprocess.Popen(- [str(helper_path)],- creationflags=(- getattr(subprocess, "DETACHED_PROCESS", 0)- | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)- | getattr(subprocess, "CREATE_NO_WINDOW", 0)- ),- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )-- def _upgrade_macos(self, installer_path: str) -> None:- target = Path(installer_path).resolve()- parent_pid = os.getpid()-- helper_content = f"""#!/bin/bash-set -e-PARENT_PID={parent_pid}-while kill -0 "$PARENT_PID" 2>/dev/null; do- sleep 1-done-open "{target}"-"""- helper_path = _updates_dir() / "_install_helper.sh"- helper_path.write_text(helper_content, encoding="utf-8")- helper_path.chmod(0o755)-- subprocess.Popen(- ["/bin/bash", str(helper_path)],- start_new_session=True,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )-- def _upgrade_linux(self, installer_path: str) -> None:- target = Path(installer_path).resolve()- parent_pid = os.getpid()-- if getattr(sys, "frozen", False):- install_dir = str(Path(sys.executable).parent.resolve())- backup_dir = f"{install_dir}.bak.$RANDOM"-- helper_content = f"""#!/bin/bash-set -e-PARENT_PID={parent_pid}-while kill -0 "$PARENT_PID" 2>/dev/null; do- sleep 1-done--BACKUP="{backup_dir}"-if [ -d "{install_dir}" ]; then- mv "{install_dir}" "$BACKUP"-fi-mkdir -p "{install_dir}"-tar xzf "{target}" -C "{install_dir}"-rm -rf "$BACKUP" 2>/dev/null || true-nohup "{install_dir}/jiuwenswarm" >/dev/null 2>&1 &-"""- else:- stored_argv = [sys.argv[0]] + sys.argv[1:]- restart_cmd = subprocess.list2cmdline(stored_argv)-- helper_content = f"""#!/bin/bash-set -e-PARENT_PID={parent_pid}-while kill -0 "$PARENT_PID" 2>/dev/null; do- sleep 1-done--tar xzf "{target}" -C /tmp/jiuwenswarm_update-nohup {restart_cmd} >/dev/null 2>&1 &-"""- helper_path = _updates_dir() / "_install_helper.sh"- helper_path.write_text(helper_content, encoding="utf-8")- helper_path.chmod(0o755)-- subprocess.Popen(- ["/bin/bash", str(helper_path)],- start_new_session=True,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )-def _download_file(self,url: str,diff --git a/jiuwenswarm/common/version_source.py b/jiuwenswarm/common/version_source.pyindex 4c7d29af95..b2d680d8e7 100644--- a/jiuwenswarm/common/version_source.py+++ b/jiuwenswarm/common/version_source.py@@ -9,7 +9,7 @@ from abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom typing import Anyfrom urllib.error import HTTPError, URLError-from urllib.parse import urljoin+from urllib.parse import parse_qsl, urlencode, urljoin, urlsplit, urlunsplitfrom urllib.request import Request, urlopenfrom jiuwenswarm.common.version import __version__@@ -50,6 +50,71 @@ def strip_prerelease_suffix(version: str) -> str:return normalized+def release_sort_key(version: str) -> tuple[tuple[int, ...], int, tuple[int, ...]]:+ """Total-order key so that newer versions sort higher.++ Ordering rules:+ - Base version compared numerically first (``0.2.3`` > ``0.2.2``).+ - At the same base, a stable release ranks above any pre-release+ (``0.2.3`` > ``0.2.3.beta1``).+ - Among pre-releases at the same base, the pre-release type decides first:+ dev < alpha < beta < rc < pre (``0.2.3.alpha2`` < ``0.2.3.beta1``).+ - Within the same pre-release type, a larger number is newer+ (``0.2.3.beta2`` > ``0.2.3.beta1``).+ """+ normalized = (version or "").strip().lstrip("vV")+ base = strip_prerelease_suffix(normalized)+ base_key = tuple(int(n) for n in re.findall(r"\d+", base)) or (0,)+ is_pre = is_prerelease_version(normalized)+ # Stable (5) outranks any pre-release at the same base.+ pre_type_rank = 5 if not is_pre else _PRERELEASE_TYPE_ORDER.get(+ _detect_prerelease_type(normalized), 0+ )+ pre_num: tuple[int, ...] = (0,)+ if is_pre:+ m = re.search(+ r"(?:alpha|beta|rc|dev|pre|a|b)\D*(\d+)",+ normalized,+ re.IGNORECASE,+ )+ if m:+ pre_num = (int(m.group(1)),)+ return (base_key, pre_type_rank, pre_num)+++def _detect_prerelease_type(version: str) -> str:+ """Return the lowercase pre-release type marker found in *version*.++ Returns one of ``"dev"``, ``"alpha"``, ``"beta"``, ``"rc"``, ``"pre"``+ or ``""`` when the single-letter forms ``a``/``b`` are used.+ """+ lowered = (version or "").lower()+ for marker in ("dev", "alpha", "beta", "rc", "pre"):+ if marker in lowered:+ return marker+ if re.search(r"(?<![a-z])a(?=\d|[.\-_])", lowered):+ return "alpha"+ if re.search(r"(?<![a-z])b(?=\d|[.\-_])", lowered):+ return "beta"+ return ""+++# Pre-release type ordering: dev < alpha < beta < rc < pre < stable.+_PRERELEASE_TYPE_ORDER: dict[str, int] = {+ "dev": 0,+ "alpha": 1,+ "beta": 2,+ "rc": 3,+ "pre": 4,+ "": 0,+}+++def _is_draft_entry(data: dict) -> bool:+ """Return True when a release dict is an unpublished draft."""+ return bool(data.get("draft"))++def _is_prerelease_entry(data: dict) -> bool:"""Return True when a release dict is a pre-release or draft."""return bool(@@ -69,13 +134,21 @@ def _unwrap_list(raw: Any) -> list | None:if isinstance(raw, list):return rawif isinstance(raw, dict):- for key in ("data", "items", "releases", "results"):+ for key in ("data", "items", "releases", "results", "value"):candidate = raw.get(key)if isinstance(candidate, list):return candidatereturn None+def _with_query_params(url: str, **params: str | int) -> str:+ """Return *url* with query parameters added without dropping existing ones."""+ parts = urlsplit(url)+ query = dict(parse_qsl(parts.query, keep_blank_values=True))+ query.update({key: str(value) for key, value in params.items()})+ return urlunsplit(parts._replace(query=urlencode(query)))++@dataclassclass ReleaseAsset:name: str@@ -108,8 +181,82 @@ class VersionSource(ABC):@staticmethoddef _clean_version(raw: str) -> str:cleaned = (raw or "").strip().lstrip("vV")- match = re.search(r"\d+(?:\.\d+)*", cleaned)- return match.group() if match else cleaned+ # Match the full version including any pre-release suffix (e.g.+ # "0.2.3.beta1") so beta releases keep their suffix for asset matching+ # and version comparison.+ match = re.search(+ r"\d+(?:\.\d+)*(?:[.\-_]?(?:alpha|beta|rc|dev|pre|a|b)(?:\.?\d+)?)*",+ cleaned,+ re.IGNORECASE,+ )+ return match.group() if match else ""++ @classmethod+ def _best_version_from_texts(cls, values: list[str]) -> str:+ versions = [cls._clean_version(value) for value in values]+ versions = [version for version in versions if version]+ if not versions:+ return ""+ return max(versions, key=release_sort_key)++ @classmethod+ def _best_version_from_release_data(cls, data: dict, assets_raw: list) -> str:+ """Resolve a release version from tags, names, and asset filenames.++ Some release APIs can omit or normalize the tag for pre-releases. The+ desktop installers still carry the canonical version in their filenames,+ so include asset names when selecting the newest release.+ """+ candidates = [+ str(data.get("tag_name") or ""),+ str(data.get("tag") or ""),+ str(data.get("version") or ""),+ str(data.get("name") or ""),+ ]+ candidates.extend(+ str(item.get("name") or "")+ for item in assets_raw+ if isinstance(item, dict)+ )+ return cls._best_version_from_texts(candidates)++ def _fetch_newest_from_list(+ self, list_url: str, headers: dict[str, str]+ ) -> ReleaseInfo | None:+ """Fetch the releases list and return the newest entry (incl. pre-releases).++ Drafts are skipped; pre-releases are included so that beta channels are+ detected. Returns None when the list cannot be fetched or is empty.+ """+ try:+ raw = self._fetch_json(list_url, headers)+ except Exception as exc:+ logger.warning(+ "Failed to fetch releases list from %s (falling back to "+ "/latest, which excludes pre-releases): %s",+ list_url, exc,+ )+ return None+ entries = _unwrap_list(raw)+ if entries is None:+ return None+ best: ReleaseInfo | None = None+ best_key: tuple = ()+ for entry in entries:+ if not isinstance(entry, dict) or _is_draft_entry(entry):+ continue+ release = self._parse_release(entry)+ if release is None:+ continue+ key = release_sort_key(release.version)+ if best is None or key > best_key:+ best = release+ best_key = key+ return best++ def _parse_release(self, data: dict) -> ReleaseInfo | None:+ """Parse a single release dict. Override in subclasses."""+ raise NotImplementedErrordef _fetch_json(self, url: str, headers: dict[str, str] | None = None) -> Any:return json.loads(self._fetch_text(url, headers))@@ -143,20 +290,34 @@ class GitHubReleasesSource(VersionSource):super().__init__(name=repo, timeout_seconds=timeout_seconds)self._api_url = api_url or GITHUB_API.format(owner=owner, repo=repo)self._token = token+ # Derive the releases-list URL from the latest-release URL so that+ # pre-releases are also discoverable (the /latest endpoint excludes them).+ self._list_url = _with_query_params(+ self._api_url.removesuffix("/latest"),+ per_page=100,+ )def fetch_latest(self) -> ReleaseInfo:headers = self._build_headers()+ release = self._fetch_newest_from_list(self._list_url, headers)+ if release is not None:+ return release++ # Fallback to /latest (stable-only) when the list endpoint is unusable.data = self._fetch_json(self._api_url, headers)- tag_name = str(data.get("tag_name") or "")- version = self._clean_version(tag_name)- if not version:+ release = self._parse_release(data)+ if release is None:raise RuntimeError("GitHub release tag_name is missing or empty.")+ return release+ def _parse_release(self, data: dict) -> ReleaseInfo | None:published_at = str(data.get("published_at") or "")body = str(data.get("body") or "")- prerelease = bool(data.get("prerelease") or data.get("draft"))-+ prerelease = _is_prerelease_entry(data)assets_raw = data.get("assets") or []+ version = self._best_version_from_release_data(data, assets_raw)+ if not version:+ return Noneassets = [ReleaseAsset(name=str(item.get("name", "")),@@ -166,7 +327,6 @@ class GitHubReleasesSource(VersionSource):for item in assets_rawif isinstance(item, dict) and item.get("name")]-return ReleaseInfo(version=version,release_notes=body,@@ -199,75 +359,27 @@ class GitCodeReleasesSource(VersionSource):self._api_url = api_url or GITCODE_API.format(owner=owner, repo=repo)self._access_token = access_token# Derive the releases-list URL from the latest-release URL.- self._list_url = (- self._api_url.replace("/latest", "")- if "/latest" in self._api_url- else self._api_url+ self._list_url = _with_query_params(+ self._api_url.removesuffix("/latest"),+ per_page=100,)def fetch_latest(self) -> ReleaseInfo:headers = self._build_headers()- data = self._fetch_json(self._api_url, headers)+ release = self._fetch_newest_from_list(self._list_url, headers)+ if release is not None:+ return release+ # Fallback to the /latest endpoint when the list endpoint is unusable.+ data = self._fetch_json(self._api_url, headers)if not isinstance(data, dict):raise RuntimeError(f"Unexpected GitCode API response type: {type(data)}")-release = self._parse_release(data)if release is None:raise RuntimeError("GitCode release tag_name is missing or empty.")-- # If the /latest endpoint returned a pre-release, walk the releases list- # to find the newest stable release instead.- if release.prerelease:- try:- stable = self._fetch_latest_stable(headers)- if stable is not None:- return stable- except Exception:- logger.warning("Failed to fetch latest stable release, using /latest result instead: %s",- release.version)-return release- def _fetch_latest_stable(self, headers: dict[str, str]) -> ReleaseInfo | None:- """Fetch the releases list, find the newest non-prerelease by version."""- raw = self._fetch_json(self._list_url, headers)-- # Normalise wrapped responses (some APIs wrap lists in a dict)- entries = _unwrap_list(raw)- if entries is None:- return None-- best: ReleaseInfo | None = None- best_key: tuple[int, ...] = ()-- for entry in entries:- if not isinstance(entry, dict):- continue- if _is_prerelease_entry(entry):- continue- release = self._parse_release(entry)- if release is None:- continue- key = self._version_key_for_cmp(release.version)- if best is None or key > best_key:- best = release- best_key = key-- return best-- @staticmethod- def _version_key_for_cmp(version: str) -> tuple[int, ...]:- numbers = re.findall(r"\d+", strip_prerelease_suffix(version))- return tuple(int(part) for part in numbers) or (0,)-- @staticmethod- def _parse_release(data: dict) -> ReleaseInfo | None:- tag_name = str(data.get("tag_name") or "")- version = VersionSource._clean_version(tag_name)- if not version:- return None-+ def _parse_release(self, data: dict) -> ReleaseInfo | None:release_notes = str(data.get("body") or data.get("description") or "")published_at = str(data.get("published_at")@@ -277,6 +389,9 @@ class GitCodeReleasesSource(VersionSource):prerelease = _is_prerelease_entry(data)assets_raw = data.get("assets") or []+ version = VersionSource._best_version_from_release_data(data, assets_raw)+ if not version:+ return Noneassets = [ReleaseAsset(name=str(item.get("name", "")),@@ -345,10 +460,8 @@ class PyPIVersionSource(VersionSource):if not versions:raise RuntimeError("Could not parse any version from .whl filenames.")- # Prefer the latest *stable* version; fall back to pre-release if none exist- stable_versions = {v for v in versions if not is_prerelease_version(v)}- pool = stable_versions if stable_versions else versions- latest_version = max(pool, key=self._version_key)+ # Pick the newest version overall, including pre-releases (beta channel).+ latest_version = max(versions, key=release_sort_key)latest_whls = [e for e in whl_entries if latest_version in e.get("filename", "")]latest_whl = latest_whls[-1] if latest_whls else whl_entries[-1]@@ -397,8 +510,3 @@ class PyPIVersionSource(VersionSource):def _resolve_url(self, url: str) -> str:return urljoin(self._api_url, url)-- @staticmethod- def _version_key(version: str) -> tuple[int, ...]:- numbers = re.findall(r"\d+", version)- return tuple(int(part) for part in numbers) or (0,)\ No newline at end of filediff --git a/tests/unit_tests/test_updater_install_mode.py b/tests/unit_tests/test_updater_install_mode.pyindex 826d10fb1e..87efc840e4 100644--- a/tests/unit_tests/test_updater_install_mode.py+++ b/tests/unit_tests/test_updater_install_mode.py@@ -35,3 +35,159 @@ def test_desktop_env_keeps_gitcode_release_source(monkeypatch):assert config["release_api_url"] == ("https://api.gitcode.com/api/v5/repos/openJiuwen/jiuwenswarm/releases/latest")+++def test_global_asset_name_pattern_applies_to_all_platforms(monkeypatch):+ monkeypatch.delattr(sys, "frozen", raising=False)+ monkeypatch.setenv("JIUWENSWARM_DESKTOP", "1")+ monkeypatch.setattr(+ updater,+ "get_config_raw",+ lambda: {+ "updater": {+ "asset_name_pattern": "MyApp-{version}.pkg",+ }+ },+ )++ config = updater.UpdaterService._load_config()++ assert config["asset_name_pattern_windows"] == "MyApp-{version}.pkg"+ assert config["asset_name_pattern_macos"] == "MyApp-{version}.pkg"+ assert config["asset_name_pattern_linux"] == "MyApp-{version}.pkg"+++def test_platform_asset_name_pattern_overrides_global_pattern(monkeypatch):+ monkeypatch.delattr(sys, "frozen", raising=False)+ monkeypatch.setenv("JIUWENSWARM_DESKTOP", "1")+ monkeypatch.setattr(+ updater,+ "get_config_raw",+ lambda: {+ "updater": {+ "asset_name_pattern": "MyApp-{version}.pkg",+ "asset_name_pattern_windows": "MyAppSetup-{version}.exe",+ "asset_name_pattern_macos": "MyApp-{version}.dmg",+ "asset_name_pattern_linux": "MyApp-{version}.tar.gz",+ }+ },+ )++ config = updater.UpdaterService._load_config()++ assert config["asset_name_pattern_windows"] == "MyAppSetup-{version}.exe"+ assert config["asset_name_pattern_macos"] == "MyApp-{version}.dmg"+ assert config["asset_name_pattern_linux"] == "MyApp-{version}.tar.gz"+++def test_gitcode_release_version_can_be_inferred_from_beta_asset_name():+ from jiuwenswarm.common.version_source import GitCodeReleasesSource++ source = GitCodeReleasesSource(owner="openJiuwen", repo="jiuwenswarm")+ release = source._parse_release({+ "tag_name": "0.2.2",+ "name": "JiuwenSwarm",+ "assets": [+ {+ "name": "JiuwenSwarm-setup-0.2.2.exe",+ "url": "https://example.test/JiuwenSwarm-setup-0.2.2.exe",+ },+ {+ "name": "JiuwenSwarm-setup-0.2.3.beta1.exe",+ "url": "https://example.test/JiuwenSwarm-setup-0.2.3.beta1.exe",+ },+ ],+ })++ assert release is not None+ assert release.version == "0.2.3.beta1"+++def test_gitcode_release_list_value_wrapper_includes_prerelease(monkeypatch):+ from jiuwenswarm.common.version_source import GitCodeReleasesSource++ source = GitCodeReleasesSource(owner="openJiuwen", repo="jiuwenswarm")++ monkeypatch.setattr(+ source,+ "_fetch_json",+ lambda url, headers: {+ "Count": 2,+ "value": [+ {+ "tag_name": "JiuwenSwarm0.2.2",+ "release_status": "latest",+ "assets": [+ {+ "name": "JiuwenSwarm-setup-0.2.2.exe",+ "url": "https://example.test/JiuwenSwarm-setup-0.2.2.exe",+ },+ ],+ },+ {+ "tag_name": "0.2.3.beta1",+ "prerelease": True,+ "release_status": "pre",+ "assets": [+ {+ "name": "JiuwenSwarm-setup-0.2.3.beta1.exe",+ "url": "https://example.test/JiuwenSwarm-setup-0.2.3.beta1.exe",+ },+ ],+ },+ ],+ },+ )++ release = source._fetch_newest_from_list("https://example.test/releases", {})++ assert release is not None+ assert release.version == "0.2.3.beta1"+ assert release.prerelease is True+++def test_desktop_check_matches_beta_windows_installer(monkeypatch):+ from jiuwenswarm.common.version_source import ReleaseAsset, ReleaseInfo++ monkeypatch.delattr(sys, "frozen", raising=False)+ monkeypatch.setenv("JIUWENSWARM_DESKTOP", "1")++ class FakeSource:+ def fetch_latest(self):+ return ReleaseInfo(+ version="0.2.3.beta1",+ assets=[+ ReleaseAsset(+ name="JiuwenSwarm-setup-0.2.2.exe",+ download_url="https://example.test/JiuwenSwarm-setup-0.2.2.exe",+ ),+ ReleaseAsset(+ name="JiuwenSwarm-setup-0.2.3.beta1.exe",+ download_url="https://example.test/JiuwenSwarm-setup-0.2.3.beta1.exe",+ ),+ ],+ source_type="gitcode",+ )++ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(updater, "__version__", "0.2.2")+ monkeypatch.setattr(+ updater.UpdaterService,+ "_create_version_source",+ staticmethod(lambda config: FakeSource()),+ )+ monkeypatch.setattr(+ updater,+ "get_config_raw",+ lambda: {+ "updater": {+ "enabled": True,+ "desktop_release_api_type": "gitcode",+ }+ },+ )++ status = updater.UpdaterService().check(manual=True)++ assert status["latest_version"] == "0.2.3.beta1"+ assert status["matched_asset"] == "JiuwenSwarm-setup-0.2.3.beta1.exe"